blob: 63a0ce635749606cf30a6a199524a6c9791a3316 [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
dchengc7eeda422015-12-26 03:56:485#include <utility>
6
mmenkefd9d15c2017-06-29 13:45:547// This must be before Windows headers
[email protected]ea224582008-12-07 20:25:468#include "build/build_config.h"
9
[email protected]9396b252008-09-29 17:29:3810#if defined(OS_WIN)
robliaoeb9bfd642017-05-18 17:35:1611#include <objbase.h>
[email protected]aa84a7e2012-03-15 21:29:0612#include <shlobj.h>
Fan Yang5a88d5d2017-10-24 01:14:2913#include <windows.h>
Robert Liaoc88f99d12017-10-17 21:48:3314#include <wrl/client.h>
[email protected]9396b252008-09-29 17:29:3815#endif
16
tbansalea2fb8c2015-05-22 22:23:0017#include <stdint.h>
18
initial.commit586acc5fe2008-07-26 22:42:5219#include <algorithm>
avibf0746c2015-12-09 19:53:1420#include <limits>
Devlin Cronine4bcb40e2018-06-05 18:02:4721#include <memory>
initial.commit586acc5fe2008-07-26 22:42:5222
nharperb7441ef2016-01-25 23:54:1423#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3824#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5825#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4726#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2927#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0728#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2829#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0130#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4531#include "base/location.h"
Avi Drissman13fc8932015-12-20 04:40:4632#include "base/macros.h"
[email protected]084262c2011-12-01 21:12:4733#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2234#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5235#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5036#include "base/power_monitor/power_monitor.h"
37#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2938#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4539#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5040#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5541#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2242#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2243#include "base/strings/string_util.h"
44#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0545#include "base/strings/utf_string_conversions.h"
Devlin Cronine4bcb40e2018-06-05 18:02:4746#include "base/test/metrics/histogram_tester.h"
Emily Stark4cfecf072017-08-08 01:05:5147#include "base/test/scoped_feature_list.h"
gabf767595f2016-05-11 18:50:3548#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0149#include "base/values.h"
mmenkefd9d15c2017-06-29 13:45:5450#include "build/buildflag.h"
mmenkecbc2b712014-10-09 20:29:0751#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0752#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0753#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2555#include "net/base/load_timing_info.h"
56#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0657#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5258#include "net/base/net_module.h"
Lily Houghton582d4622018-01-22 22:43:4059#include "net/base/proxy_server.h"
[email protected]2ca01e52013-10-31 22:05:1960#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3661#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2862#include "net/base/upload_bytes_element_reader.h"
63#include "net/base/upload_data_stream.h"
64#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4465#include "net/base/url_util.h"
rsleevid6de8302016-06-21 01:33:2066#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4767#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3668#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1169#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2470#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3671#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1072#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1173#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0674#include "net/cookies/cookie_monster.h"
75#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5276#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5377#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3878#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5279#include "net/http/http_cache.h"
80#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1981#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2582#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2183#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3684#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0085#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0086#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1987#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5188#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4689#include "net/log/test_net_log_entry.h"
90#include "net/log/test_net_log_util.h"
Scott Violet0caaaf432018-03-24 00:43:5991#include "net/net_buildflags.h"
Lily Houghtonffe89daa02018-03-09 18:30:0392#include "net/proxy_resolution/proxy_resolution_service.h"
zhongyi18ddddd2017-02-03 19:06:3693#include "net/quic/chromium/mock_crypto_client_stream_factory.h"
94#include "net/quic/chromium/quic_server_info.h"
95#include "net/socket/socket_test_util.h"
[email protected]c3456bb2011-12-12 22:22:1996#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1497#include "net/ssl/channel_id_service.h"
David Benjamin76a40ad2018-02-24 22:22:0898#include "net/ssl/client_cert_identity_test_util.h"
nharperb7441ef2016-01-25 23:54:1499#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:57100#include "net/ssl/ssl_connection_status_flags.h"
David Benjamin76a40ad2018-02-24 22:22:08101#include "net/ssl/ssl_private_key.h"
tommycli59a63432015-11-06 00:10:55102#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:14103#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:11104#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36105#include "net/test/embedded_test_server/embedded_test_server.h"
106#include "net/test/embedded_test_server/http_request.h"
107#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01108#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21109#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43110#include "net/test/test_data_directory.h"
Bence Béky98447b12018-05-08 03:14:01111#include "net/test/test_with_scoped_task_environment.h"
mmenkefb18c772015-09-30 22:22:50112#include "net/test/url_request/url_request_failed_job.h"
Carlos ILaef65d62018-06-04 21:24:13113#include "net/test/url_request/url_request_mock_http_job.h"
rhalavatib7bd7c792017-04-27 05:25:16114#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34115#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43116#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52117#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50118#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14119#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58120#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50121#include "net/url_request/url_request_intercepting_job_factory.h"
122#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49123#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51124#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47125#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44126#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01127#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52128#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15129#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52130
Eric Romanefddd0a2017-10-10 02:14:25131#if defined(OS_FUCHSIA)
132#define USE_BUILTIN_CERT_VERIFIER
133#endif
134
brettwa1228ebb2016-10-28 03:51:34135#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55136#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29137#include "net/url_request/file_protocol_handler.h"
138#include "net/url_request/url_request_file_dir_job.h"
139#endif
140
brettwa1228ebb2016-10-28 03:51:34141#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47142#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29143#include "net/url_request/ftp_protocol_handler.h"
144#endif
145
[email protected]dffe8242012-03-20 15:14:27146#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48147#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27148#endif
149
mmenkefd9d15c2017-06-29 13:45:54150#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27151#include "net/network_error_logging/network_error_logging_service.h"
Julia Tuttle91a655d2018-01-26 18:03:03152#include "net/reporting/reporting_policy.h"
mmenkefd9d15c2017-06-29 13:45:54153#include "net/reporting/reporting_service.h"
154#endif // BUILDFLAG(ENABLE_REPORTING)
155
Matt Muellerfb271992018-01-30 18:10:48156#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25157#include "net/cert/cert_net_fetcher.h"
158#include "net/cert_net/cert_net_fetcher_impl.h"
159#endif
160
161#if defined(USE_NSS_CERTS)
162#include "net/cert_net/nss_ocsp.h"
163#endif
164
robpercival214763f2016-07-01 23:27:01165using net::test::IsError;
166using net::test::IsOk;
167
[email protected]ad65a3e2013-12-25 18:18:01168using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33169using base::Time;
halton.huoe4e45742014-12-08 07:55:46170using std::string;
[email protected]e1acf6f2008-10-27 20:43:33171
[email protected]7461a402011-03-24 23:19:51172namespace net {
173
initial.commit586acc5fe2008-07-26 22:42:52174namespace {
175
Martijn Croonenb1383da2017-10-11 11:56:35176namespace test_default {
177#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35178}
179
[email protected]42cba2fb2013-03-29 19:58:57180const base::string16 kChrome(ASCIIToUTF16("chrome"));
181const base::string16 kSecret(ASCIIToUTF16("secret"));
182const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44183
mmenke9f2ec60c2015-06-01 20:59:47184const base::FilePath::CharType kTestFilePath[] =
185 FILE_PATH_LITERAL("net/data/url_request_unittest");
186
Sergey Ulanovc4580e72017-09-13 23:30:11187#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
188 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47189// Test file used in most FTP tests.
190const char kFtpTestFile[] = "BullRunSpeech.txt";
191#endif
192
[email protected]2bba3252013-04-08 19:50:59193// Tests load timing information in the case a fresh connection was used, with
194// no proxy.
[email protected]cba24642014-08-15 20:49:59195void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25196 int connect_timing_flags) {
197 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19198 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25199
200 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
201 EXPECT_FALSE(load_timing_info.request_start.is_null());
202
203 EXPECT_LE(load_timing_info.request_start,
204 load_timing_info.connect_timing.connect_start);
205 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
206 connect_timing_flags);
207 EXPECT_LE(load_timing_info.connect_timing.connect_end,
208 load_timing_info.send_start);
209 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
210 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
211
[email protected]58e32bb2013-01-21 18:23:25212 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
213 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
214}
215
[email protected]2bba3252013-04-08 19:50:59216// Same as above, but with proxy times.
217void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59218 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59219 int connect_timing_flags) {
220 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19221 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59222
223 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
224 EXPECT_FALSE(load_timing_info.request_start.is_null());
225
226 EXPECT_LE(load_timing_info.request_start,
227 load_timing_info.proxy_resolve_start);
228 EXPECT_LE(load_timing_info.proxy_resolve_start,
229 load_timing_info.proxy_resolve_end);
230 EXPECT_LE(load_timing_info.proxy_resolve_end,
231 load_timing_info.connect_timing.connect_start);
232 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
233 connect_timing_flags);
234 EXPECT_LE(load_timing_info.connect_timing.connect_end,
235 load_timing_info.send_start);
236 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
237 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
238}
239
240// Same as above, but with a reused socket and proxy times.
241void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59242 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59243 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19244 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59245
246 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
247 EXPECT_FALSE(load_timing_info.request_start.is_null());
248
249 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
250
251 EXPECT_LE(load_timing_info.request_start,
252 load_timing_info.proxy_resolve_start);
253 EXPECT_LE(load_timing_info.proxy_resolve_start,
254 load_timing_info.proxy_resolve_end);
255 EXPECT_LE(load_timing_info.proxy_resolve_end,
256 load_timing_info.send_start);
257 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
258 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
259}
260
brettwa1228ebb2016-10-28 03:51:34261#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25262// Tests load timing information in the case of a cache hit, when no cache
263// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17264base::StringPiece TestNetResourceProvider(int key) {
265 return "header";
266}
267
268void FillBuffer(char* buffer, size_t len) {
269 static bool called = false;
270 if (!called) {
271 called = true;
272 int seed = static_cast<int>(Time::Now().ToInternalValue());
273 srand(seed);
274 }
275
276 for (size_t i = 0; i < len; i++) {
277 buffer[i] = static_cast<char>(rand());
278 if (!buffer[i])
279 buffer[i] = 'g';
280 }
281}
xunjielia6888202015-04-14 21:34:25282#endif
[email protected]e3a85452013-11-14 01:46:17283
[email protected]3b23a222013-05-15 21:33:25284void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59285 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25286 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19287 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25288
289 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
290 EXPECT_FALSE(load_timing_info.request_start.is_null());
291
292 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
293 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
294 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
295 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
296
297 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
298 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
299}
300
Sergey Ulanovc4580e72017-09-13 23:30:11301#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
302 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25303// Tests load timing in the case that there is no HTTP response. This can be
304// used to test in the case of errors or non-HTTP requests.
305void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59306 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25307 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19308 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25309
310 // Only the request times should be non-null.
311 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
312 EXPECT_FALSE(load_timing_info.request_start.is_null());
313
314 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
315
316 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
317 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
318 EXPECT_TRUE(load_timing_info.send_start.is_null());
319 EXPECT_TRUE(load_timing_info.send_end.is_null());
320 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
321}
xunjielia6888202015-04-14 21:34:25322#endif
[email protected]58e32bb2013-01-21 18:23:25323
mmenkefb18c772015-09-30 22:22:50324// Test power monitor source that can simulate entering suspend mode. Can't use
325// the one in base/ because it insists on bringing its own MessageLoop.
326class TestPowerMonitorSource : public base::PowerMonitorSource {
327 public:
Chris Watkins7a41d3552017-12-01 02:13:27328 TestPowerMonitorSource() = default;
329 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50330
331 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
332
333 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
334
335 bool IsOnBatteryPowerImpl() override { return false; }
336
337 private:
338 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
339};
340
mmenkeed0498b2015-12-08 23:20:42341// Job that allows monitoring of its priority.
342class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
343 public:
344 // The latest priority of the job is always written to |request_priority_|.
345 PriorityMonitoringURLRequestJob(URLRequest* request,
346 NetworkDelegate* network_delegate,
347 RequestPriority* request_priority)
348 : URLRequestTestJob(request, network_delegate),
349 request_priority_(request_priority) {
350 *request_priority_ = DEFAULT_PRIORITY;
351 }
352
353 void SetPriority(RequestPriority priority) override {
354 *request_priority_ = priority;
355 URLRequestTestJob::SetPriority(priority);
356 }
357
358 private:
359 RequestPriority* const request_priority_;
360};
361
[email protected]71c64f62008-11-15 04:36:51362// Do a case-insensitive search through |haystack| for |needle|.
363bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50364 std::string::const_iterator it = std::search(
365 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
366 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51367 return it != haystack.end();
368}
369
danakj8522a25b2016-04-16 00:17:36370std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
371 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28372 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48373 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23374}
375
[email protected]96adadb2010-08-28 01:16:17376// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51377void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17378 // -1 means unknown. 0 means no encryption.
379 EXPECT_GT(ssl_info.security_bits, 0);
380
381 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14382 uint16_t cipher_suite =
383 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29384 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17385}
386
[email protected]79e1fd62013-06-20 06:50:04387void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
388 const GURL& host_url) {
389 std::string sent_value;
390
391 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
392 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
393
394 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
395 EXPECT_EQ("keep-alive", sent_value);
396}
397
[email protected]dc5a5cf2012-09-26 02:49:30398// A network delegate that allows the user to choose a subset of request stages
399// to block in. When blocking, the delegate can do one of the following:
400// * synchronously return a pre-specified error code, or
401// * asynchronously return that value via an automatically called callback,
402// or
403// * block and wait for the user to do a callback.
404// Additionally, the user may also specify a redirect URL -- then each request
405// with the current URL different from the redirect target will be redirected
406// to that target, in the on-before-URL-request stage, independent of whether
407// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12408class BlockingNetworkDelegate : public TestNetworkDelegate {
409 public:
[email protected]dc5a5cf2012-09-26 02:49:30410 // Stages in which the delegate can block.
411 enum Stage {
[email protected]9045b8822012-01-13 20:35:35412 NOT_BLOCKED = 0,
413 ON_BEFORE_URL_REQUEST = 1 << 0,
414 ON_BEFORE_SEND_HEADERS = 1 << 1,
415 ON_HEADERS_RECEIVED = 1 << 2,
416 ON_AUTH_REQUIRED = 1 << 3
417 };
418
[email protected]dc5a5cf2012-09-26 02:49:30419 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59420 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30421 enum BlockMode {
422 SYNCHRONOUS, // No callback, returns specified return values.
423 AUTO_CALLBACK, // |this| posts a task to run the callback using the
424 // specified return codes.
425 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
426 // |auth_retval_| are ignored. In every blocking stage the
427 // message loop is quit.
428 };
429
430 // Creates a delegate which does not block at all.
431 explicit BlockingNetworkDelegate(BlockMode block_mode);
432
Wez2a31b222018-06-07 22:07:15433 // Runs the message loop until the delegate blocks.
434 void RunUntilBlocked();
435
[email protected]dc5a5cf2012-09-26 02:49:30436 // For users to trigger a callback returning |response|.
437 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
438 // Only call if |block_mode_| == USER_CALLBACK.
439 void DoCallback(int response);
440 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
441
442 // Setters.
443 void set_retval(int retval) {
444 ASSERT_NE(USER_CALLBACK, block_mode_);
445 ASSERT_NE(ERR_IO_PENDING, retval);
446 ASSERT_NE(OK, retval);
447 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35448 }
449
[email protected]dc5a5cf2012-09-26 02:49:30450 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
451 // |auth_credentials_| will be passed with the response.
452 void set_auth_retval(AuthRequiredResponse auth_retval) {
453 ASSERT_NE(USER_CALLBACK, block_mode_);
454 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
455 auth_retval_ = auth_retval;
456 }
457 void set_auth_credentials(const AuthCredentials& auth_credentials) {
458 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35459 }
460
[email protected]dc5a5cf2012-09-26 02:49:30461 void set_redirect_url(const GURL& url) {
462 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35463 }
464
[email protected]dc5a5cf2012-09-26 02:49:30465 void set_block_on(int block_on) {
466 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35467 }
468
[email protected]dc5a5cf2012-09-26 02:49:30469 // Allows the user to check in which state did we block.
470 Stage stage_blocked_for_callback() const {
471 EXPECT_EQ(USER_CALLBACK, block_mode_);
472 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35473 }
474
475 private:
Wez2a31b222018-06-07 22:07:15476 void OnBlocked();
477
David Benjamind1f287bf2018-06-12 01:57:20478 void RunCallback(int response, CompletionOnceCallback callback);
479 void RunAuthCallback(AuthRequiredResponse response, AuthCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30480
[email protected]9045b8822012-01-13 20:35:35481 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20482 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20483 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:20484 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35485
ryansturm2343cb62016-06-15 01:09:00486 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20487 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:00488 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35489
dchengb03027d2014-10-21 12:00:20490 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35491 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20492 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32493 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16494 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13495 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35496
dchengb03027d2014-10-21 12:00:20497 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35498 URLRequest* request,
499 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20500 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:13501 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35502
[email protected]dc5a5cf2012-09-26 02:49:30503 // Resets the callbacks and |stage_blocked_for_callback_|.
504 void Reset();
[email protected]9045b8822012-01-13 20:35:35505
[email protected]dc5a5cf2012-09-26 02:49:30506 // Checks whether we should block in |stage|. If yes, returns an error code
507 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
David Benjamind1f287bf2018-06-12 01:57:20508 int MaybeBlockStage(Stage stage, CompletionOnceCallback callback);
[email protected]dc5a5cf2012-09-26 02:49:30509
510 // Configuration parameters, can be adjusted by public methods:
511 const BlockMode block_mode_;
512
513 // Values returned on blocking stages when mode is SYNCHRONOUS or
514 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
515 int retval_; // To be returned in non-auth stages.
516 AuthRequiredResponse auth_retval_;
517
[email protected]5f714132014-03-26 10:41:16518 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30519 int block_on_; // Bit mask: in which stages to block.
520
521 // |auth_credentials_| will be copied to |*target_auth_credential_| on
522 // callback.
523 AuthCredentials auth_credentials_;
524 AuthCredentials* target_auth_credentials_;
525
526 // Internal variables, not set by not the user:
527 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
528 // USER_CALLBACK).
529 Stage stage_blocked_for_callback_;
530
531 // Callback objects stored during blocking stages.
David Benjamind1f287bf2018-06-12 01:57:20532 CompletionOnceCallback callback_;
[email protected]9045b8822012-01-13 20:35:35533 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30534
Wez2a31b222018-06-07 22:07:15535 // Closure to run to exit RunUntilBlocked().
536 base::OnceClosure on_blocked_;
537
[email protected]dc5a5cf2012-09-26 02:49:30538 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
539
540 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35541};
542
[email protected]dc5a5cf2012-09-26 02:49:30543BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
544 : block_mode_(block_mode),
545 retval_(OK),
546 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
547 block_on_(0),
548 target_auth_credentials_(NULL),
549 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32550 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30551}
552
Wez2a31b222018-06-07 22:07:15553void BlockingNetworkDelegate::RunUntilBlocked() {
554 base::RunLoop run_loop;
555 on_blocked_ = run_loop.QuitClosure();
556 run_loop.Run();
557}
558
[email protected]dc5a5cf2012-09-26 02:49:30559void BlockingNetworkDelegate::DoCallback(int response) {
560 ASSERT_EQ(USER_CALLBACK, block_mode_);
561 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
562 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20563 CompletionOnceCallback callback = std::move(callback_);
[email protected]dc5a5cf2012-09-26 02:49:30564 Reset();
Wez2a31b222018-06-07 22:07:15565
566 // |callback| may trigger completion of a request, so post it as a task, so
567 // it will run under a subsequent TestDelegate::RunUntilComplete() loop.
568 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20569 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
570 weak_factory_.GetWeakPtr(), response,
571 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30572}
573
574void BlockingNetworkDelegate::DoAuthCallback(
575 NetworkDelegate::AuthRequiredResponse response) {
576 ASSERT_EQ(USER_CALLBACK, block_mode_);
577 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
David Benjamind1f287bf2018-06-12 01:57:20578 AuthCallback auth_callback = std::move(auth_callback_);
[email protected]dc5a5cf2012-09-26 02:49:30579 Reset();
David Benjamind1f287bf2018-06-12 01:57:20580 RunAuthCallback(response, std::move(auth_callback));
[email protected]dc5a5cf2012-09-26 02:49:30581}
582
Wez2a31b222018-06-07 22:07:15583void BlockingNetworkDelegate::OnBlocked() {
584 // If this fails due to |on_blocked_| being null then OnBlocked() was run by
585 // a RunLoop other than RunUntilBlocked(), indicating a bug in the calling
586 // test.
587 std::move(on_blocked_).Run();
588}
589
[email protected]dc5a5cf2012-09-26 02:49:30590void BlockingNetworkDelegate::RunCallback(int response,
David Benjamind1f287bf2018-06-12 01:57:20591 CompletionOnceCallback callback) {
592 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30593}
594
595void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
David Benjamind1f287bf2018-06-12 01:57:20596 AuthCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30597 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
598 ASSERT_TRUE(target_auth_credentials_ != NULL);
599 *target_auth_credentials_ = auth_credentials_;
600 }
David Benjamind1f287bf2018-06-12 01:57:20601 std::move(callback).Run(response);
[email protected]dc5a5cf2012-09-26 02:49:30602}
603
David Benjamind1f287bf2018-06-12 01:57:20604int BlockingNetworkDelegate::OnBeforeURLRequest(URLRequest* request,
605 CompletionOnceCallback callback,
606 GURL* new_url) {
[email protected]dc5a5cf2012-09-26 02:49:30607 if (redirect_url_ == request->url())
608 return OK; // We've already seen this request and redirected elsewhere.
609
David Benjamind1f287bf2018-06-12 01:57:20610 // TestNetworkDelegate always completes synchronously.
611 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
612 request, base::NullCallback(), new_url));
[email protected]dc5a5cf2012-09-26 02:49:30613
614 if (!redirect_url_.is_empty())
615 *new_url = redirect_url_;
616
David Benjamind1f287bf2018-06-12 01:57:20617 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30618}
619
ryansturm2343cb62016-06-15 01:09:00620int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30621 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20622 CompletionOnceCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30623 HttpRequestHeaders* headers) {
David Benjamind1f287bf2018-06-12 01:57:20624 // TestNetworkDelegate always completes synchronously.
625 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
626 request, base::NullCallback(), headers));
[email protected]dc5a5cf2012-09-26 02:49:30627
David Benjamind1f287bf2018-06-12 01:57:20628 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30629}
630
631int BlockingNetworkDelegate::OnHeadersReceived(
632 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:20633 CompletionOnceCallback callback,
[email protected]507af8f2012-10-20 00:42:32634 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16635 scoped_refptr<HttpResponseHeaders>* override_response_headers,
636 GURL* allowed_unsafe_redirect_url) {
David Benjamind1f287bf2018-06-12 01:57:20637 // TestNetworkDelegate always completes synchronously.
638 CHECK_NE(ERR_IO_PENDING,
639 TestNetworkDelegate::OnHeadersReceived(
640 request, base::NullCallback(), original_response_headers,
641 override_response_headers, allowed_unsafe_redirect_url));
[email protected]dc5a5cf2012-09-26 02:49:30642
David Benjamind1f287bf2018-06-12 01:57:20643 return MaybeBlockStage(ON_HEADERS_RECEIVED, std::move(callback));
[email protected]dc5a5cf2012-09-26 02:49:30644}
645
646NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
647 URLRequest* request,
648 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:20649 AuthCallback callback,
[email protected]dc5a5cf2012-09-26 02:49:30650 AuthCredentials* credentials) {
David Benjamind1f287bf2018-06-12 01:57:20651 // TestNetworkDelegate always completes synchronously.
652 CHECK_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING,
653 TestNetworkDelegate::OnAuthRequired(
654 request, auth_info, base::NullCallback(), credentials));
[email protected]dc5a5cf2012-09-26 02:49:30655 // Check that the user has provided callback for the previous blocked stage.
656 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
657
658 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
659 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
660 }
661
662 target_auth_credentials_ = credentials;
663
664 switch (block_mode_) {
665 case SYNCHRONOUS:
666 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
667 *target_auth_credentials_ = auth_credentials_;
668 return auth_retval_;
669
670 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45671 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20672 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunAuthCallback,
673 weak_factory_.GetWeakPtr(), auth_retval_,
674 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30675 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
676
677 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20678 auth_callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30679 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
Wez2a31b222018-06-07 22:07:15680 // We may reach here via a callback prior to RunUntilBlocked(), so post
681 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45682 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15683 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
684 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30685 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
686 }
687 NOTREACHED();
688 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
689}
690
691void BlockingNetworkDelegate::Reset() {
692 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
693 stage_blocked_for_callback_ = NOT_BLOCKED;
694 callback_.Reset();
695 auth_callback_.Reset();
696}
697
698int BlockingNetworkDelegate::MaybeBlockStage(
699 BlockingNetworkDelegate::Stage stage,
David Benjamind1f287bf2018-06-12 01:57:20700 CompletionOnceCallback callback) {
[email protected]dc5a5cf2012-09-26 02:49:30701 // Check that the user has provided callback for the previous blocked stage.
702 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
703
704 if ((block_on_ & stage) == 0) {
705 return OK;
706 }
707
708 switch (block_mode_) {
709 case SYNCHRONOUS:
710 EXPECT_NE(OK, retval_);
711 return retval_;
712
713 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45714 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamind1f287bf2018-06-12 01:57:20715 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::RunCallback,
716 weak_factory_.GetWeakPtr(), retval_,
717 std::move(callback)));
[email protected]dc5a5cf2012-09-26 02:49:30718 return ERR_IO_PENDING;
719
720 case USER_CALLBACK:
David Benjamind1f287bf2018-06-12 01:57:20721 callback_ = std::move(callback);
[email protected]dc5a5cf2012-09-26 02:49:30722 stage_blocked_for_callback_ = stage;
Wez2a31b222018-06-07 22:07:15723 // We may reach here via a callback prior to RunUntilBlocked(), so post
724 // a task to fetch and run the |on_blocked_| closure.
skyostil4891b25b2015-06-11 11:43:45725 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:15726 FROM_HERE, base::BindOnce(&BlockingNetworkDelegate::OnBlocked,
727 weak_factory_.GetWeakPtr()));
[email protected]dc5a5cf2012-09-26 02:49:30728 return ERR_IO_PENDING;
729 }
730 NOTREACHED();
731 return 0;
732}
733
[email protected]d5a4dd62012-05-23 01:41:04734class TestURLRequestContextWithProxy : public TestURLRequestContext {
735 public:
736 // Does not own |delegate|.
737 TestURLRequestContextWithProxy(const std::string& proxy,
738 NetworkDelegate* delegate)
739 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59740 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49741 ProxyResolutionService::CreateFixed(proxy,
742 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04743 set_network_delegate(delegate);
744 Init();
745 }
Chris Watkins7a41d3552017-12-01 02:13:27746 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04747};
748
stefanocsbd5be5202016-06-10 03:37:55749// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01750// URI and report to be sent.
751class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55752 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01753 public:
Chris Watkins7a41d3552017-12-01 02:13:27754 MockCertificateReportSender() = default;
755 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01756
meacer5d4dc5a2017-04-27 20:37:48757 void Send(const GURL& report_uri,
758 base::StringPiece content_type,
759 base::StringPiece report,
760 const base::Callback<void()>& success_callback,
761 const base::Callback<void(const GURL&, int, int)>& error_callback)
762 override {
estark06e0dac2015-08-07 21:56:01763 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44764 report.CopyToString(&latest_report_);
765 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01766 }
estark06e0dac2015-08-07 21:56:01767 const GURL& latest_report_uri() { return latest_report_uri_; }
768 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44769 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01770
771 private:
772 GURL latest_report_uri_;
773 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44774 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01775};
776
estarkcd39c11f2015-10-19 19:46:36777class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
778 public:
779 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
780};
781
dadrian612337a2016-07-20 22:36:58782// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
783// This is needed because after the certificate failure, the URLRequest will
784// retry the connection, and return a partial SSLInfo with a cached cert status.
785// The partial SSLInfo does not have the OCSP information filled out.
786class OCSPErrorTestDelegate : public TestDelegate {
787 public:
788 void OnSSLCertificateError(URLRequest* request,
789 const SSLInfo& ssl_info,
790 bool fatal) override {
791 ssl_info_ = ssl_info;
792 on_ssl_certificate_error_called_ = true;
793 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
794 }
795
796 bool on_ssl_certificate_error_called() {
797 return on_ssl_certificate_error_called_;
798 }
799
800 SSLInfo ssl_info() { return ssl_info_; }
801
802 private:
803 bool on_ssl_certificate_error_called_ = false;
804 SSLInfo ssl_info_;
805};
806
[email protected]d5a4dd62012-05-23 01:41:04807} // namespace
808
[email protected]a592c0432012-12-01 18:10:29809// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01810class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00811 public:
fdorayf33fede2017-05-11 21:18:10812 URLRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:09813 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25814 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50815 job_factory_impl_ = new URLRequestJobFactoryImpl();
816 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50817 }
bengr1bf8e942014-11-07 01:36:50818
dcheng67be2b1f2014-10-27 21:47:29819 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18820 // URLRequestJobs may post clean-up tasks on destruction.
821 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35822
823 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18824 }
[email protected]87a09a92011-07-14 15:50:50825
dcheng2339883c2014-12-23 00:23:05826 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50827 SetUpFactory();
828 default_context_.set_job_factory(job_factory_.get());
829 default_context_.Init();
830 PlatformTest::SetUp();
831 }
832
833 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20834 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04835 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34836#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50837 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19838 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07839 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50840#endif
841 }
842
843 TestNetworkDelegate* default_network_delegate() {
844 return &default_network_delegate_;
845 }
846
847 const TestURLRequestContext& default_context() const {
848 return default_context_;
849 }
850
851
[email protected]3c5ca8c2011-09-29 01:14:51852 // Adds the TestJobInterceptor to the default context.
853 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23854 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20855 job_factory_impl_->SetProtocolHandler("http", nullptr);
856 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36857 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23858 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51859 }
860
Sergey Ulanov2e49f492017-09-14 19:37:51861 // Creates a temp test file and writes |data| to the file. The file will be
862 // deleted after the test completes.
863 void CreateTestFile(const char* data,
864 size_t data_size,
865 base::FilePath* test_file) {
866 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
867 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
868 // now, Mac and Android bots return a path with a symbolic link.
869 base::FilePath absolute_temp_dir =
870 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
871
872 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
873 ASSERT_EQ(static_cast<int>(data_size),
874 base::WriteFile(*test_file, data, data_size));
875 }
876
[email protected]87a09a92011-07-14 15:50:50877 protected:
vishal.b62985ca92015-04-17 08:45:51878 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24879 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50880 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36881 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09882 TestURLRequestContext default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51883 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48884};
885
satoruxddac0442017-05-29 06:06:18886// This NetworkDelegate is picky about what files are accessible. Only
887// whitelisted files are allowed.
888class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
889 public:
Chris Watkins7a41d3552017-12-01 02:13:27890 CookieBlockingNetworkDelegate() = default;
891 ;
satoruxddac0442017-05-29 06:06:18892
893 // Adds |directory| to the access white list.
894 void AddToWhitelist(const base::FilePath& directory) {
895 whitelist_.insert(directory);
896 }
897
898 private:
899 // Returns true if |path| matches the white list.
900 bool OnCanAccessFileInternal(const base::FilePath& path) const {
901 for (const auto& directory : whitelist_) {
902 if (directory == path || directory.IsParent(path))
903 return true;
904 }
905 return false;
906 }
907
908 // Returns true only if both |original_path| and |absolute_path| match the
909 // white list.
910 bool OnCanAccessFile(const URLRequest& request,
911 const base::FilePath& original_path,
912 const base::FilePath& absolute_path) const override {
913 return (OnCanAccessFileInternal(original_path) &&
914 OnCanAccessFileInternal(absolute_path));
915 }
916
917 std::set<base::FilePath> whitelist_;
918
919 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
920};
921
[email protected]316c1e5e2012-09-12 15:17:44922TEST_F(URLRequestTest, AboutBlankTest) {
923 TestDelegate d;
924 {
rhalavatib7bd7c792017-04-27 05:25:16925 std::unique_ptr<URLRequest> r(
926 default_context_.CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
927 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44928
[email protected]f7022f32014-08-21 16:32:19929 r->Start();
930 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44931
Wez2a31b222018-06-07 22:07:15932 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44933
[email protected]f7022f32014-08-21 16:32:19934 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44935 EXPECT_FALSE(d.received_data_before_response());
936 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19937 EXPECT_EQ("", r->GetSocketAddress().host());
938 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04939
940 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19941 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44942 }
943}
944
945TEST_F(URLRequestTest, DataURLImageTest) {
946 TestDelegate d;
947 {
948 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36949 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
950 GURL("data:image/png;base64,"
951 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
952 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
953 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
954 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
955 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
956 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
957 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
958 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
959 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
960 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
961 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
962 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
963 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
964 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
965 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
966 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
967 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
968 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
969 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16970 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44971
[email protected]f7022f32014-08-21 16:32:19972 r->Start();
973 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44974
Wez2a31b222018-06-07 22:07:15975 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:44976
[email protected]f7022f32014-08-21 16:32:19977 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44978 EXPECT_FALSE(d.received_data_before_response());
979 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19980 EXPECT_EQ("", r->GetSocketAddress().host());
981 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04982
983 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19984 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44985 }
986}
987
brettwa1228ebb2016-10-28 03:51:34988#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44989TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51990 const char kTestFileContent[] = "Hello";
991 base::FilePath test_file;
992 ASSERT_NO_FATAL_FAILURE(
993 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04994
Sergey Ulanov2e49f492017-09-14 19:37:51995 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44996
997 TestDelegate d;
998 {
rhalavatib7bd7c792017-04-27 05:25:16999 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511000 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441001
[email protected]f7022f32014-08-21 16:32:191002 r->Start();
1003 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441004
Wez2a31b222018-06-07 22:07:151005 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441006
[email protected]f7022f32014-08-21 16:32:191007 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441008 EXPECT_EQ(1, d.response_started_count());
1009 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:511010 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:191011 EXPECT_EQ("", r->GetSocketAddress().host());
1012 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:041013
1014 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:191015 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:441016 }
1017}
1018
[email protected]ba40bb762012-12-17 07:11:041019TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:511020 const char kTestFileContent[] = "Hello";
1021 base::FilePath test_file;
1022 ASSERT_NO_FATAL_FAILURE(
1023 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
1024
1025 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:041026
1027 TestDelegate d;
1028 {
rhalavatib7bd7c792017-04-27 05:25:161029 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:511030 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:041031
[email protected]f7022f32014-08-21 16:32:191032 r->Start();
1033 EXPECT_TRUE(r->is_pending());
1034 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:041035 }
[email protected]79e1fd62013-06-20 06:50:041036 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:041037 // destroyed.
[email protected]255620da2013-08-19 13:14:291038 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041039}
1040
[email protected]316c1e5e2012-09-12 15:17:441041TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1042 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361043 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441044 FillBuffer(buffer.get(), buffer_size);
1045
Sergey Ulanov2e49f492017-09-14 19:37:511046 base::FilePath test_file;
1047 ASSERT_NO_FATAL_FAILURE(
1048 CreateTestFile(buffer.get(), buffer_size, &test_file));
1049 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441050
1051 const size_t first_byte_position = 500;
1052 const size_t last_byte_position = buffer_size - first_byte_position;
1053 const size_t content_length = last_byte_position - first_byte_position + 1;
1054 std::string partial_buffer_string(buffer.get() + first_byte_position,
1055 buffer.get() + last_byte_position + 1);
1056
1057 TestDelegate d;
1058 {
rhalavatib7bd7c792017-04-27 05:25:161059 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1060 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441061
1062 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381063 headers.SetHeader(
1064 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591065 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381066 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191067 r->SetExtraRequestHeaders(headers);
1068 r->Start();
1069 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441070
Wez2a31b222018-06-07 22:07:151071 d.RunUntilComplete();
1072
[email protected]f7022f32014-08-21 16:32:191073 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441074 EXPECT_EQ(1, d.response_started_count());
1075 EXPECT_FALSE(d.received_data_before_response());
1076 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1077 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1078 EXPECT_TRUE(partial_buffer_string == d.data_received());
1079 }
[email protected]316c1e5e2012-09-12 15:17:441080}
1081
1082TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1083 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361084 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441085 FillBuffer(buffer.get(), buffer_size);
1086
Sergey Ulanov2e49f492017-09-14 19:37:511087 base::FilePath test_file;
1088 ASSERT_NO_FATAL_FAILURE(
1089 CreateTestFile(buffer.get(), buffer_size, &test_file));
1090 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441091
1092 const size_t first_byte_position = 500;
1093 const size_t last_byte_position = buffer_size - 1;
1094 const size_t content_length = last_byte_position - first_byte_position + 1;
1095 std::string partial_buffer_string(buffer.get() + first_byte_position,
1096 buffer.get() + last_byte_position + 1);
1097
1098 TestDelegate d;
1099 {
rhalavatib7bd7c792017-04-27 05:25:161100 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1101 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441102
1103 HttpRequestHeaders headers;
1104 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591105 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381106 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191107 r->SetExtraRequestHeaders(headers);
1108 r->Start();
1109 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441110
[email protected]255620da2013-08-19 13:14:291111 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191112 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441113 EXPECT_EQ(1, d.response_started_count());
1114 EXPECT_FALSE(d.received_data_before_response());
1115 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1116 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1117 EXPECT_TRUE(partial_buffer_string == d.data_received());
1118 }
[email protected]316c1e5e2012-09-12 15:17:441119}
1120
1121TEST_F(URLRequestTest, FileTestMultipleRanges) {
1122 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361123 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441124 FillBuffer(buffer.get(), buffer_size);
1125
Sergey Ulanov2e49f492017-09-14 19:37:511126 base::FilePath test_file;
1127 ASSERT_NO_FATAL_FAILURE(
1128 CreateTestFile(buffer.get(), buffer_size, &test_file));
1129 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441130
1131 TestDelegate d;
1132 {
rhalavatib7bd7c792017-04-27 05:25:161133 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1134 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441135
1136 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381137 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191138 r->SetExtraRequestHeaders(headers);
1139 r->Start();
1140 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441141
Wez2a31b222018-06-07 22:07:151142 d.RunUntilComplete();
1143
[email protected]316c1e5e2012-09-12 15:17:441144 EXPECT_TRUE(d.request_failed());
1145 }
[email protected]316c1e5e2012-09-12 15:17:441146}
1147
[email protected]3ca8b362013-11-11 22:18:071148TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511149 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071150 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511151 ASSERT_NO_FATAL_FAILURE(
1152 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1153
satoruxddac0442017-05-29 06:06:181154 // The directory part of the path returned from CreateTemporaryFileInDir()
1155 // can be slightly different from |absolute_temp_dir| on Windows.
1156 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1157 // Hence the test should use the directory name of |test_file|, rather than
1158 // |absolute_temp_dir|, for whitelisting.
1159 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591160 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071161 {
1162 TestDelegate d;
satoruxddac0442017-05-29 06:06:181163 CookieBlockingNetworkDelegate network_delegate;
1164 network_delegate.AddToWhitelist(real_temp_dir);
[email protected]3ca8b362013-11-11 22:18:071165 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161166 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1167 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191168 r->Start();
Wez2a31b222018-06-07 22:07:151169 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181170 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071171 EXPECT_FALSE(d.request_failed());
1172 EXPECT_EQ(test_data, d.data_received());
1173 }
1174
1175 {
1176 TestDelegate d;
satoruxddac0442017-05-29 06:06:181177 CookieBlockingNetworkDelegate network_delegate;
[email protected]3ca8b362013-11-11 22:18:071178 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161179 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1180 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191181 r->Start();
Wez2a31b222018-06-07 22:07:151182 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181183 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071184 EXPECT_TRUE(d.request_failed());
1185 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181186 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071187 }
1188}
1189
Kevin Marshalla9f05ec2017-07-14 02:10:051190#if defined(OS_POSIX) && !defined(OS_FUCHSIA) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181191
1192TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511193 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181194 // Get an absolute path since temp_dir can contain a symbolic link.
1195 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511196 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181197
1198 // Create a good directory (will be whitelisted) and a good file.
1199 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1200 ASSERT_TRUE(base::CreateDirectory(good_dir));
1201 base::FilePath good_file;
1202 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1203 std::string good_data("good");
1204 base::WriteFile(good_file, good_data.data(), good_data.size());
1205 // See the comment in AllowFileURLs() for why this is done.
1206 base::FilePath real_good_dir = good_file.DirName();
1207
1208 // Create a bad directory (will not be whitelisted) and a bad file.
1209 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1210 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1211 base::FilePath bad_file;
1212 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1213 std::string bad_data("bad");
1214 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1215
1216 // This symlink will point to the good file. Access to the symlink will be
1217 // allowed as both the symlink and the destination file are in the same
1218 // good directory.
1219 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1220 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1221 GURL good_file_url = FilePathToFileURL(good_symlink);
1222 // This symlink will point to the bad file. Even though the symlink is in
1223 // the good directory, access to the symlink will be rejected since it
1224 // points to the bad file.
1225 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1226 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1227 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1228
1229 CookieBlockingNetworkDelegate network_delegate;
1230 network_delegate.AddToWhitelist(real_good_dir);
1231 {
1232 TestDelegate d;
1233 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371234 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1235 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181236 r->Start();
Wez2a31b222018-06-07 22:07:151237 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181238 // good_file_url should be allowed.
1239 EXPECT_FALSE(d.request_failed());
1240 EXPECT_EQ(good_data, d.data_received());
1241 }
1242
1243 {
1244 TestDelegate d;
1245 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371246 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1247 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181248 r->Start();
Wez2a31b222018-06-07 22:07:151249 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181250 // bad_file_url should be rejected.
1251 EXPECT_TRUE(d.request_failed());
1252 EXPECT_EQ("", d.data_received());
1253 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1254 }
1255}
1256
1257TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511258 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181259 // Get an absolute path since temp_dir can contain a symbolic link.
1260 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511261 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181262
1263 // Create a good directory (will be whitelisted).
1264 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1265 ASSERT_TRUE(base::CreateDirectory(good_dir));
1266
1267 // Create a bad directory (will not be whitelisted).
1268 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1269 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1270
1271 // This symlink will point to the good directory. Access to the symlink
1272 // will be allowed as the symlink is in the good dir that'll be white
1273 // listed.
1274 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1275 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1276 GURL good_file_url = FilePathToFileURL(good_symlink);
1277 // This symlink will point to the bad directory. Even though the symlink is
1278 // in the good directory, access to the symlink will be rejected since it
1279 // points to the bad directory.
1280 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1281 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1282 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1283
1284 CookieBlockingNetworkDelegate network_delegate;
1285 network_delegate.AddToWhitelist(good_dir);
1286 {
1287 TestDelegate d;
1288 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371289 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1290 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181291 r->Start();
Wez2a31b222018-06-07 22:07:151292 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181293 // good_file_url should be allowed.
1294 EXPECT_FALSE(d.request_failed());
1295 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1296 }
1297
1298 {
1299 TestDelegate d;
1300 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371301 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1302 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181303 r->Start();
Wez2a31b222018-06-07 22:07:151304 d.RunUntilComplete();
satoruxddac0442017-05-29 06:06:181305 // bad_file_url should be rejected.
1306 EXPECT_TRUE(d.request_failed());
1307 EXPECT_EQ("", d.data_received());
1308 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1309 }
1310}
1311
Kevin Marshalla9f05ec2017-07-14 02:10:051312#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]316c1e5e2012-09-12 15:17:441313
1314TEST_F(URLRequestTest, FileDirCancelTest) {
1315 // Put in mock resource provider.
1316 NetModule::SetResourceProvider(TestNetResourceProvider);
1317
1318 TestDelegate d;
1319 {
[email protected]6cdfd7f2013-02-08 20:40:151320 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191321 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441322 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1323 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1324
danakj8522a25b2016-04-16 00:17:361325 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161326 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1327 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191328 req->Start();
1329 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441330
1331 d.set_cancel_in_received_data_pending(true);
1332
Wez2a31b222018-06-07 22:07:151333 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441334 }
1335
1336 // Take out mock resource provider.
1337 NetModule::SetResourceProvider(NULL);
1338}
1339
[email protected]5f9581402013-10-30 13:08:321340TEST_F(URLRequestTest, FileDirOutputSanity) {
1341 // Verify the general sanity of the the output of the file:
1342 // directory lister by checking for the output of a known existing
1343 // file.
1344 const char sentinel_name[] = "filedir-sentinel";
1345
1346 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191347 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471348 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321349
1350 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161351 std::unique_ptr<URLRequest> req(
1352 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1353 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191354 req->Start();
Wez2a31b222018-06-07 22:07:151355 d.RunUntilComplete();
[email protected]5f9581402013-10-30 13:08:321356
1357 // Generate entry for the sentinel file.
1358 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581359 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491360 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321361 EXPECT_GT(info.size, 0);
1362 std::string sentinel_output = GetDirectoryListingEntry(
1363 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181364 std::string(sentinel_name), false /* is_dir */, info.size,
1365
[email protected]5f9581402013-10-30 13:08:321366 info.last_modified);
1367
1368 ASSERT_LT(0, d.bytes_received());
1369 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501370 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321371 // Check for the entry generated for the "sentinel" file.
1372 const std::string& data = d.data_received();
1373 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1374}
1375
[email protected]316c1e5e2012-09-12 15:17:441376TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1377 // There is an implicit redirect when loading a file path that matches a
1378 // directory and does not end with a slash. Ensure that following such
1379 // redirects does not crash. See http://crbug.com/18686.
1380
[email protected]6cdfd7f2013-02-08 20:40:151381 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191382 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471383 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441384
1385 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161386 std::unique_ptr<URLRequest> req(
1387 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1388 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191389 req->Start();
Wez2a31b222018-06-07 22:07:151390 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441391
1392 ASSERT_EQ(1, d.received_redirect_count());
1393 ASSERT_LT(0, d.bytes_received());
1394 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501395 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441396}
1397
1398#if defined(OS_WIN)
1399// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1400TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1401 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161402 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
1403 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191404 req->Start();
Wez2a31b222018-06-07 22:07:151405 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:441406
1407 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501408 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441409}
[email protected]5ecf7cb282014-05-11 01:49:551410#endif // defined(OS_WIN)
1411
brettwa1228ebb2016-10-28 03:51:341412#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551413
1414TEST_F(URLRequestTest, InvalidUrlTest) {
1415 TestDelegate d;
1416 {
rhalavatib7bd7c792017-04-27 05:25:161417 std::unique_ptr<URLRequest> r(
1418 default_context_.CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1419 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551420
[email protected]f7022f32014-08-21 16:32:191421 r->Start();
1422 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551423
Wez2a31b222018-06-07 22:07:151424 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551425 EXPECT_TRUE(d.request_failed());
1426 }
1427}
1428
jochen0e3b3a62014-09-16 18:31:231429TEST_F(URLRequestTest, InvalidReferrerTest) {
1430 TestURLRequestContext context;
1431 TestNetworkDelegate network_delegate;
1432 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1433 context.set_network_delegate(&network_delegate);
1434 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361435 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161436 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1437 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231438 req->SetReferrer("https://somewhere.com/");
1439
1440 req->Start();
Wez2a31b222018-06-07 22:07:151441 d.RunUntilComplete();
jochen0e3b3a62014-09-16 18:31:231442 EXPECT_TRUE(d.request_failed());
1443}
1444
[email protected]5ecf7cb282014-05-11 01:49:551445#if defined(OS_WIN)
1446TEST_F(URLRequestTest, ResolveShortcutTest) {
1447 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191448 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471449 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551450 app_path = app_path.AppendASCII("with-headers.html");
1451
1452 std::wstring lnk_path = app_path.value() + L".lnk";
1453
1454 base::win::ScopedCOMInitializer com_initializer;
1455
1456 // Temporarily create a shortcut for test
1457 {
Robert Liaoc88f99d12017-10-17 21:48:331458 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161459 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1460 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331461 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001462 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551463 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1464 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1465 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1466 }
1467
1468 TestDelegate d;
1469 {
danakj8522a25b2016-04-16 00:17:361470 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161471 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1472 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551473
[email protected]f7022f32014-08-21 16:32:191474 r->Start();
1475 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551476
Wez2a31b222018-06-07 22:07:151477 d.RunUntilComplete();
[email protected]5ecf7cb282014-05-11 01:49:551478
1479 WIN32_FILE_ATTRIBUTE_DATA data;
1480 GetFileAttributesEx(app_path.value().c_str(),
1481 GetFileExInfoStandard, &data);
1482 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1483 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1484 FILE_ATTRIBUTE_NORMAL, NULL);
1485 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361486 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551487 DWORD read_size;
1488 BOOL result;
1489 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1490 &read_size, NULL);
1491 std::string content(buffer.get(), read_size);
1492 CloseHandle(file);
1493
[email protected]f7022f32014-08-21 16:32:191494 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551495 EXPECT_EQ(1, d.received_redirect_count());
1496 EXPECT_EQ(content, d.data_received());
1497 }
1498
1499 // Clean the shortcut
1500 DeleteFile(lnk_path.c_str());
1501}
1502#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441503
1504// Custom URLRequestJobs for use with interceptor tests
1505class RestartTestJob : public URLRequestTestJob {
1506 public:
1507 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1508 : URLRequestTestJob(request, network_delegate, true) {}
1509 protected:
dchengb03027d2014-10-21 12:00:201510 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441511 private:
Chris Watkins7a41d3552017-12-01 02:13:271512 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441513};
1514
1515class CancelTestJob : public URLRequestTestJob {
1516 public:
1517 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1518 : URLRequestTestJob(request, network_delegate, true) {}
1519 protected:
dchengb03027d2014-10-21 12:00:201520 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441521 private:
Chris Watkins7a41d3552017-12-01 02:13:271522 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441523};
1524
1525class CancelThenRestartTestJob : public URLRequestTestJob {
1526 public:
1527 explicit CancelThenRestartTestJob(URLRequest* request,
1528 NetworkDelegate* network_delegate)
1529 : URLRequestTestJob(request, network_delegate, true) {
1530 }
1531 protected:
dchengb03027d2014-10-21 12:00:201532 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441533 request_->Cancel();
1534 this->NotifyRestartRequired();
1535 }
1536 private:
Chris Watkins7a41d3552017-12-01 02:13:271537 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441538};
1539
bengr1bf8e942014-11-07 01:36:501540// An Interceptor for use with interceptor tests.
1541class MockURLRequestInterceptor : public URLRequestInterceptor {
1542 public:
1543 // Static getters for canned response header and data strings.
1544 static std::string ok_data() {
1545 return URLRequestTestJob::test_data_1();
1546 }
1547
1548 static std::string ok_headers() {
1549 return URLRequestTestJob::test_headers();
1550 }
1551
1552 static std::string redirect_data() {
1553 return std::string();
1554 }
1555
1556 static std::string redirect_headers() {
1557 return URLRequestTestJob::test_redirect_headers();
1558 }
1559
1560 static std::string error_data() {
1561 return std::string("ohhh nooooo mr. bill!");
1562 }
1563
1564 static std::string error_headers() {
1565 return URLRequestTestJob::test_error_headers();
1566 }
1567
1568 MockURLRequestInterceptor()
1569 : intercept_main_request_(false), restart_main_request_(false),
1570 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1571 simulate_main_network_error_(false),
1572 intercept_redirect_(false), cancel_redirect_request_(false),
1573 intercept_final_response_(false), cancel_final_request_(false),
1574 use_url_request_http_job_(false),
1575 did_intercept_main_(false), did_restart_main_(false),
1576 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1577 did_simulate_error_main_(false),
1578 did_intercept_redirect_(false), did_cancel_redirect_(false),
1579 did_intercept_final_(false), did_cancel_final_(false) {
1580 }
1581
Chris Watkins7a41d3552017-12-01 02:13:271582 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501583
1584 // URLRequestInterceptor implementation:
1585 URLRequestJob* MaybeInterceptRequest(
1586 URLRequest* request,
1587 NetworkDelegate* network_delegate) const override {
1588 if (restart_main_request_) {
1589 restart_main_request_ = false;
1590 did_restart_main_ = true;
1591 return new RestartTestJob(request, network_delegate);
1592 }
1593 if (cancel_main_request_) {
1594 cancel_main_request_ = false;
1595 did_cancel_main_ = true;
1596 return new CancelTestJob(request, network_delegate);
1597 }
1598 if (cancel_then_restart_main_request_) {
1599 cancel_then_restart_main_request_ = false;
1600 did_cancel_then_restart_main_ = true;
1601 return new CancelThenRestartTestJob(request, network_delegate);
1602 }
1603 if (simulate_main_network_error_) {
1604 simulate_main_network_error_ = false;
1605 did_simulate_error_main_ = true;
1606 if (use_url_request_http_job_) {
1607 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1608 }
1609 // This job will result in error since the requested URL is not one of the
1610 // URLs supported by these tests.
1611 return new URLRequestTestJob(request, network_delegate, true);
1612 }
1613 if (!intercept_main_request_)
1614 return nullptr;
1615 intercept_main_request_ = false;
1616 did_intercept_main_ = true;
1617 URLRequestTestJob* job = new URLRequestTestJob(request,
1618 network_delegate,
1619 main_headers_,
1620 main_data_,
1621 true);
1622 job->set_load_timing_info(main_request_load_timing_info_);
1623 return job;
1624 }
1625
1626 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1627 NetworkDelegate* network_delegate,
1628 const GURL& location) const override {
1629 if (cancel_redirect_request_) {
1630 cancel_redirect_request_ = false;
1631 did_cancel_redirect_ = true;
1632 return new CancelTestJob(request, network_delegate);
1633 }
1634 if (!intercept_redirect_)
1635 return nullptr;
1636 intercept_redirect_ = false;
1637 did_intercept_redirect_ = true;
1638 if (use_url_request_http_job_) {
1639 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1640 }
1641 return new URLRequestTestJob(request,
1642 network_delegate,
1643 redirect_headers_,
1644 redirect_data_,
1645 true);
1646 }
1647
1648 URLRequestJob* MaybeInterceptResponse(
1649 URLRequest* request,
1650 NetworkDelegate* network_delegate) const override {
1651 if (cancel_final_request_) {
1652 cancel_final_request_ = false;
1653 did_cancel_final_ = true;
1654 return new CancelTestJob(request, network_delegate);
1655 }
1656 if (!intercept_final_response_)
1657 return nullptr;
1658 intercept_final_response_ = false;
1659 did_intercept_final_ = true;
1660 if (use_url_request_http_job_) {
1661 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1662 }
1663 return new URLRequestTestJob(request,
1664 network_delegate,
1665 final_headers_,
1666 final_data_,
1667 true);
1668 }
1669
1670 void set_intercept_main_request(bool intercept_main_request) {
1671 intercept_main_request_ = intercept_main_request;
1672 }
1673
1674 void set_main_headers(const std::string& main_headers) {
1675 main_headers_ = main_headers;
1676 }
1677
1678 void set_main_data(const std::string& main_data) {
1679 main_data_ = main_data;
1680 }
1681
1682 void set_main_request_load_timing_info(
1683 const LoadTimingInfo& main_request_load_timing_info) {
1684 main_request_load_timing_info_ = main_request_load_timing_info;
1685 }
1686
1687 void set_restart_main_request(bool restart_main_request) {
1688 restart_main_request_ = restart_main_request;
1689 }
1690
1691 void set_cancel_main_request(bool cancel_main_request) {
1692 cancel_main_request_ = cancel_main_request;
1693 }
1694
1695 void set_cancel_then_restart_main_request(
1696 bool cancel_then_restart_main_request) {
1697 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1698 }
1699
1700 void set_simulate_main_network_error(bool simulate_main_network_error) {
1701 simulate_main_network_error_ = simulate_main_network_error;
1702 }
1703
1704 void set_intercept_redirect(bool intercept_redirect) {
1705 intercept_redirect_ = intercept_redirect;
1706 }
1707
1708 void set_redirect_headers(const std::string& redirect_headers) {
1709 redirect_headers_ = redirect_headers;
1710 }
1711
1712 void set_redirect_data(const std::string& redirect_data) {
1713 redirect_data_ = redirect_data;
1714 }
1715
1716 void set_cancel_redirect_request(bool cancel_redirect_request) {
1717 cancel_redirect_request_ = cancel_redirect_request;
1718 }
1719
1720 void set_intercept_final_response(bool intercept_final_response) {
1721 intercept_final_response_ = intercept_final_response;
1722 }
1723
1724 void set_final_headers(const std::string& final_headers) {
1725 final_headers_ = final_headers;
1726 }
1727
1728 void set_final_data(const std::string& final_data) {
1729 final_data_ = final_data;
1730 }
1731
1732 void set_cancel_final_request(bool cancel_final_request) {
1733 cancel_final_request_ = cancel_final_request;
1734 }
1735
1736 void set_use_url_request_http_job(bool use_url_request_http_job) {
1737 use_url_request_http_job_ = use_url_request_http_job;
1738 }
1739
1740 bool did_intercept_main() const {
1741 return did_intercept_main_;
1742 }
1743
1744 bool did_restart_main() const {
1745 return did_restart_main_;
1746 }
1747
1748 bool did_cancel_main() const {
1749 return did_cancel_main_;
1750 }
1751
1752 bool did_cancel_then_restart_main() const {
1753 return did_cancel_then_restart_main_;
1754 }
1755
1756 bool did_simulate_error_main() const {
1757 return did_simulate_error_main_;
1758 }
1759
1760 bool did_intercept_redirect() const {
1761 return did_intercept_redirect_;
1762 }
1763
1764 bool did_cancel_redirect() const {
1765 return did_cancel_redirect_;
1766 }
1767
1768 bool did_intercept_final() const {
1769 return did_intercept_final_;
1770 }
1771
1772 bool did_cancel_final() const {
1773 return did_cancel_final_;
1774 }
1775
1776 private:
1777 // Indicate whether to intercept the main request, and if so specify the
1778 // response to return and the LoadTimingInfo to use.
1779 mutable bool intercept_main_request_;
1780 mutable std::string main_headers_;
1781 mutable std::string main_data_;
1782 mutable LoadTimingInfo main_request_load_timing_info_;
1783
1784 // These indicate actions that can be taken within MaybeInterceptRequest.
1785 mutable bool restart_main_request_;
1786 mutable bool cancel_main_request_;
1787 mutable bool cancel_then_restart_main_request_;
1788 mutable bool simulate_main_network_error_;
1789
1790 // Indicate whether to intercept redirects, and if so specify the response to
1791 // return.
1792 mutable bool intercept_redirect_;
1793 mutable std::string redirect_headers_;
1794 mutable std::string redirect_data_;
1795
1796 // Cancel the request within MaybeInterceptRedirect.
1797 mutable bool cancel_redirect_request_;
1798
1799 // Indicate whether to intercept the final response, and if so specify the
1800 // response to return.
1801 mutable bool intercept_final_response_;
1802 mutable std::string final_headers_;
1803 mutable std::string final_data_;
1804
1805 // Cancel the final request within MaybeInterceptResponse.
1806 mutable bool cancel_final_request_;
1807
1808 // Instruct the interceptor to use a real URLRequestHTTPJob.
1809 mutable bool use_url_request_http_job_;
1810
1811 // These indicate if the interceptor did something or not.
1812 mutable bool did_intercept_main_;
1813 mutable bool did_restart_main_;
1814 mutable bool did_cancel_main_;
1815 mutable bool did_cancel_then_restart_main_;
1816 mutable bool did_simulate_error_main_;
1817 mutable bool did_intercept_redirect_;
1818 mutable bool did_cancel_redirect_;
1819 mutable bool did_intercept_final_;
1820 mutable bool did_cancel_final_;
1821};
1822
1823// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1824class URLRequestInterceptorTest : public URLRequestTest {
1825 public:
1826 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1827 }
1828
1829 ~URLRequestInterceptorTest() override {
1830 // URLRequestJobs may post clean-up tasks on destruction.
1831 base::RunLoop().RunUntilIdle();
1832 }
1833
1834 void SetUpFactory() override {
1835 interceptor_ = new MockURLRequestInterceptor();
1836 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361837 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501838 }
1839
1840 MockURLRequestInterceptor* interceptor() const {
1841 return interceptor_;
1842 }
1843
1844 private:
1845 MockURLRequestInterceptor* interceptor_;
1846};
1847
1848TEST_F(URLRequestInterceptorTest, Intercept) {
1849 // Intercept the main request and respond with a simple response.
1850 interceptor()->set_intercept_main_request(true);
1851 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1852 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591853 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361854 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161855 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1856 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501857 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1858 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1859 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091860 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041861 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1862 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501863 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191864 req->Start();
Wez2a31b222018-06-07 22:07:151865 d.RunUntilComplete();
[email protected]2bba3252013-04-08 19:50:591866
bengr1bf8e942014-11-07 01:36:501867 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091868 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501869 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1870 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591871
bengr1bf8e942014-11-07 01:36:501872 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501873 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501874 EXPECT_EQ(200, req->response_headers()->response_code());
1875 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1876 EXPECT_EQ(1, d.response_started_count());
1877 EXPECT_EQ(0, d.received_redirect_count());
1878}
[email protected]2bba3252013-04-08 19:50:591879
bengr1bf8e942014-11-07 01:36:501880TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1881 // Intercept the main request and respond with a redirect.
1882 interceptor()->set_intercept_main_request(true);
1883 interceptor()->set_main_headers(
1884 MockURLRequestInterceptor::redirect_headers());
1885 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1886
1887 // Intercept that redirect and respond with a final OK response.
1888 interceptor()->set_intercept_redirect(true);
1889 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1890 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1891
1892 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361893 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161894 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1895 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501896 req->set_method("GET");
1897 req->Start();
Wez2a31b222018-06-07 22:07:151898 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501899
1900 // Check that the interceptor got called as expected.
1901 EXPECT_TRUE(interceptor()->did_intercept_main());
1902 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1903
1904 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501905 int status = d.request_status();
1906 EXPECT_EQ(OK, status);
1907 if (status == OK)
bengr1bf8e942014-11-07 01:36:501908 EXPECT_EQ(200, req->response_headers()->response_code());
1909
1910 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1911 EXPECT_EQ(1, d.response_started_count());
1912 EXPECT_EQ(0, d.received_redirect_count());
1913}
1914
1915TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1916 // Intercept the main request to generate a server error response.
1917 interceptor()->set_intercept_main_request(true);
1918 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1919 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1920
1921 // Intercept that error and respond with an OK response.
1922 interceptor()->set_intercept_final_response(true);
1923 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1924 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1925
1926 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361927 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161928 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1929 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501930 req->set_method("GET");
1931 req->Start();
Wez2a31b222018-06-07 22:07:151932 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501933
1934 // Check that the interceptor got called as expected.
1935 EXPECT_TRUE(interceptor()->did_intercept_main());
1936 EXPECT_TRUE(interceptor()->did_intercept_final());
1937
1938 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501939 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501940 EXPECT_EQ(200, req->response_headers()->response_code());
1941 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1942 EXPECT_EQ(1, d.response_started_count());
1943 EXPECT_EQ(0, d.received_redirect_count());
1944}
1945
1946TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1947 // Intercept the main request to simulate a network error.
1948 interceptor()->set_simulate_main_network_error(true);
1949
1950 // Intercept that error and respond with an OK response.
1951 interceptor()->set_intercept_final_response(true);
1952 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1953 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1954
1955 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361956 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161957 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1958 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501959 req->set_method("GET");
1960 req->Start();
Wez2a31b222018-06-07 22:07:151961 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501962
1963 // Check that the interceptor got called as expected.
1964 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1965 EXPECT_TRUE(interceptor()->did_intercept_final());
1966
1967 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501968 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501969 EXPECT_EQ(200, req->response_headers()->response_code());
1970 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1971 EXPECT_EQ(1, d.response_started_count());
1972 EXPECT_EQ(0, d.received_redirect_count());
1973}
1974
1975TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1976 // Restart the main request.
1977 interceptor()->set_restart_main_request(true);
1978
1979 // then intercept the new main request and respond with an OK response
1980 interceptor()->set_intercept_main_request(true);
1981 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1982 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1983
1984 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361985 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161986 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1987 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501988 req->set_method("GET");
1989 req->Start();
Wez2a31b222018-06-07 22:07:151990 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:501991
1992 // Check that the interceptor got called as expected.
1993 EXPECT_TRUE(interceptor()->did_restart_main());
1994 EXPECT_TRUE(interceptor()->did_intercept_main());
1995
1996 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501997 int status = d.request_status();
1998 EXPECT_EQ(OK, status);
1999 if (status == OK)
bengr1bf8e942014-11-07 01:36:502000 EXPECT_EQ(200, req->response_headers()->response_code());
2001
2002 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2003 EXPECT_EQ(1, d.response_started_count());
2004 EXPECT_EQ(0, d.received_redirect_count());
2005}
2006
2007TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2008 // Intercept the main request and cancel from within the restarted job.
2009 interceptor()->set_cancel_main_request(true);
2010
2011 // Set up to intercept the final response and override it with an OK response.
2012 interceptor()->set_intercept_final_response(true);
2013 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2014 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2015
2016 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362017 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162018 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2019 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502020 req->set_method("GET");
2021 req->Start();
Wez2a31b222018-06-07 22:07:152022 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502023
2024 // Check that the interceptor got called as expected.
2025 EXPECT_TRUE(interceptor()->did_cancel_main());
2026 EXPECT_FALSE(interceptor()->did_intercept_final());
2027
2028 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502029 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502030}
2031
2032TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2033 // Intercept the main request and respond with a redirect.
2034 interceptor()->set_intercept_main_request(true);
2035 interceptor()->set_main_headers(
2036 MockURLRequestInterceptor::redirect_headers());
2037 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2038
2039 // Intercept the redirect and cancel from within that job.
2040 interceptor()->set_cancel_redirect_request(true);
2041
2042 // Set up to intercept the final response and override it with an OK response.
2043 interceptor()->set_intercept_final_response(true);
2044 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2045 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2046
2047 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362048 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162049 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2050 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502051 req->set_method("GET");
2052 req->Start();
Wez2a31b222018-06-07 22:07:152053 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502054
2055 // Check that the interceptor got called as expected.
2056 EXPECT_TRUE(interceptor()->did_intercept_main());
2057 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2058 EXPECT_FALSE(interceptor()->did_intercept_final());
2059
2060 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502061 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502062}
2063
2064TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2065 // Intercept the main request to simulate a network error.
2066 interceptor()->set_simulate_main_network_error(true);
2067
2068 // Set up to intercept final the response and cancel from within that job.
2069 interceptor()->set_cancel_final_request(true);
2070
2071 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362072 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162073 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2074 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502075 req->set_method("GET");
2076 req->Start();
Wez2a31b222018-06-07 22:07:152077 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502078
2079 // Check that the interceptor got called as expected.
2080 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2081 EXPECT_TRUE(interceptor()->did_cancel_final());
2082
2083 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502084 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502085}
2086
2087TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2088 // Intercept the main request and cancel then restart from within that job.
2089 interceptor()->set_cancel_then_restart_main_request(true);
2090
2091 // Set up to intercept the final response and override it with an OK response.
2092 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502093 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2094 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502095
2096 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362097 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162098 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2099 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502100 req->set_method("GET");
2101 req->Start();
Wez2a31b222018-06-07 22:07:152102 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502103
2104 // Check that the interceptor got called as expected.
2105 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2106 EXPECT_FALSE(interceptor()->did_intercept_final());
2107
2108 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502109 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592110}
2111
2112// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2113// reused. |connect_time_flags| is used to indicate if there should be dns
2114// or SSL times, and |used_proxy| is used for proxy times.
2115LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2116 int connect_time_flags,
2117 bool used_proxy) {
2118 LoadTimingInfo load_timing;
2119 load_timing.socket_log_id = 1;
2120
2121 if (used_proxy) {
2122 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2123 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2124 }
2125
2126 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2127 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2128 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2129 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2130 }
2131 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2132 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2133 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2134 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2135 }
2136 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2137
2138 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2139 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2140 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2141 return load_timing;
2142}
2143
2144// Same as above, but in the case of a reused socket.
2145LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2146 bool used_proxy) {
2147 LoadTimingInfo load_timing;
2148 load_timing.socket_log_id = 1;
2149 load_timing.socket_reused = true;
2150
2151 if (used_proxy) {
2152 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2153 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2154 }
2155
2156 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2157 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2158 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2159 return load_timing;
2160}
2161
bengr1bf8e942014-11-07 01:36:502162LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2163 const LoadTimingInfo& job_load_timing,
2164 const URLRequestContext& context,
2165 MockURLRequestInterceptor* interceptor) {
2166 interceptor->set_intercept_main_request(true);
2167 interceptor->set_main_request_load_timing_info(job_load_timing);
2168 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162169 std::unique_ptr<URLRequest> req(
2170 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2171 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502172 req->Start();
Wez2a31b222018-06-07 22:07:152173 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:502174
2175 LoadTimingInfo resulting_load_timing;
2176 req->GetLoadTimingInfo(&resulting_load_timing);
2177
2178 // None of these should be modified by the URLRequest.
2179 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2180 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2181 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2182 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2183 EXPECT_EQ(job_load_timing.receive_headers_end,
2184 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572185 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2186 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502187
2188 return resulting_load_timing;
2189}
2190
[email protected]2bba3252013-04-08 19:50:592191// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502192TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592193 base::TimeTicks now = base::TimeTicks::Now();
2194 LoadTimingInfo job_load_timing =
2195 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2196
[email protected]2ca01e52013-10-31 22:05:192197 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502198 RunURLRequestInterceptorLoadTimingTest(
2199 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592200
2201 // Nothing should have been changed by the URLRequest.
2202 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2203 load_timing_result.proxy_resolve_start);
2204 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2205 load_timing_result.proxy_resolve_end);
2206 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2207 load_timing_result.connect_timing.dns_start);
2208 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2209 load_timing_result.connect_timing.dns_end);
2210 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2211 load_timing_result.connect_timing.connect_start);
2212 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2213 load_timing_result.connect_timing.connect_end);
2214 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2215 load_timing_result.connect_timing.ssl_start);
2216 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2217 load_timing_result.connect_timing.ssl_end);
2218
2219 // Redundant sanity check.
2220 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2221}
2222
2223// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502224TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592225 base::TimeTicks now = base::TimeTicks::Now();
2226 LoadTimingInfo job_load_timing =
2227 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2228
[email protected]2ca01e52013-10-31 22:05:192229 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502230 RunURLRequestInterceptorLoadTimingTest(
2231 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592232
2233 // Nothing should have been changed by the URLRequest.
2234 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2235 load_timing_result.proxy_resolve_start);
2236 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2237 load_timing_result.proxy_resolve_end);
2238 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2239 load_timing_result.connect_timing.dns_start);
2240 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2241 load_timing_result.connect_timing.dns_end);
2242 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2243 load_timing_result.connect_timing.connect_start);
2244 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2245 load_timing_result.connect_timing.connect_end);
2246 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2247 load_timing_result.connect_timing.ssl_start);
2248 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2249 load_timing_result.connect_timing.ssl_end);
2250
2251 // Redundant sanity check.
2252 TestLoadTimingNotReusedWithProxy(load_timing_result,
2253 CONNECT_TIMING_HAS_SSL_TIMES);
2254}
2255
2256// Make sure that URLRequest correctly adjusts proxy times when they're before
2257// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102258// the case of reusing a SPDY session. The connected socket is not considered
2259// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592260//
2261// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502262TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592263 base::TimeTicks now = base::TimeTicks::Now();
2264 LoadTimingInfo job_load_timing =
2265 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2266 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2267 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2268 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2269 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2270 job_load_timing.connect_timing.connect_start =
2271 now - base::TimeDelta::FromDays(2);
2272 job_load_timing.connect_timing.connect_end =
2273 now - base::TimeDelta::FromDays(1);
2274
[email protected]2ca01e52013-10-31 22:05:192275 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502276 RunURLRequestInterceptorLoadTimingTest(
2277 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592278
2279 // Proxy times, connect times, and DNS times should all be replaced with
2280 // request_start.
2281 EXPECT_EQ(load_timing_result.request_start,
2282 load_timing_result.proxy_resolve_start);
2283 EXPECT_EQ(load_timing_result.request_start,
2284 load_timing_result.proxy_resolve_end);
2285 EXPECT_EQ(load_timing_result.request_start,
2286 load_timing_result.connect_timing.dns_start);
2287 EXPECT_EQ(load_timing_result.request_start,
2288 load_timing_result.connect_timing.dns_end);
2289 EXPECT_EQ(load_timing_result.request_start,
2290 load_timing_result.connect_timing.connect_start);
2291 EXPECT_EQ(load_timing_result.request_start,
2292 load_timing_result.connect_timing.connect_end);
2293
2294 // Other times should have been left null.
2295 TestLoadTimingNotReusedWithProxy(load_timing_result,
2296 CONNECT_TIMING_HAS_DNS_TIMES);
2297}
2298
2299// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502300TEST_F(URLRequestInterceptorTest,
2301 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592302 base::TimeTicks now = base::TimeTicks::Now();
2303 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2304 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2305 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2306
[email protected]2ca01e52013-10-31 22:05:192307 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502308 RunURLRequestInterceptorLoadTimingTest(
2309 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592310
2311 // Proxy times and connect times should all be replaced with request_start.
2312 EXPECT_EQ(load_timing_result.request_start,
2313 load_timing_result.proxy_resolve_start);
2314 EXPECT_EQ(load_timing_result.request_start,
2315 load_timing_result.proxy_resolve_end);
2316
2317 // Other times should have been left null.
2318 TestLoadTimingReusedWithProxy(load_timing_result);
2319}
2320
2321// Make sure that URLRequest correctly adjusts connect times when they're before
2322// |request_start|, due to reusing a connected socket. The connected socket is
2323// not considered reused in this test (May be a preconnect).
2324//
2325// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502326TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592327 base::TimeTicks now = base::TimeTicks::Now();
2328 LoadTimingInfo job_load_timing =
2329 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2330 job_load_timing.connect_timing.connect_start =
2331 now - base::TimeDelta::FromDays(1);
2332 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2333 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2334 job_load_timing.connect_timing.connect_end =
2335 now - base::TimeDelta::FromDays(4);
2336
[email protected]2ca01e52013-10-31 22:05:192337 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502338 RunURLRequestInterceptorLoadTimingTest(
2339 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592340
2341 // Connect times, and SSL times should be replaced with request_start.
2342 EXPECT_EQ(load_timing_result.request_start,
2343 load_timing_result.connect_timing.connect_start);
2344 EXPECT_EQ(load_timing_result.request_start,
2345 load_timing_result.connect_timing.ssl_start);
2346 EXPECT_EQ(load_timing_result.request_start,
2347 load_timing_result.connect_timing.ssl_end);
2348 EXPECT_EQ(load_timing_result.request_start,
2349 load_timing_result.connect_timing.connect_end);
2350
2351 // Other times should have been left null.
2352 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2353}
2354
2355// Make sure that URLRequest correctly adjusts connect times when they're before
2356// |request_start|, due to reusing a connected socket in the case that there
2357// are also proxy times. The connected socket is not considered reused in this
2358// test (May be a preconnect).
2359//
2360// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502361TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592362 base::TimeTicks now = base::TimeTicks::Now();
2363 LoadTimingInfo job_load_timing =
2364 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2365 job_load_timing.connect_timing.connect_start =
2366 now - base::TimeDelta::FromDays(1);
2367 job_load_timing.connect_timing.connect_end =
2368 now - base::TimeDelta::FromDays(2);
2369
[email protected]2ca01e52013-10-31 22:05:192370 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502371 RunURLRequestInterceptorLoadTimingTest(
2372 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592373
2374 // Connect times should be replaced with proxy_resolve_end.
2375 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2376 load_timing_result.connect_timing.connect_start);
2377 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2378 load_timing_result.connect_timing.connect_end);
2379
2380 // Other times should have been left null.
2381 TestLoadTimingNotReusedWithProxy(load_timing_result,
2382 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2383}
2384
[email protected]316c1e5e2012-09-12 15:17:442385// Check that two different URL requests have different identifiers.
2386TEST_F(URLRequestTest, Identifiers) {
2387 TestDelegate d;
2388 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362389 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162390 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2391 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362392 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162393 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2394 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442395
mmenke19378d22014-09-09 04:12:592396 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442397}
2398
blundellb8163592f2015-12-16 14:22:422399#if defined(OS_IOS)
2400// TODO(droger): Check that a failure to connect to the proxy is reported to
2401// the network delegate. crbug.com/496743
2402#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2403#else
2404#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2405#endif
2406TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442407 MockHostResolver host_resolver;
2408 host_resolver.rules()->AddSimulatedFailure("*");
2409
[email protected]ceefd7fd2012-11-29 00:36:242410 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442411 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2412
2413 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362414 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162415 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2416 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192417 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442418
[email protected]f7022f32014-08-21 16:32:192419 req->Start();
Wez2a31b222018-06-07 22:07:152420 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442421
2422 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152423 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472424 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502425 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442426
2427 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012428 EXPECT_THAT(network_delegate.last_error(),
2429 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442430 EXPECT_EQ(1, network_delegate.completed_requests());
2431}
2432
[email protected]cba24642014-08-15 20:49:592433// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442434// content is empty.
2435TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2436 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162437 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2438 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192439 req->Start();
Wez2a31b222018-06-07 22:07:152440 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442441 EXPECT_EQ("", d.data_received());
2442 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2443}
2444
[email protected]5033ab82013-03-22 20:17:462445// Make sure that SetPriority actually sets the URLRequest's priority
2446// correctly, both before and after start.
2447TEST_F(URLRequestTest, SetPriorityBasic) {
2448 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362449 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162450 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2451 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192452 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462453
[email protected]f7022f32014-08-21 16:32:192454 req->SetPriority(LOW);
2455 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462456
[email protected]f7022f32014-08-21 16:32:192457 req->Start();
2458 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462459
[email protected]f7022f32014-08-21 16:32:192460 req->SetPriority(MEDIUM);
2461 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462462}
2463
2464// Make sure that URLRequest calls SetPriority on a job before calling
2465// Start on it.
2466TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2467 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362468 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162469 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2470 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192471 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462472
mmenkeed0498b2015-12-08 23:20:422473 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362474 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422475 req.get(), &default_network_delegate_, &job_priority));
2476 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2477 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462478
[email protected]f7022f32014-08-21 16:32:192479 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462480
[email protected]f7022f32014-08-21 16:32:192481 req->Start();
mmenkeed0498b2015-12-08 23:20:422482 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462483}
2484
2485// Make sure that URLRequest passes on its priority updates to its
2486// job.
2487TEST_F(URLRequestTest, SetJobPriority) {
2488 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362489 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162490 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2491 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462492
mmenkeed0498b2015-12-08 23:20:422493 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362494 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422495 req.get(), &default_network_delegate_, &job_priority));
2496 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462497
[email protected]f7022f32014-08-21 16:32:192498 req->SetPriority(LOW);
2499 req->Start();
mmenkeed0498b2015-12-08 23:20:422500 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462501
[email protected]f7022f32014-08-21 16:32:192502 req->SetPriority(MEDIUM);
2503 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422504 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462505}
2506
[email protected]bb1c4662013-11-14 00:00:072507// Setting the IGNORE_LIMITS load flag should be okay if the priority
2508// is MAXIMUM_PRIORITY.
2509TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2510 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362511 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162512 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2513 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192514 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072515
mmenkeed0498b2015-12-08 23:20:422516 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362517 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422518 req.get(), &default_network_delegate_, &job_priority));
2519 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072520
[email protected]f7022f32014-08-21 16:32:192521 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2522 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072523
[email protected]f7022f32014-08-21 16:32:192524 req->SetPriority(MAXIMUM_PRIORITY);
2525 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072526
[email protected]f7022f32014-08-21 16:32:192527 req->Start();
2528 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422529 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072530}
2531
nick5d570de92015-05-04 20:16:162532namespace {
2533
2534// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392535class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442536 public:
David Benjamin42116f62017-11-20 21:45:392537 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552538 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272539 }
tommycli59a63432015-11-06 00:10:552540
David Benjamin42116f62017-11-20 21:45:392541 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552542};
tommyclieae5f75f2015-11-05 19:07:272543
nick5d570de92015-05-04 20:16:162544} // namespace
2545
[email protected]f2f31b32013-01-16 23:24:092546TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392547 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442548 ASSERT_TRUE(test_server.Start());
2549
2550 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362551 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502552 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442553
2554 // Set up a cookie.
2555 {
2556 TestNetworkDelegate network_delegate;
2557 context.set_network_delegate(&network_delegate);
2558 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362559 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552560 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162561 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192562 req->Start();
Wez2a31b222018-06-07 22:07:152563 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442564 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2565 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2566 EXPECT_EQ(1, network_delegate.set_cookie_count());
2567 }
2568
2569 // Verify that the cookie is set.
2570 {
2571 TestNetworkDelegate network_delegate;
2572 context.set_network_delegate(&network_delegate);
2573 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362574 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162575 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2576 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192577 req->Start();
Wez2a31b222018-06-07 22:07:152578 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442579
2580 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2581 != std::string::npos);
2582 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2583 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2584 }
2585}
2586
[email protected]f2f31b32013-01-16 23:24:092587TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392588 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442589 ASSERT_TRUE(test_server.Start());
2590
2591 // Set up a cookie.
2592 {
2593 TestNetworkDelegate network_delegate;
2594 default_context_.set_network_delegate(&network_delegate);
2595 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362596 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552597 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162598 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192599 req->Start();
Wez2a31b222018-06-07 22:07:152600 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442601 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2602 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2603 }
2604
2605 // Verify that the cookie is set.
2606 {
2607 TestNetworkDelegate network_delegate;
2608 default_context_.set_network_delegate(&network_delegate);
2609 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362610 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162611 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2612 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192613 req->Start();
Wez2a31b222018-06-07 22:07:152614 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442615
2616 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2617 != std::string::npos);
2618 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2619 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2620 }
2621
2622 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2623 {
2624 TestNetworkDelegate network_delegate;
2625 default_context_.set_network_delegate(&network_delegate);
2626 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362627 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162628 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2629 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192630 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2631 req->Start();
Wez2a31b222018-06-07 22:07:152632 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442633
2634 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2635 == std::string::npos);
2636
2637 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2638 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2639 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2640 }
2641}
2642
2643TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392644 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442645 ASSERT_TRUE(test_server.Start());
2646
2647 // Set up a cookie.
2648 {
2649 TestNetworkDelegate network_delegate;
2650 default_context_.set_network_delegate(&network_delegate);
2651 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362652 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552653 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162654 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192655 req->Start();
Wez2a31b222018-06-07 22:07:152656 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442657
2658 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2659 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2660 EXPECT_EQ(1, network_delegate.set_cookie_count());
2661 }
2662
2663 // Try to set-up another cookie and update the previous cookie.
2664 {
2665 TestNetworkDelegate network_delegate;
2666 default_context_.set_network_delegate(&network_delegate);
2667 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362668 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552669 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162670 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192671 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2672 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442673
Wez2a31b222018-06-07 22:07:152674 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442675
2676 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2677 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2678 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2679 EXPECT_EQ(0, network_delegate.set_cookie_count());
2680 }
2681
2682 // Verify the cookies weren't saved or updated.
2683 {
2684 TestNetworkDelegate network_delegate;
2685 default_context_.set_network_delegate(&network_delegate);
2686 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362687 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162688 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2689 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192690 req->Start();
Wez2a31b222018-06-07 22:07:152691 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442692
2693 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2694 == std::string::npos);
2695 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2696 != std::string::npos);
2697
2698 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2699 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2700 EXPECT_EQ(0, network_delegate.set_cookie_count());
2701 }
2702}
2703
2704TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392705 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442706 ASSERT_TRUE(test_server.Start());
2707
2708 // Set up a cookie.
2709 {
2710 TestNetworkDelegate network_delegate;
2711 default_context_.set_network_delegate(&network_delegate);
2712 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362713 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552714 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162715 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192716 req->Start();
Wez2a31b222018-06-07 22:07:152717 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442718
2719 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2720 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2721 }
2722
2723 // Verify that the cookie is set.
2724 {
2725 TestNetworkDelegate network_delegate;
2726 default_context_.set_network_delegate(&network_delegate);
2727 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362728 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162729 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2730 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192731 req->Start();
Wez2a31b222018-06-07 22:07:152732 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442733
2734 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2735 != std::string::npos);
2736
2737 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739 }
2740
2741 // Verify that the cookie isn't sent.
2742 {
2743 TestNetworkDelegate network_delegate;
2744 default_context_.set_network_delegate(&network_delegate);
2745 TestDelegate d;
2746 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362747 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162748 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2749 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192750 req->Start();
Wez2a31b222018-06-07 22:07:152751 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442752
2753 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2754 == std::string::npos);
2755
[email protected]22e045f2013-09-20 03:54:032756 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442757 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2758 }
2759}
2760
marqf14fff8d2015-12-02 15:52:292761// TODO(crbug.com/564656) This test is flaky on iOS.
2762#if defined(OS_IOS)
2763#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2764#else
2765#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2766#endif
[email protected]316c1e5e2012-09-12 15:17:442767TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392768 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442769 ASSERT_TRUE(test_server.Start());
2770
2771 // Set up a cookie.
2772 {
2773 TestNetworkDelegate network_delegate;
2774 default_context_.set_network_delegate(&network_delegate);
2775 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362776 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552777 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162778 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192779 req->Start();
Wez2a31b222018-06-07 22:07:152780 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442781
2782 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2783 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2784 }
2785
2786 // Try to set-up another cookie and update the previous cookie.
2787 {
2788 TestNetworkDelegate network_delegate;
2789 default_context_.set_network_delegate(&network_delegate);
2790 TestDelegate d;
2791 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362792 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552793 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162794 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192795 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442796
Wez2a31b222018-06-07 22:07:152797 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442798
2799 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2800 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2801 }
2802
2803 // Verify the cookies weren't saved or updated.
2804 {
2805 TestNetworkDelegate network_delegate;
2806 default_context_.set_network_delegate(&network_delegate);
2807 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362808 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162809 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2810 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192811 req->Start();
Wez2a31b222018-06-07 22:07:152812 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442813
2814 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2815 == std::string::npos);
2816 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2817 != std::string::npos);
2818
2819 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2820 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2821 }
2822}
2823
2824TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:392825 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442826 ASSERT_TRUE(test_server.Start());
2827
2828 // Set up an empty cookie.
2829 {
2830 TestNetworkDelegate network_delegate;
2831 default_context_.set_network_delegate(&network_delegate);
2832 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362833 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162834 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2835 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192836 req->Start();
Wez2a31b222018-06-07 22:07:152837 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442838
2839 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2840 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2841 EXPECT_EQ(0, network_delegate.set_cookie_count());
2842 }
2843}
2844
2845TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392846 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442847 ASSERT_TRUE(test_server.Start());
2848
2849 // Set up a cookie.
2850 {
2851 TestNetworkDelegate network_delegate;
2852 default_context_.set_network_delegate(&network_delegate);
2853 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362854 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552855 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162856 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192857 req->Start();
Wez2a31b222018-06-07 22:07:152858 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442859
2860 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2861 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2862 }
2863
2864 // Verify that the cookie is set.
2865 {
2866 TestNetworkDelegate network_delegate;
2867 default_context_.set_network_delegate(&network_delegate);
2868 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362869 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162870 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2871 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192872 req->Start();
Wez2a31b222018-06-07 22:07:152873 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442874
2875 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2876 != std::string::npos);
2877
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 isn't sent.
2883 {
2884 TestNetworkDelegate network_delegate;
2885 default_context_.set_network_delegate(&network_delegate);
2886 TestDelegate d;
2887 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362888 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162889 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2890 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192891 req->Start();
Wez2a31b222018-06-07 22:07:152892 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442893
2894 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2895 == std::string::npos);
2896
[email protected]22e045f2013-09-20 03:54:032897 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442898 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2899 }
2900}
2901
2902TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392903 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442904 ASSERT_TRUE(test_server.Start());
2905
2906 // Set up a cookie.
2907 {
2908 TestNetworkDelegate network_delegate;
2909 default_context_.set_network_delegate(&network_delegate);
2910 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362911 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552912 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162913 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192914 req->Start();
Wez2a31b222018-06-07 22:07:152915 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442916
2917 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2918 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2919 }
2920
2921 // Try to set-up another cookie and update the previous cookie.
2922 {
2923 TestNetworkDelegate network_delegate;
2924 default_context_.set_network_delegate(&network_delegate);
2925 TestDelegate d;
2926 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362927 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552928 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162929 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192930 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442931
Wez2a31b222018-06-07 22:07:152932 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442933
2934 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2935 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2936 }
2937
2938 // Verify the cookies weren't saved or updated.
2939 {
2940 TestNetworkDelegate network_delegate;
2941 default_context_.set_network_delegate(&network_delegate);
2942 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362943 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162944 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2945 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192946 req->Start();
Wez2a31b222018-06-07 22:07:152947 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:442948
2949 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2950 == std::string::npos);
2951 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2952 != std::string::npos);
2953
2954 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2955 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2956 }
2957}
2958
mkwstc5fa7762016-03-28 09:28:232959TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:392960 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:262961 ASSERT_TRUE(test_server.Start());
2962
mkwst202534e32016-01-15 16:07:152963 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152964 default_context_.set_network_delegate(&network_delegate);
2965
mkwstf71d0bd2016-03-21 14:15:242966 const std::string kHost = "example.test";
2967 const std::string kSubHost = "subdomain.example.test";
2968 const std::string kCrossHost = "cross-origin.test";
2969
2970 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262971 {
mkwst3f3daac2015-02-26 20:15:262972 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362973 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242974 test_server.GetURL(kHost,
2975 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2976 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162977 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262978 req->Start();
Wez2a31b222018-06-07 22:07:152979 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:262980 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2981 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242982 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262983 }
2984
mkwstf71d0bd2016-03-21 14:15:242985 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262986 {
mkwst3f3daac2015-02-26 20:15:262987 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362988 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162989 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2990 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462991 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:462992 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262993 req->Start();
Wez2a31b222018-06-07 22:07:152994 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:262995
mkwstf71d0bd2016-03-21 14:15:242996 EXPECT_NE(std::string::npos,
2997 d.data_received().find("StrictSameSiteCookie=1"));
2998 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262999 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3000 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3001 }
3002
clamyfd58ca072016-12-21 17:18:323003 // Verify that both cookies are sent when the request has no initiator (can
3004 // happen for main frame browser-initiated navigations).
3005 {
3006 TestDelegate d;
3007 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163008 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3009 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463010 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:323011 req->Start();
Wez2a31b222018-06-07 22:07:153012 d.RunUntilComplete();
clamyfd58ca072016-12-21 17:18:323013
3014 EXPECT_NE(std::string::npos,
3015 d.data_received().find("StrictSameSiteCookie=1"));
3016 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3017 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3018 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3019 }
3020
mkwstf71d0bd2016-03-21 14:15:243021 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:263022 {
mkwst3f3daac2015-02-26 20:15:263023 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363024 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163025 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3026 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463027 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463028 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:153029 req->Start();
Wez2a31b222018-06-07 22:07:153030 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153031
mkwstf71d0bd2016-03-21 14:15:243032 EXPECT_NE(std::string::npos,
3033 d.data_received().find("StrictSameSiteCookie=1"));
3034 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153035 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 neither cookie is not sent for cross-site requests.
3040 {
3041 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363042 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(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463046 req->set_initiator(
3047 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243048 req->Start();
Wez2a31b222018-06-07 22:07:153049 d.RunUntilComplete();
mkwstf71d0bd2016-03-21 14:15:243050
3051 EXPECT_EQ(std::string::npos,
3052 d.data_received().find("StrictSameSiteCookie=1"));
3053 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3054 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3055 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3056 }
3057
3058 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153059 // method is "safe".
3060 {
3061 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363062 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163063 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3064 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463065 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463066 req->set_initiator(
3067 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243068 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153069 req->Start();
Wez2a31b222018-06-07 22:07:153070 d.RunUntilComplete();
mkwst202534e32016-01-15 16:07:153071
mkwstf71d0bd2016-03-21 14:15:243072 EXPECT_EQ(std::string::npos,
3073 d.data_received().find("StrictSameSiteCookie=1"));
3074 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153075 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3076 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3077 }
3078
mkwstf71d0bd2016-03-21 14:15:243079 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153080 // method is unsafe (e.g. POST).
3081 {
3082 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363083 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163084 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3085 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463086 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463087 req->set_initiator(
3088 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153089 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263090 req->Start();
Wez2a31b222018-06-07 22:07:153091 d.RunUntilComplete();
mkwst3f3daac2015-02-26 20:15:263092
mkwstf71d0bd2016-03-21 14:15:243093 EXPECT_EQ(std::string::npos,
3094 d.data_received().find("StrictSameSiteCookie=1"));
3095 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263096 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3097 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3098 }
3099}
3100
estark557a5eb82015-12-01 22:57:103101// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363102TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553103 EmbeddedTestServer http_server;
3104 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363105 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553106 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3107 https_server.AddDefaultHandlers(
3108 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3109 ASSERT_TRUE(http_server.Start());
3110 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363111
estarkb15166b2015-12-18 16:56:383112 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363113 TestURLRequestContext context(true);
3114 context.set_network_delegate(&network_delegate);
3115 context.Init();
3116
estarkb15166b2015-12-18 16:56:383117 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363118 {
3119 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363120 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103121 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163122 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363123 req->Start();
Wez2a31b222018-06-07 22:07:153124 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363125 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3126 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3127 }
3128
3129 // Verify that the cookie is not set.
3130 {
3131 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363132 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163133 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3134 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363135 req->Start();
Wez2a31b222018-06-07 22:07:153136 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363137
jww79aceda2015-12-07 01:56:343138 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3139 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363140 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3141 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3142 }
3143}
3144
estarkb15166b2015-12-18 16:56:383145TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553146 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3147 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363148 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553149 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363150
3151 TestNetworkDelegate network_delegate;
3152 TestURLRequestContext context(true);
3153 context.set_network_delegate(&network_delegate);
3154 context.Init();
3155
estarkb15166b2015-12-18 16:56:383156 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363157 {
3158 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163159 std::unique_ptr<URLRequest> req(context.CreateRequest(
3160 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3161 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363162 req->Start();
Wez2a31b222018-06-07 22:07:153163 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583164 EXPECT_EQ(0, network_delegate.set_cookie_count());
estarkcd39c11f2015-10-19 19:46:363165 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3166 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3167 }
3168
3169 // Verify that the cookie is not set.
3170 {
3171 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363172 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163173 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3174 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363175 req->Start();
Wez2a31b222018-06-07 22:07:153176 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363177
jww79aceda2015-12-07 01:56:343178 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363179 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3180 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3181 }
3182}
3183
estarkb15166b2015-12-18 16:56:383184TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553185 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3186 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363187 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553188 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363189
estarkb15166b2015-12-18 16:56:383190 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363191 TestURLRequestContext context(true);
3192 context.set_network_delegate(&network_delegate);
3193 context.Init();
3194
estarkb15166b2015-12-18 16:56:383195 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363196 {
3197 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363198 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103199 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163200 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363201 req->Start();
Wez2a31b222018-06-07 22:07:153202 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363203 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3204 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3205 }
3206
3207 // Verify that the cookie is set.
3208 {
3209 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363210 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163211 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3212 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363213 req->Start();
Wez2a31b222018-06-07 22:07:153214 d.RunUntilComplete();
estarkcd39c11f2015-10-19 19:46:363215
jww79aceda2015-12-07 01:56:343216 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3217 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3218 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3219 }
3220}
3221
3222// Tests that secure cookies can't be set on non-secure origins if strict secure
3223// cookies are enabled.
3224TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3225 EmbeddedTestServer http_server;
3226 http_server.AddDefaultHandlers(
3227 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3228 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3229 https_server.AddDefaultHandlers(
3230 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3231 ASSERT_TRUE(http_server.Start());
3232 ASSERT_TRUE(https_server.Start());
3233
3234 TestExperimentalFeaturesNetworkDelegate network_delegate;
3235 TestURLRequestContext context(true);
3236 context.set_network_delegate(&network_delegate);
3237 context.Init();
3238
3239 // Try to set a Secure cookie, with experimental features enabled.
3240 {
3241 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363242 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343243 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163244 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343245 req->Start();
Wez2a31b222018-06-07 22:07:153246 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343247 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3248 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3249 }
3250
3251 // Verify that the cookie is not set.
3252 {
3253 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363254 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163255 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3256 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343257 req->Start();
Wez2a31b222018-06-07 22:07:153258 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343259
3260 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3261 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3262 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3263 }
3264}
3265
3266// Tests that secure cookies can be set on secure origins even if strict secure
3267// cookies are enabled.
3268TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3269 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3270 https_server.AddDefaultHandlers(
3271 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3272 ASSERT_TRUE(https_server.Start());
3273
3274 TestExperimentalFeaturesNetworkDelegate network_delegate;
3275 TestURLRequestContext context(true);
3276 context.set_network_delegate(&network_delegate);
3277 context.Init();
3278
3279 // Try to set a Secure cookie, with experimental features enabled.
3280 {
3281 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363282 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343283 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163284 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343285 req->Start();
Wez2a31b222018-06-07 22:07:153286 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343287 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3288 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3289 }
3290
3291 // Verify that the cookie is not set.
3292 {
3293 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363294 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163295 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3296 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343297 req->Start();
Wez2a31b222018-06-07 22:07:153298 d.RunUntilComplete();
jww79aceda2015-12-07 01:56:343299
3300 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363301 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3302 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3303 }
3304}
3305
Thiemo Nagel0793b9c532018-04-18 16:57:583306// The parameter is true for same-site and false for cross-site requests.
3307class URLRequestTestParameterizedSameSite
3308 : public URLRequestTest,
3309 public ::testing::WithParamInterface<bool> {
3310 protected:
3311 URLRequestTestParameterizedSameSite() {
3312 auto params = std::make_unique<HttpNetworkSession::Params>();
3313 params->ignore_certificate_errors = true;
3314 context_.set_http_network_session_params(std::move(params));
3315 context_.set_network_delegate(&network_delegate_);
3316 https_server_.AddDefaultHandlers(
3317 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3318 EXPECT_TRUE(https_server_.Start());
3319 }
3320
3321 // To be called after configuration of |context_| has been finalized.
3322 void InitContext() { context_.Init(); }
3323
3324 const std::string kHost_ = "example.test";
3325 const std::string kCrossHost_ = "cross-site.test";
3326 TestURLRequestContext context_{true};
3327 TestNetworkDelegate network_delegate_;
3328 base::HistogramTester histograms_;
3329 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3330};
3331
3332INSTANTIATE_TEST_CASE_P(URLRequestTest,
3333 URLRequestTestParameterizedSameSite,
3334 ::testing::Bool());
3335
3336TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3337 const bool same_site = GetParam();
3338 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3339 InitContext();
3340
Mike West86149882017-07-28 10:41:493341 EmbeddedTestServer http_server;
3342 http_server.AddDefaultHandlers(
3343 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543344 ASSERT_TRUE(http_server.Start());
3345
Thiemo Nagel0793b9c532018-04-18 16:57:583346 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543347 {
3348 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583349 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3350 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543351 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3352 req->Start();
Wez2a31b222018-06-07 22:07:153353 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583354 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3355 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3356 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3357 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3358 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3359 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3360 0);
3361 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3362 0);
3363 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3364 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543365 }
3366
Thiemo Nagel0793b9c532018-04-18 16:57:583367 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543368 {
3369 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583370 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3371 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3372 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3373 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103374 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583375 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103376 req->Start();
Wez2a31b222018-06-07 22:07:153377 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583378 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3379 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3380 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3381 !same_site);
3382 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3383 same_site);
3384 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3385 0);
3386 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3387 0);
3388 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3389 same_site ? 0 : 2);
3390 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3391 same_site ? 2 : 0);
3392 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3393 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103394 }
3395
Thiemo Nagel0793b9c532018-04-18 16:57:583396 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103397 {
3398 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583399 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3400 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103401 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583402 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103403 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583404 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103405 req->Start();
Wez2a31b222018-06-07 22:07:153406 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583407 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3408 !same_site);
3409 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3410 same_site);
3411 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3412 !same_site);
3413 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3414 same_site);
3415 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3416 same_site ? 0 : 2);
3417 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3418 same_site ? 2 : 0);
3419 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3420 same_site ? 0 : 2);
3421 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3422 same_site ? 2 : 0);
3423 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3424 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3425 }
3426}
3427
3428// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3429TEST_P(URLRequestTestParameterizedSameSite,
3430 CookieNetworkSecurityMetricSecureAttribute) {
3431 const bool same_site = GetParam();
3432 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3433 InitContext();
3434
3435 // Set cookies.
3436 {
3437 TestDelegate d;
3438 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3439 https_server_.GetURL(kHost_,
3440 "/set-cookie?session-cookie=value;Secure&"
3441 "longlived-cookie=value;Secure;domain=" +
3442 kHost_ + ";Max-Age=360000"),
3443 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3444 req->Start();
Wez2a31b222018-06-07 22:07:153445 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583446 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3447 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3448 }
3449
3450 // Verify that the cookies fall into the correct metrics bucket.
3451 {
3452 TestDelegate d;
3453 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3454 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3455 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3456 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3457 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3458 req->Start();
Wez2a31b222018-06-07 22:07:153459 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583460 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3461 // Static cast of boolean required for MSVC 1911.
3462 histograms_.ExpectBucketCount(
3463 "Cookie.NetworkSecurity",
3464 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3465 static_cast<int>(!same_site),
3466 2);
3467 }
3468}
3469
3470// Short-lived host cookie --> k1pHSTSHostCookie
3471TEST_P(URLRequestTestParameterizedSameSite,
3472 CookieNetworkSecurityMetricShortlivedHostCookie) {
3473 const bool same_site = GetParam();
3474 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3475
3476 TransportSecurityState transport_security_state;
3477 transport_security_state.AddHSTS(
3478 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3479 false /* include_subdomains */);
3480 context_.set_transport_security_state(&transport_security_state);
3481 InitContext();
3482
3483 // Set cookie.
3484 {
3485 TestDelegate d;
3486 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3487 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3488 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3489 req->Start();
Wez2a31b222018-06-07 22:07:153490 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583491 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3492 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3493 }
3494
3495 // Verify that the cookie falls into the correct metrics bucket.
3496 {
3497 TestDelegate d;
3498 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3499 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3500 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3501 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3502 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3503 req->Start();
Wez2a31b222018-06-07 22:07:153504 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583505 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3506 // Static cast of boolean required for MSVC 1911.
3507 histograms_.ExpectBucketCount(
3508 "Cookie.NetworkSecurity",
3509 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3510 static_cast<int>(!same_site),
3511 1);
3512 }
3513}
3514
3515// Long-lived (either due to expiry or due to being a session cookie) host
3516// cookies --> k1pExpiringHSTSHostCookie
3517TEST_P(URLRequestTestParameterizedSameSite,
3518 CookieNetworkSecurityMetricLonglivedHostCookie) {
3519 const bool same_site = GetParam();
3520 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3521
3522 TransportSecurityState transport_security_state;
3523 transport_security_state.AddHSTS(
3524 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3525 false /* include_subdomains */);
3526 context_.set_transport_security_state(&transport_security_state);
3527 InitContext();
3528
3529 // Set cookies.
3530 {
3531 TestDelegate d;
3532 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3533 https_server_.GetURL(kHost_,
3534 "/set-cookie?session-cookie=value&"
3535 "longlived-cookie=value;Max-Age=360000"),
3536 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3537 req->Start();
Wez2a31b222018-06-07 22:07:153538 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583539 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3540 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3541 }
3542
3543 // Verify that the cookies fall into the correct metrics bucket.
3544 {
3545 TestDelegate d;
3546 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3547 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3548 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3549 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3550 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3551 req->Start();
Wez2a31b222018-06-07 22:07:153552 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583553 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3554 // Static cast of boolean required for MSVC 1911.
3555 histograms_.ExpectBucketCount(
3556 "Cookie.NetworkSecurity",
3557 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3558 static_cast<int>(!same_site),
3559 2);
3560 }
3561}
3562
3563// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3564// k1pHSTSSubdomainsIncluded
3565TEST_P(URLRequestTestParameterizedSameSite,
3566 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3567 const bool same_site = GetParam();
3568 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3569
3570 TransportSecurityState transport_security_state;
3571 transport_security_state.AddHSTS(
3572 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3573 true /* include_subdomains */);
3574 context_.set_transport_security_state(&transport_security_state);
3575 InitContext();
3576
3577 // Set cookie.
3578 {
3579 TestDelegate d;
3580 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3581 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3582 kHost_ + ";Max-Age=3600"),
3583 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3584 req->Start();
Wez2a31b222018-06-07 22:07:153585 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583586 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3587 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3588 }
3589
3590 // Verify that the cookie falls into the correct metrics bucket.
3591 {
3592 TestDelegate d;
3593 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3594 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3595 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3596 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3597 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3598 req->Start();
Wez2a31b222018-06-07 22:07:153599 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583600 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3601 // Static cast of boolean required for MSVC 1911.
3602 histograms_.ExpectBucketCount(
3603 "Cookie.NetworkSecurity",
3604 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3605 static_cast<int>(!same_site),
3606 1);
3607 }
3608}
3609
3610// Long-lived (either due to expiry or due to being a session cookie) domain
3611// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3612TEST_P(URLRequestTestParameterizedSameSite,
3613 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3614 const bool same_site = GetParam();
3615 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3616
3617 TransportSecurityState transport_security_state;
3618 transport_security_state.AddHSTS(
3619 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3620 true /* include_subdomains */);
3621 context_.set_transport_security_state(&transport_security_state);
3622 InitContext();
3623
3624 // Set cookies.
3625 {
3626 TestDelegate d;
3627 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3628 https_server_.GetURL(
3629 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3630 "longlived-cookie=value;domain=" + kHost_ +
3631 ";Max-Age=360000"),
3632 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3633 req->Start();
Wez2a31b222018-06-07 22:07:153634 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583635 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3636 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3637 }
3638
3639 // Verify that the cookies fall into the correct metrics bucket.
3640 {
3641 TestDelegate d;
3642 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3643 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3644 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3645 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3646 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3647 req->Start();
Wez2a31b222018-06-07 22:07:153648 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583649 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3650 // Static cast of boolean required for MSVC 1911.
3651 histograms_.ExpectBucketCount(
3652 "Cookie.NetworkSecurity",
3653 static_cast<int>(
3654 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3655 static_cast<int>(!same_site),
3656 2);
3657 }
3658}
3659
3660// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3661TEST_P(URLRequestTestParameterizedSameSite,
3662 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3663 const bool same_site = GetParam();
3664 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3665
3666 TransportSecurityState transport_security_state;
3667 transport_security_state.AddHSTS(
3668 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3669 false /* include_subdomains */);
3670 context_.set_transport_security_state(&transport_security_state);
3671 InitContext();
3672
3673 // Set cookie.
3674 {
3675 TestDelegate d;
3676 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3677 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3678 kHost_ + ";Max-Age=3600"),
3679 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3680 req->Start();
Wez2a31b222018-06-07 22:07:153681 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583682 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3683 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3684 }
3685
3686 // Verify that the cookie falls into the correct metrics bucket.
3687 {
3688 TestDelegate d;
3689 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3690 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3691 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3692 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3693 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3694 req->Start();
Wez2a31b222018-06-07 22:07:153695 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583696 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3697 // Static cast of boolean required for MSVC 1911.
3698 histograms_.ExpectBucketCount(
3699 "Cookie.NetworkSecurity",
3700 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3701 static_cast<int>(!same_site),
3702 1);
3703 }
3704}
3705
3706// Cookie without HSTS --> k1p(Non)SecureConnection
3707TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3708 const bool same_site = GetParam();
3709 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3710 InitContext();
3711
3712 EmbeddedTestServer http_server;
3713 http_server.AddDefaultHandlers(
3714 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3715 ASSERT_TRUE(http_server.Start());
3716
3717 // Set cookies.
3718 {
3719 TestDelegate d;
3720 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3721 https_server_.GetURL(kHost_,
3722 "/set-cookie?cookie=value;domain=" + kHost_ +
3723 ";Max-Age=3600&host-cookie=value"),
3724 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3725 req->Start();
Wez2a31b222018-06-07 22:07:153726 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583727 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3728 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3729 }
3730
3731 // Verify that the cookie falls into the correct metrics bucket.
3732 {
3733 TestDelegate d;
3734 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3735 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3736 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3737 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3738 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3739 req->Start();
Wez2a31b222018-06-07 22:07:153740 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583741 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3742 // Static cast of boolean required for MSVC 1911.
3743 histograms_.ExpectBucketCount(
3744 "Cookie.NetworkSecurity",
3745 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3746 static_cast<int>(!same_site),
3747 2);
3748 }
3749
3750 // Verify that the cookie falls into the correct metrics bucket.
3751 {
3752 TestDelegate d;
3753 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3754 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3755 TRAFFIC_ANNOTATION_FOR_TESTS));
3756 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3757 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3758 req->Start();
Wez2a31b222018-06-07 22:07:153759 d.RunUntilComplete();
Thiemo Nagel0793b9c532018-04-18 16:57:583760 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3761 // Static cast of boolean required for MSVC 1911.
3762 histograms_.ExpectBucketCount(
3763 "Cookie.NetworkSecurity",
3764 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3765 static_cast<int>(!same_site),
3766 2);
3767 // Static cast of boolean required for MSVC 1911.
3768 histograms_.ExpectBucketCount(
3769 "Cookie.NetworkSecurity",
3770 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3771 static_cast<int>(!same_site),
3772 2);
Mike West86149882017-07-28 10:41:493773 }
3774}
3775
mmenkefb18c772015-09-30 22:22:503776// Tests that a request is cancelled while entering suspend mode. Uses mocks
3777// rather than a spawned test server because the connection used to talk to
3778// the test server is affected by entering suspend mode on Android.
3779TEST_F(URLRequestTest, CancelOnSuspend) {
3780 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363781 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503782
3783 URLRequestFailedJob::AddUrlHandler();
3784
3785 TestDelegate d;
3786 // Request that just hangs.
3787 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
rhalavatib7bd7c792017-04-27 05:25:163788 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3789 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503790 r->Start();
3791
3792 power_monitor_source->Suspend();
3793 // Wait for the suspend notification to cause the request to fail.
Wez2a31b222018-06-07 22:07:153794 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:503795 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503796 EXPECT_TRUE(d.request_failed());
3797 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3798
3799 URLRequestFilter::GetInstance()->ClearHandlers();
3800
3801 // Shouldn't be needed, but just in case.
3802 power_monitor_source->Resume();
3803}
3804
[email protected]5095cd72012-11-01 10:29:163805// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3806// value for the |fixed_date| argument given to the constructor.
3807class FixedDateNetworkDelegate : public TestNetworkDelegate {
3808 public:
3809 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3810 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273811 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163812
[email protected]cba24642014-08-15 20:49:593813 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203814 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593815 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203816 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593817 const HttpResponseHeaders* original_response_headers,
3818 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133819 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163820
3821 private:
3822 std::string fixed_date_;
3823
3824 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3825};
3826
3827int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593828 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:203829 CompletionOnceCallback callback,
[email protected]cba24642014-08-15 20:49:593830 const HttpResponseHeaders* original_response_headers,
3831 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163832 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593833 HttpResponseHeaders* new_response_headers =
3834 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163835
3836 new_response_headers->RemoveHeader("Date");
3837 new_response_headers->AddHeader("Date: " + fixed_date_);
3838
3839 *override_response_headers = new_response_headers;
David Benjamind1f287bf2018-06-12 01:57:203840 return TestNetworkDelegate::OnHeadersReceived(
3841 request, std::move(callback), original_response_headers,
3842 override_response_headers, allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163843}
3844
3845// Test that cookie expiration times are adjusted for server/client clock
3846// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3847// headers by defaulting to GMT. (crbug.com/135131)
3848TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393849 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163850 ASSERT_TRUE(test_server.Start());
3851
3852 // Set up an expired cookie.
3853 {
3854 TestNetworkDelegate network_delegate;
3855 default_context_.set_network_delegate(&network_delegate);
3856 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363857 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193858 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553859 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163860 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193861 req->Start();
Wez2a31b222018-06-07 22:07:153862 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163863 }
3864 // Verify that the cookie is not set.
3865 {
3866 TestNetworkDelegate network_delegate;
3867 default_context_.set_network_delegate(&network_delegate);
3868 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363869 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163870 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3871 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193872 req->Start();
Wez2a31b222018-06-07 22:07:153873 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163874
3875 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3876 }
3877 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3878 {
3879 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3880 default_context_.set_network_delegate(&network_delegate);
3881 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363882 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193883 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553884 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163885 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193886 req->Start();
Wez2a31b222018-06-07 22:07:153887 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163888 }
3889 // Verify that the cookie is set.
3890 {
3891 TestNetworkDelegate network_delegate;
3892 default_context_.set_network_delegate(&network_delegate);
3893 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363894 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163895 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3896 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193897 req->Start();
Wez2a31b222018-06-07 22:07:153898 d.RunUntilComplete();
[email protected]5095cd72012-11-01 10:29:163899
3900 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3901 }
3902}
3903
3904
[email protected]316c1e5e2012-09-12 15:17:443905// Check that it is impossible to change the referrer in the extra headers of
3906// an URLRequest.
3907TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:393908 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443909 ASSERT_TRUE(test_server.Start());
3910
3911 // If extra headers contain referer and the request contains a referer,
3912 // only the latter shall be respected.
3913 {
3914 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363915 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163916 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3917 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193918 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443919
3920 HttpRequestHeaders headers;
3921 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193922 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443923
[email protected]f7022f32014-08-21 16:32:193924 req->Start();
Wez2a31b222018-06-07 22:07:153925 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443926
3927 EXPECT_EQ("http://foo.com/", d.data_received());
3928 }
3929
3930 // If extra headers contain a referer but the request does not, no referer
3931 // shall be sent in the header.
3932 {
3933 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363934 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163935 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3936 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443937
3938 HttpRequestHeaders headers;
3939 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193940 req->SetExtraRequestHeaders(headers);
3941 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443942
[email protected]f7022f32014-08-21 16:32:193943 req->Start();
Wez2a31b222018-06-07 22:07:153944 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:443945
3946 EXPECT_EQ("None", d.data_received());
3947 }
3948}
3949
[email protected]b89290212009-08-14 22:37:353950class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113951 public:
mmenke9f2ec60c2015-06-01 20:59:473952 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113953
[email protected]b89290212009-08-14 22:37:353954 protected:
[email protected]21184962011-10-26 00:50:303955 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3956 // |request_method| is the method to use for the initial request.
3957 // |redirect_method| is the method that is expected to be used for the second
3958 // request, after redirection.
3959 // If |include_data| is true, data is uploaded with the request. The
3960 // response body is expected to match it exactly, if and only if
3961 // |request_method| == |redirect_method|.
3962 void HTTPRedirectMethodTest(const GURL& redirect_url,
3963 const std::string& request_method,
3964 const std::string& redirect_method,
3965 bool include_data) {
3966 static const char kData[] = "hello world";
3967 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163968 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3969 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193970 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303971 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073972 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303973 HttpRequestHeaders headers;
3974 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:323975 base::NumberToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543976 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193977 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303978 }
[email protected]f7022f32014-08-21 16:32:193979 req->Start();
Wez2a31b222018-06-07 22:07:153980 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:193981 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503982 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303983 if (include_data) {
3984 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543985 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3986 HttpRequestHeaders::kContentLength));
3987 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3988 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303989 EXPECT_EQ(kData, d.data_received());
3990 } else {
svaldez5b3a8972015-10-09 23:23:543991 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3992 HttpRequestHeaders::kContentLength));
3993 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3994 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303995 EXPECT_NE(kData, d.data_received());
3996 }
3997 }
3998 if (HasFailure())
3999 LOG(WARNING) << "Request method was: " << request_method;
4000 }
4001
Alex Clarke1e08882b32017-10-06 14:22:404002 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
4003 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:514004 // |request_method| is the method to use for the initial request.
4005 // |redirect_method| is the method that is expected to be used for the second
4006 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:404007 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:514008 // redirection. If empty, expects that there will be no Origin header.
4009 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
4010 const std::string& request_method,
4011 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:404012 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:514013 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:164014 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
4015 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:514016 req->set_method(request_method);
4017 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
4018 redirect_url.GetOrigin().spec(), false);
4019 req->Start();
4020
Wez2a31b222018-06-07 22:07:154021 d.RunUntilComplete();
jww5fe460ff2015-03-28 00:22:514022
4023 EXPECT_EQ(redirect_method, req->method());
4024 // Note that there is no check for request success here because, for
4025 // purposes of testing, the request very well may fail. For example, if the
4026 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
4027 // origin, there is not an HTTPS server in this unit test framework, so the
4028 // request would fail. However, that's fine, as long as the request headers
4029 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:404030 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:514031 EXPECT_FALSE(
4032 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
4033 } else {
4034 std::string origin_header;
4035 EXPECT_TRUE(req->extra_request_headers().GetHeader(
4036 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:404037 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514038 }
4039 }
4040
[email protected]762d2db2010-01-11 19:03:014041 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014042 const int kMsgSize = 20000; // multiple of 10
4043 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484044 char* uploadBytes = new char[kMsgSize+1];
4045 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014046 char marker = 'a';
4047 for (int idx = 0; idx < kMsgSize/10; idx++) {
4048 memcpy(ptr, "----------", 10);
4049 ptr += 10;
4050 if (idx % 100 == 0) {
4051 ptr--;
4052 *ptr++ = marker;
4053 if (++marker > 'z')
4054 marker = 'a';
4055 }
4056 }
4057 uploadBytes[kMsgSize] = '\0';
4058
[email protected]762d2db2010-01-11 19:03:014059 for (int i = 0; i < kIterations; ++i) {
4060 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364061 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164062 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4063 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194064 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014065
mmenkecbc2b712014-10-09 20:29:074066 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014067
[email protected]f7022f32014-08-21 16:32:194068 r->Start();
4069 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014070
Wez2a31b222018-06-07 22:07:154071 d.RunUntilComplete();
[email protected]762d2db2010-01-11 19:03:014072
maksim.sisovb53724b52016-09-16 05:30:504073 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4074 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014075
4076 EXPECT_FALSE(d.received_data_before_response());
4077 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014078 }
4079 delete[] uploadBytes;
4080 }
4081
[email protected]ede03212012-09-07 12:52:264082 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344083 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364084 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554085 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:364086 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164087 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344088
[email protected]f7022f32014-08-21 16:32:194089 r->Start();
4090 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344091
Wez2a31b222018-06-07 22:07:154092 d.RunUntilComplete();
[email protected]263163f2012-06-14 22:40:344093
maksim.sisovb53724b52016-09-16 05:30:504094 if (d.request_status() != OK) {
4095 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4096 return false;
4097 }
[email protected]263163f2012-06-14 22:40:344098
maksim.sisovb53724b52016-09-16 05:30:504099 return true;
[email protected]263163f2012-06-14 22:40:344100 }
4101
David Benjamin42116f62017-11-20 21:45:394102 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504103
tommycli59a63432015-11-06 00:10:554104 private:
David Benjamin42116f62017-11-20 21:45:394105 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354106};
4107
tommycli59a63432015-11-06 00:10:554108namespace {
4109
danakj8522a25b2016-04-16 00:17:364110std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554111 const test_server::HttpRequest& request) {
4112 if (request.headers.find("Host") == request.headers.end() ||
4113 request.headers.at("Host") != "www.redirect.com" ||
4114 request.method != test_server::METHOD_CONNECT) {
4115 return nullptr;
4116 }
4117
danakj8522a25b2016-04-16 00:17:364118 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554119 new test_server::BasicHttpResponse);
4120 http_response->set_code(HTTP_FOUND);
4121 http_response->AddCustomHeader("Location",
4122 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484123 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554124}
4125
4126} // namespace
4127
nharperb7441ef2016-01-25 23:54:144128class TestSSLConfigService : public SSLConfigService {
4129 public:
Ryan Sleevi5b4702a2018-04-06 22:23:564130 TestSSLConfigService(bool online_rev_checking,
nharperb7441ef2016-01-25 23:54:144131 bool rev_checking_required_local_anchors,
4132 bool token_binding_enabled)
Ryan Sleevi5b4702a2018-04-06 22:23:564133 : online_rev_checking_(online_rev_checking),
nharperb7441ef2016-01-25 23:54:144134 rev_checking_required_local_anchors_(
4135 rev_checking_required_local_anchors),
4136 token_binding_enabled_(token_binding_enabled),
davidben095ebb52017-04-12 22:23:344137 min_version_(kDefaultSSLVersionMin),
4138 max_version_(kDefaultSSLVersionMax) {}
nharperb7441ef2016-01-25 23:54:144139
davidben095ebb52017-04-12 22:23:344140 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144141 void set_min_version(uint16_t version) { min_version_ = version; }
4142
nharperb7441ef2016-01-25 23:54:144143 // SSLConfigService:
4144 void GetSSLConfig(SSLConfig* config) override {
4145 *config = SSLConfig();
4146 config->rev_checking_enabled = online_rev_checking_;
nharperb7441ef2016-01-25 23:54:144147 config->rev_checking_required_local_anchors =
4148 rev_checking_required_local_anchors_;
davidben095ebb52017-04-12 22:23:344149 config->version_min = min_version_;
4150 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144151 if (token_binding_enabled_) {
4152 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
4153 }
4154 }
4155
4156 protected:
Chris Watkins7a41d3552017-12-01 02:13:274157 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144158
4159 private:
nharperb7441ef2016-01-25 23:54:144160 const bool online_rev_checking_;
4161 const bool rev_checking_required_local_anchors_;
4162 const bool token_binding_enabled_;
4163 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344164 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144165};
4166
4167// TODO(svaldez): Update tests to use EmbeddedTestServer.
4168#if !defined(OS_IOS)
4169class TokenBindingURLRequestTest : public URLRequestTestHTTP {
4170 public:
fdoray9f0b4782017-02-10 12:55:474171 TokenBindingURLRequestTest() = default;
fdoraya89e673c2017-01-31 21:44:214172
nharperb7441ef2016-01-25 23:54:144173 void SetUp() override {
4174 default_context_.set_ssl_config_service(
Ryan Sleevi5b4702a2018-04-06 22:23:564175 new TestSSLConfigService(false, false, true));
fdoraya89e673c2017-01-31 21:44:214176 channel_id_service_.reset(
4177 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:144178 default_context_.set_channel_id_service(channel_id_service_.get());
4179 URLRequestTestHTTP::SetUp();
4180 }
4181
4182 protected:
danakj8522a25b2016-04-16 00:17:364183 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:144184};
4185
4186TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
4187 SpawnedTestServer::SSLOptions ssl_options;
4188 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4189 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4190 ssl_options,
4191 base::FilePath(kTestFilePath));
4192 ASSERT_TRUE(https_test_server.Start());
4193
4194 TestDelegate d;
4195 {
danakj8522a25b2016-04-16 00:17:364196 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164197 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d,
4198 TRAFFIC_ANNOTATION_FOR_TESTS));
nharperb7441ef2016-01-25 23:54:144199 r->Start();
4200 EXPECT_TRUE(r->is_pending());
4201
Wez2a31b222018-06-07 22:07:154202 d.RunUntilComplete();
nharperb7441ef2016-01-25 23:54:144203
maksim.sisovb53724b52016-09-16 05:30:504204 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:144205
4206 HttpRequestHeaders headers;
4207 std::string token_binding_header, token_binding_message;
4208 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4209 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4210 &token_binding_header));
4211 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354212 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:144213 &token_binding_message));
nharperd6e65822016-03-30 23:05:484214 std::vector<TokenBinding> token_bindings;
4215 ASSERT_TRUE(
4216 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4217 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:144218
4219 EXPECT_GT(d.bytes_received(), 0);
4220 std::string ekm = d.data_received();
4221
nharperd6e65822016-03-30 23:05:484222 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354223 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4224 token_bindings[0].signature,
4225 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:144226 }
4227}
nharperd6e65822016-03-30 23:05:484228
4229TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
4230 SpawnedTestServer::SSLOptions ssl_options;
4231 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4232 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4233 ssl_options,
4234 base::FilePath(kTestFilePath));
4235 ASSERT_TRUE(https_test_server.Start());
4236
4237 TestDelegate d;
4238 {
4239 GURL redirect_url =
4240 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
rhalavatib7bd7c792017-04-27 05:25:164241 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4242 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484243 r->Start();
4244 EXPECT_TRUE(r->is_pending());
4245
Wez2a31b222018-06-07 22:07:154246 d.RunUntilComplete();
nharperd6e65822016-03-30 23:05:484247
maksim.sisovb53724b52016-09-16 05:30:504248 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484249
4250 HttpRequestHeaders headers;
4251 std::string token_binding_header, token_binding_message;
4252 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4253 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4254 &token_binding_header));
4255 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354256 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:484257 &token_binding_message));
4258 std::vector<TokenBinding> token_bindings;
4259 ASSERT_TRUE(
4260 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4261 ASSERT_EQ(2ull, token_bindings.size());
4262
4263 EXPECT_GT(d.bytes_received(), 0);
4264 std::string ekm = d.data_received();
4265
4266 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354267 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4268 token_bindings[0].signature,
4269 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:484270 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:354271 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
4272 token_bindings[1].signature,
4273 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:484274 }
4275}
4276
4277// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
4278// EmbeddedTestServer once crbug.com/599187 is resolved.
4279#if !defined(OS_ANDROID)
4280TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
Sergey Ulanov9e8d6f32017-08-14 22:12:584281 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP, base::FilePath());
nharperd6e65822016-03-30 23:05:484282 ASSERT_TRUE(http_server.Start());
4283 SpawnedTestServer::SSLOptions ssl_options;
4284 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4285 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4286 ssl_options,
4287 base::FilePath(kTestFilePath));
4288 ASSERT_TRUE(https_test_server.Start());
4289
4290 TestDelegate d;
4291 {
4292 GURL redirect_url = http_server.GetURL(
4293 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:164294 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4295 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484296 r->Start();
4297 EXPECT_TRUE(r->is_pending());
4298
Wez2a31b222018-06-07 22:07:154299 d.RunUntilComplete();
nharperd6e65822016-03-30 23:05:484300
maksim.sisovb53724b52016-09-16 05:30:504301 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484302
4303 HttpRequestHeaders headers;
4304 std::string token_binding_header, token_binding_message;
4305 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4306 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4307 &token_binding_header));
4308 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354309 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:484310 &token_binding_message));
4311 std::vector<TokenBinding> token_bindings;
4312 ASSERT_TRUE(
4313 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4314 ASSERT_EQ(1ull, token_bindings.size());
4315
4316 EXPECT_GT(d.bytes_received(), 0);
4317 std::string ekm = d.data_received();
4318
4319 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354320 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4321 token_bindings[0].signature,
4322 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:484323 }
4324}
4325
4326// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:364327// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:484328// support Token Binding, then we do not send a Sec-Token-Binding when following
4329// the redirect.
4330TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
4331 SpawnedTestServer::SSLOptions ssl_options;
4332 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4333 ssl_options,
4334 base::FilePath(kTestFilePath));
4335 ASSERT_TRUE(https_test_server.Start());
4336 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4337 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
4338 ssl_options,
4339 base::FilePath(kTestFilePath));
4340 ASSERT_TRUE(token_binding_test_server.Start());
4341
4342 TestDelegate d;
4343 {
4344 GURL redirect_url = token_binding_test_server.GetURL(
4345 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:164346 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4347 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484348 r->Start();
4349 EXPECT_TRUE(r->is_pending());
4350
Wez2a31b222018-06-07 22:07:154351 d.RunUntilComplete();
nharperd6e65822016-03-30 23:05:484352
maksim.sisovb53724b52016-09-16 05:30:504353 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484354
4355 HttpRequestHeaders headers;
4356 std::string token_binding_header, token_binding_message;
4357 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4358 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4359 &token_binding_header));
4360 }
4361}
4362#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:144363#endif // !defined(OS_IOS)
4364
4365// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114366// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554367// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114368// follow.
[email protected]f2f31b32013-01-16 23:24:094369TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554370 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124371 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554372 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114373
[email protected]ceefd7fd2012-11-29 00:36:244374 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044375 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554376 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504377
[email protected]d1ec59082009-02-11 02:48:154378 TestDelegate d;
4379 {
danakj8522a25b2016-04-16 00:17:364380 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164381 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4382 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194383 r->Start();
4384 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154385
Wez2a31b222018-06-07 22:07:154386 d.RunUntilComplete();
[email protected]d1ec59082009-02-11 02:48:154387
[email protected]d8fc4722014-06-13 13:17:154388 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474389 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504390 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084391 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154392 // We should not have followed the redirect.
4393 EXPECT_EQ(0, d.received_redirect_count());
4394 }
4395}
4396
[email protected]8202d0c2011-02-23 08:31:144397// This is the same as the previous test, but checks that the network delegate
4398// registers the error.
[email protected]c044616e2013-02-20 02:01:264399TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554400 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144401
[email protected]ceefd7fd2012-11-29 00:36:244402 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044403 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554404 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504405
[email protected]8202d0c2011-02-23 08:31:144406 TestDelegate d;
4407 {
danakj8522a25b2016-04-16 00:17:364408 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164409 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4410 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194411 r->Start();
4412 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144413
Wez2a31b222018-06-07 22:07:154414 d.RunUntilComplete();
[email protected]8202d0c2011-02-23 08:31:144415
[email protected]d8fc4722014-06-13 13:17:154416 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474417 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144418 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504419 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144420 // We should not have followed the redirect.
4421 EXPECT_EQ(0, d.received_redirect_count());
4422
4423 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014424 EXPECT_THAT(network_delegate.last_error(),
4425 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144426 }
4427}
4428
[email protected]dc5a5cf2012-09-26 02:49:304429// Tests that we can block and asynchronously return OK in various stages.
4430TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4431 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4432 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4433 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4434 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4435 };
4436 static const size_t blocking_stages_length = arraysize(blocking_stages);
4437
tommycli59a63432015-11-06 00:10:554438 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304439
4440 TestDelegate d;
4441 BlockingNetworkDelegate network_delegate(
4442 BlockingNetworkDelegate::USER_CALLBACK);
4443 network_delegate.set_block_on(
4444 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4445 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4446 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4447
4448 TestURLRequestContext context(true);
4449 context.set_network_delegate(&network_delegate);
4450 context.Init();
4451
4452 {
danakj8522a25b2016-04-16 00:17:364453 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164454 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4455 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304456
[email protected]f7022f32014-08-21 16:32:194457 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304458 for (size_t i = 0; i < blocking_stages_length; ++i) {
Wez2a31b222018-06-07 22:07:154459 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:304460 EXPECT_EQ(blocking_stages[i],
4461 network_delegate.stage_blocked_for_callback());
4462 network_delegate.DoCallback(OK);
4463 }
Wez2a31b222018-06-07 22:07:154464 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:194465 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504466 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304467 EXPECT_EQ(1, network_delegate.created_requests());
4468 EXPECT_EQ(0, network_delegate.destroyed_requests());
4469 }
4470 EXPECT_EQ(1, network_delegate.destroyed_requests());
4471}
4472
[email protected]4c76d7c2011-04-15 19:14:124473// Tests that the network delegate can block and cancel a request.
4474TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554475 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124476
4477 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304478 BlockingNetworkDelegate network_delegate(
4479 BlockingNetworkDelegate::AUTO_CALLBACK);
4480 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4481 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124482
[email protected]d5a4dd62012-05-23 01:41:044483 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554484 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504485
[email protected]4c76d7c2011-04-15 19:14:124486 {
rhalavatib7bd7c792017-04-27 05:25:164487 std::unique_ptr<URLRequest> r(
4488 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4489 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124490
[email protected]f7022f32014-08-21 16:32:194491 r->Start();
Wez2a31b222018-06-07 22:07:154492 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124493
[email protected]d8fc4722014-06-13 13:17:154494 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474495 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504496 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124497 EXPECT_EQ(1, network_delegate.created_requests());
4498 EXPECT_EQ(0, network_delegate.destroyed_requests());
4499 }
4500 EXPECT_EQ(1, network_delegate.destroyed_requests());
4501}
4502
[email protected]b4438d32012-09-27 06:15:304503// Helper function for NetworkDelegateCancelRequestAsynchronously and
4504// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4505// delegate operating in |block_mode| and a request for |url|. It blocks the
4506// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4507void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4508 BlockingNetworkDelegate::Stage stage,
4509 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364510 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304511 BlockingNetworkDelegate network_delegate(block_mode);
4512 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4513 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364514
[email protected]b4438d32012-09-27 06:15:304515 TestURLRequestContext context(true);
4516 context.set_network_delegate(&network_delegate);
4517 context.Init();
[email protected]3cd384c602011-08-31 16:12:364518
4519 {
rhalavatib7bd7c792017-04-27 05:25:164520 std::unique_ptr<URLRequest> r(context.CreateRequest(
4521 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364522
[email protected]f7022f32014-08-21 16:32:194523 r->Start();
Wez2a31b222018-06-07 22:07:154524 d.RunUntilComplete();
[email protected]3cd384c602011-08-31 16:12:364525
[email protected]d8fc4722014-06-13 13:17:154526 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474527 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4528 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4529 EXPECT_FALSE(r->proxy_server().is_valid());
4530 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4531 EXPECT_TRUE(r->proxy_server().is_direct());
4532 } else {
4533 NOTREACHED();
4534 }
maksim.sisovb53724b52016-09-16 05:30:504535 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364536 EXPECT_EQ(1, network_delegate.created_requests());
4537 EXPECT_EQ(0, network_delegate.destroyed_requests());
4538 }
4539 EXPECT_EQ(1, network_delegate.destroyed_requests());
4540}
4541
[email protected]b4438d32012-09-27 06:15:304542// The following 3 tests check that the network delegate can cancel a request
4543// synchronously in various stages of the request.
4544TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554545 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304546 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4547 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554548 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304549}
4550
4551TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554552 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304553 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4554 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554555 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304556}
4557
4558TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554559 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304560 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4561 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554562 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304563}
4564
4565// The following 3 tests check that the network delegate can cancel a request
4566// asynchronously in various stages of the request.
4567TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554568 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304569 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4570 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554571 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304572}
4573
4574TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554575 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304576 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4577 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554578 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304579}
4580
4581TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554582 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304583 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4584 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554585 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304586}
4587
[email protected]4c76d7c2011-04-15 19:14:124588// Tests that the network delegate can block and redirect a request to a new
4589// URL.
4590TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554591 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124592
4593 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304594 BlockingNetworkDelegate network_delegate(
4595 BlockingNetworkDelegate::AUTO_CALLBACK);
4596 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554597 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:124598 network_delegate.set_redirect_url(redirect_url);
4599
[email protected]d5a4dd62012-05-23 01:41:044600 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554601 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504602
[email protected]4c76d7c2011-04-15 19:14:124603 {
tommycli59a63432015-11-06 00:10:554604 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164605 std::unique_ptr<URLRequest> r(context.CreateRequest(
4606 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124607
[email protected]6be6fa92014-08-06 23:44:564608 // Quit after hitting the redirect, so can check the headers.
4609 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194610 r->Start();
Wez2a31b222018-06-07 22:07:154611 d.RunUntilComplete();
[email protected]4c76d7c2011-04-15 19:14:124612
[email protected]6be6fa92014-08-06 23:44:564613 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194614 EXPECT_EQ(307, r->GetResponseCode());
4615 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564616 std::string location;
[email protected]f7022f32014-08-21 16:32:194617 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4618 &location));
[email protected]6be6fa92014-08-06 23:44:564619 EXPECT_EQ(redirect_url, GURL(location));
4620
4621 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204622 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154623 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:504624 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474625 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4626 http_test_server()->host_port_pair()),
4627 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094628 // before_send_headers_with_proxy_count only increments for headers sent
4629 // through an untunneled proxy.
4630 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554631 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4632 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274633
maksim.sisovb53724b52016-09-16 05:30:504634 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194635 EXPECT_EQ(redirect_url, r->url());
4636 EXPECT_EQ(original_url, r->original_url());
4637 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124638 EXPECT_EQ(1, network_delegate.created_requests());
4639 EXPECT_EQ(0, network_delegate.destroyed_requests());
4640 }
4641 EXPECT_EQ(1, network_delegate.destroyed_requests());
4642}
4643
[email protected]b813ed72012-04-05 08:21:364644// Tests that the network delegate can block and redirect a request to a new
4645// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4646TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554647 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364648
4649 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304650 BlockingNetworkDelegate network_delegate(
4651 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:554652 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:364653 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364654
[email protected]d5a4dd62012-05-23 01:41:044655 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554656 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364657
4658 {
tommycli59a63432015-11-06 00:10:554659 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164660 std::unique_ptr<URLRequest> r(context.CreateRequest(
4661 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364662
[email protected]6be6fa92014-08-06 23:44:564663 // Quit after hitting the redirect, so can check the headers.
4664 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194665 r->Start();
Wez2a31b222018-06-07 22:07:154666 d.RunUntilComplete();
[email protected]b813ed72012-04-05 08:21:364667
[email protected]6be6fa92014-08-06 23:44:564668 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194669 EXPECT_EQ(307, r->GetResponseCode());
4670 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564671 std::string location;
[email protected]f7022f32014-08-21 16:32:194672 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4673 &location));
[email protected]6be6fa92014-08-06 23:44:564674 EXPECT_EQ(redirect_url, GURL(location));
4675
4676 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204677 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154678 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564679
maksim.sisovb53724b52016-09-16 05:30:504680 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474681 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4682 http_test_server()->host_port_pair()),
4683 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094684 // before_send_headers_with_proxy_count only increments for headers sent
4685 // through an untunneled proxy.
4686 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554687 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4688 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504689 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194690 EXPECT_EQ(redirect_url, r->url());
4691 EXPECT_EQ(original_url, r->original_url());
4692 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364693 EXPECT_EQ(1, network_delegate.created_requests());
4694 EXPECT_EQ(0, network_delegate.destroyed_requests());
4695 }
4696 EXPECT_EQ(1, network_delegate.destroyed_requests());
4697}
4698
[email protected]3c5ca8c2011-09-29 01:14:514699// Tests that redirects caused by the network delegate preserve POST data.
4700TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554701 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514702
4703 const char kData[] = "hello world";
4704
4705 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304706 BlockingNetworkDelegate network_delegate(
4707 BlockingNetworkDelegate::AUTO_CALLBACK);
4708 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554709 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514710 network_delegate.set_redirect_url(redirect_url);
4711
[email protected]ef2bf422012-05-11 03:27:094712 TestURLRequestContext context(true);
4713 context.set_network_delegate(&network_delegate);
4714 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514715
4716 {
tommycli59a63432015-11-06 00:10:554717 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164718 std::unique_ptr<URLRequest> r(context.CreateRequest(
4719 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194720 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074721 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514722 HttpRequestHeaders headers;
4723 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:324724 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194725 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564726
4727 // Quit after hitting the redirect, so can check the headers.
4728 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194729 r->Start();
Wez2a31b222018-06-07 22:07:154730 d.RunUntilComplete();
[email protected]3c5ca8c2011-09-29 01:14:514731
[email protected]6be6fa92014-08-06 23:44:564732 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194733 EXPECT_EQ(307, r->GetResponseCode());
4734 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564735 std::string location;
[email protected]f7022f32014-08-21 16:32:194736 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4737 &location));
[email protected]6be6fa92014-08-06 23:44:564738 EXPECT_EQ(redirect_url, GURL(location));
4739
4740 // Let the request finish.
Chong Zhang7607f1f2018-06-01 20:52:204741 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:154742 d.RunUntilComplete();
[email protected]6be6fa92014-08-06 23:44:564743
maksim.sisovb53724b52016-09-16 05:30:504744 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194745 EXPECT_EQ(redirect_url, r->url());
4746 EXPECT_EQ(original_url, r->original_url());
4747 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514748 EXPECT_EQ(1, network_delegate.created_requests());
4749 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194750 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514751 EXPECT_EQ(kData, d.data_received());
4752 }
4753 EXPECT_EQ(1, network_delegate.destroyed_requests());
4754}
4755
[email protected]5f714132014-03-26 10:41:164756// Tests that the network delegate can block and redirect a request to a new
4757// URL during OnHeadersReceived.
4758TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554759 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164760
4761 TestDelegate d;
4762 BlockingNetworkDelegate network_delegate(
4763 BlockingNetworkDelegate::AUTO_CALLBACK);
4764 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554765 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164766 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4767
4768 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554769 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164770
4771 {
tommycli59a63432015-11-06 00:10:554772 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164773 std::unique_ptr<URLRequest> r(context.CreateRequest(
4774 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164775
[email protected]f7022f32014-08-21 16:32:194776 r->Start();
Wez2a31b222018-06-07 22:07:154777 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:164778
maksim.sisovb53724b52016-09-16 05:30:504779 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474780 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4781 http_test_server()->host_port_pair()),
4782 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094783 // before_send_headers_with_proxy_count only increments for headers sent
4784 // through an untunneled proxy.
4785 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554786 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4787 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194788
maksim.sisovb53724b52016-09-16 05:30:504789 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194790 EXPECT_EQ(redirect_url, r->url());
4791 EXPECT_EQ(original_url, r->original_url());
4792 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164793 EXPECT_EQ(2, network_delegate.created_requests());
4794 EXPECT_EQ(0, network_delegate.destroyed_requests());
4795 }
4796 EXPECT_EQ(1, network_delegate.destroyed_requests());
4797}
4798
[email protected]c2911d72011-10-03 22:16:364799// Tests that the network delegate can synchronously complete OnAuthRequired
4800// by taking no action. This indicates that the NetworkDelegate does not want to
4801// handle the challenge, and is passing the buck along to the
4802// URLRequest::Delegate.
4803TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554804 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364805
4806 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304807 BlockingNetworkDelegate network_delegate(
4808 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364809
[email protected]ef2bf422012-05-11 03:27:094810 TestURLRequestContext context(true);
4811 context.set_network_delegate(&network_delegate);
4812 context.Init();
[email protected]c2911d72011-10-03 22:16:364813
[email protected]f3cf9802011-10-28 18:44:584814 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364815
4816 {
tommycli59a63432015-11-06 00:10:554817 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164818 std::unique_ptr<URLRequest> r(context.CreateRequest(
4819 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194820 r->Start();
[email protected]79e1fd62013-06-20 06:50:044821
Wez2a31b222018-06-07 22:07:154822 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044823
maksim.sisovb53724b52016-09-16 05:30:504824 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194825 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044826 EXPECT_TRUE(d.auth_required_called());
4827 EXPECT_EQ(1, network_delegate.created_requests());
4828 EXPECT_EQ(0, network_delegate.destroyed_requests());
4829 }
4830 EXPECT_EQ(1, network_delegate.destroyed_requests());
4831}
4832
4833TEST_F(URLRequestTestHTTP,
4834 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554835 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044836
4837 TestDelegate d;
4838 BlockingNetworkDelegate network_delegate(
4839 BlockingNetworkDelegate::SYNCHRONOUS);
4840
4841 TestURLRequestContext context(true);
4842 context.set_network_delegate(&network_delegate);
4843 context.Init();
4844
4845 d.set_credentials(AuthCredentials(kUser, kSecret));
4846
4847 {
tommycli59a63432015-11-06 00:10:554848 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164849 std::unique_ptr<URLRequest> r(context.CreateRequest(
4850 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194851 r->Start();
[email protected]79e1fd62013-06-20 06:50:044852
Wez2a31b222018-06-07 22:07:154853 d.RunUntilComplete();
shivanisha8061c4202017-06-13 23:35:524854
[email protected]79e1fd62013-06-20 06:50:044855 {
4856 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194857 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524858 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044859 }
4860
maksim.sisovb53724b52016-09-16 05:30:504861 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194862 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364863 EXPECT_TRUE(d.auth_required_called());
4864 EXPECT_EQ(1, network_delegate.created_requests());
4865 EXPECT_EQ(0, network_delegate.destroyed_requests());
4866 }
4867 EXPECT_EQ(1, network_delegate.destroyed_requests());
4868}
4869
4870// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404871// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364872TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554873 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364874
4875 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304876 BlockingNetworkDelegate network_delegate(
4877 BlockingNetworkDelegate::SYNCHRONOUS);
4878 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364879 network_delegate.set_auth_retval(
4880 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4881
[email protected]f3cf9802011-10-28 18:44:584882 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364883
[email protected]ef2bf422012-05-11 03:27:094884 TestURLRequestContext context(true);
4885 context.set_network_delegate(&network_delegate);
4886 context.Init();
[email protected]c2911d72011-10-03 22:16:364887
4888 {
tommycli59a63432015-11-06 00:10:554889 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164890 std::unique_ptr<URLRequest> r(context.CreateRequest(
4891 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194892 r->Start();
Wez2a31b222018-06-07 22:07:154893 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364894
maksim.sisovb53724b52016-09-16 05:30:504895 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194896 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364897 EXPECT_FALSE(d.auth_required_called());
4898 EXPECT_EQ(1, network_delegate.created_requests());
4899 EXPECT_EQ(0, network_delegate.destroyed_requests());
4900 }
4901 EXPECT_EQ(1, network_delegate.destroyed_requests());
4902}
4903
[email protected]79e1fd62013-06-20 06:50:044904// Same as above, but also tests that GetFullRequestHeaders returns the proper
4905// headers (for the first or second request) when called at the proper times.
4906TEST_F(URLRequestTestHTTP,
4907 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554908 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044909
4910 TestDelegate d;
4911 BlockingNetworkDelegate network_delegate(
4912 BlockingNetworkDelegate::SYNCHRONOUS);
4913 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4914 network_delegate.set_auth_retval(
4915 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4916
4917 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4918
4919 TestURLRequestContext context(true);
4920 context.set_network_delegate(&network_delegate);
4921 context.Init();
4922
4923 {
tommycli59a63432015-11-06 00:10:554924 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164925 std::unique_ptr<URLRequest> r(context.CreateRequest(
4926 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194927 r->Start();
Wez2a31b222018-06-07 22:07:154928 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:044929
maksim.sisovb53724b52016-09-16 05:30:504930 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194931 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044932 EXPECT_FALSE(d.auth_required_called());
4933 EXPECT_EQ(1, network_delegate.created_requests());
4934 EXPECT_EQ(0, network_delegate.destroyed_requests());
4935
4936 {
4937 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194938 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044939 EXPECT_TRUE(headers.HasHeader("Authorization"));
4940 }
4941 }
4942 EXPECT_EQ(1, network_delegate.destroyed_requests());
4943}
4944
[email protected]c2911d72011-10-03 22:16:364945// Tests that the network delegate can synchronously complete OnAuthRequired
4946// by cancelling authentication.
4947TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554948 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364949
4950 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304951 BlockingNetworkDelegate network_delegate(
4952 BlockingNetworkDelegate::SYNCHRONOUS);
4953 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364954 network_delegate.set_auth_retval(
4955 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4956
[email protected]ef2bf422012-05-11 03:27:094957 TestURLRequestContext context(true);
4958 context.set_network_delegate(&network_delegate);
4959 context.Init();
[email protected]c2911d72011-10-03 22:16:364960
4961 {
tommycli59a63432015-11-06 00:10:554962 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164963 std::unique_ptr<URLRequest> r(context.CreateRequest(
4964 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194965 r->Start();
Wez2a31b222018-06-07 22:07:154966 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:364967
maksim.sisovb53724b52016-09-16 05:30:504968 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194969 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364970 EXPECT_FALSE(d.auth_required_called());
4971 EXPECT_EQ(1, network_delegate.created_requests());
4972 EXPECT_EQ(0, network_delegate.destroyed_requests());
4973 }
4974 EXPECT_EQ(1, network_delegate.destroyed_requests());
4975}
4976
4977// Tests that the network delegate can asynchronously complete OnAuthRequired
4978// by taking no action. This indicates that the NetworkDelegate does not want
4979// to handle the challenge, and is passing the buck along to the
4980// URLRequest::Delegate.
4981TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554982 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364983
4984 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304985 BlockingNetworkDelegate network_delegate(
4986 BlockingNetworkDelegate::AUTO_CALLBACK);
4987 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364988
[email protected]ef2bf422012-05-11 03:27:094989 TestURLRequestContext context(true);
4990 context.set_network_delegate(&network_delegate);
4991 context.Init();
[email protected]c2911d72011-10-03 22:16:364992
[email protected]f3cf9802011-10-28 18:44:584993 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364994
4995 {
tommycli59a63432015-11-06 00:10:554996 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164997 std::unique_ptr<URLRequest> r(context.CreateRequest(
4998 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194999 r->Start();
Wez2a31b222018-06-07 22:07:155000 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365001
maksim.sisovb53724b52016-09-16 05:30:505002 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195003 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365004 EXPECT_TRUE(d.auth_required_called());
5005 EXPECT_EQ(1, network_delegate.created_requests());
5006 EXPECT_EQ(0, network_delegate.destroyed_requests());
5007 }
5008 EXPECT_EQ(1, network_delegate.destroyed_requests());
5009}
5010
5011// Tests that the network delegate can asynchronously complete OnAuthRequired
5012// by setting credentials.
5013TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:555014 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365015
5016 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305017 BlockingNetworkDelegate network_delegate(
5018 BlockingNetworkDelegate::AUTO_CALLBACK);
5019 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365020 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365021 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5022
[email protected]f3cf9802011-10-28 18:44:585023 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:365024 network_delegate.set_auth_credentials(auth_credentials);
5025
[email protected]ef2bf422012-05-11 03:27:095026 TestURLRequestContext context(true);
5027 context.set_network_delegate(&network_delegate);
5028 context.Init();
[email protected]c2911d72011-10-03 22:16:365029
5030 {
tommycli59a63432015-11-06 00:10:555031 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165032 std::unique_ptr<URLRequest> r(context.CreateRequest(
5033 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195034 r->Start();
Wez2a31b222018-06-07 22:07:155035 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365036
maksim.sisovb53724b52016-09-16 05:30:505037 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195038 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365039 EXPECT_FALSE(d.auth_required_called());
5040 EXPECT_EQ(1, network_delegate.created_requests());
5041 EXPECT_EQ(0, network_delegate.destroyed_requests());
5042 }
5043 EXPECT_EQ(1, network_delegate.destroyed_requests());
5044}
5045
5046// Tests that the network delegate can asynchronously complete OnAuthRequired
5047// by cancelling authentication.
5048TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555049 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365050
5051 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305052 BlockingNetworkDelegate network_delegate(
5053 BlockingNetworkDelegate::AUTO_CALLBACK);
5054 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365055 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365056 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5057
[email protected]ef2bf422012-05-11 03:27:095058 TestURLRequestContext context(true);
5059 context.set_network_delegate(&network_delegate);
5060 context.Init();
[email protected]c2911d72011-10-03 22:16:365061
5062 {
tommycli59a63432015-11-06 00:10:555063 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165064 std::unique_ptr<URLRequest> r(context.CreateRequest(
5065 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195066 r->Start();
Wez2a31b222018-06-07 22:07:155067 d.RunUntilComplete();
[email protected]c2911d72011-10-03 22:16:365068
maksim.sisovb53724b52016-09-16 05:30:505069 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195070 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365071 EXPECT_FALSE(d.auth_required_called());
5072 EXPECT_EQ(1, network_delegate.created_requests());
5073 EXPECT_EQ(0, network_delegate.destroyed_requests());
5074 }
5075 EXPECT_EQ(1, network_delegate.destroyed_requests());
5076}
5077
David Benjamin0bda12f2018-02-07 19:58:455078// Tests that NetworkDelegate header overrides from the 401 response do not
5079// affect the 200 response. This is a regression test for
5080// https://crbug.com/801237.
5081TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5082 ASSERT_TRUE(http_test_server()->Start());
5083
5084 TestDelegate d;
5085 d.set_credentials(AuthCredentials(kUser, kSecret));
5086 default_network_delegate_.set_add_header_to_first_response(true);
5087
5088 {
5089 GURL url(http_test_server()->GetURL("/auth-basic"));
5090 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5091 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5092 r->Start();
5093
Wez2a31b222018-06-07 22:07:155094 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455095
5096 EXPECT_EQ(OK, d.request_status());
5097 EXPECT_EQ(200, r->GetResponseCode());
5098 EXPECT_TRUE(d.auth_required_called());
5099 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5100 }
5101
5102 {
5103 GURL url(http_test_server()->GetURL("/defaultresponse"));
5104 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5105 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5106 r->Start();
5107
Wez2a31b222018-06-07 22:07:155108 d.RunUntilComplete();
David Benjamin0bda12f2018-02-07 19:58:455109
5110 // Check that set_add_header_to_first_response normally adds a header.
5111 EXPECT_EQ(OK, d.request_status());
5112 EXPECT_EQ(200, r->GetResponseCode());
5113 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5114 }
5115}
5116
[email protected]9045b8822012-01-13 20:35:355117// Tests that we can handle when a network request was canceled while we were
5118// waiting for the network delegate.
5119// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5120TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555121 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355122
5123 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305124 BlockingNetworkDelegate network_delegate(
5125 BlockingNetworkDelegate::USER_CALLBACK);
5126 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355127
[email protected]ef2bf422012-05-11 03:27:095128 TestURLRequestContext context(true);
5129 context.set_network_delegate(&network_delegate);
5130 context.Init();
[email protected]9045b8822012-01-13 20:35:355131
5132 {
rhalavatib7bd7c792017-04-27 05:25:165133 std::unique_ptr<URLRequest> r(
5134 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5135 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355136
[email protected]f7022f32014-08-21 16:32:195137 r->Start();
Wez2a31b222018-06-07 22:07:155138 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305139 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5140 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355141 EXPECT_EQ(0, network_delegate.completed_requests());
5142 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195143 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355144 // Ensure that network delegate is notified.
5145 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505146 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355147 EXPECT_EQ(1, network_delegate.created_requests());
5148 EXPECT_EQ(0, network_delegate.destroyed_requests());
5149 }
5150 EXPECT_EQ(1, network_delegate.destroyed_requests());
5151}
5152
5153// Tests that we can handle when a network request was canceled while we were
5154// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005155// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5156// callback.
[email protected]9045b8822012-01-13 20:35:355157TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555158 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355159
5160 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305161 BlockingNetworkDelegate network_delegate(
5162 BlockingNetworkDelegate::USER_CALLBACK);
5163 network_delegate.set_block_on(
5164 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:355165
[email protected]ef2bf422012-05-11 03:27:095166 TestURLRequestContext context(true);
5167 context.set_network_delegate(&network_delegate);
5168 context.Init();
[email protected]9045b8822012-01-13 20:35:355169
5170 {
rhalavatib7bd7c792017-04-27 05:25:165171 std::unique_ptr<URLRequest> r(
5172 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5173 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355174
[email protected]f7022f32014-08-21 16:32:195175 r->Start();
Wez2a31b222018-06-07 22:07:155176 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305177 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
5178 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355179 EXPECT_EQ(0, network_delegate.completed_requests());
5180 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195181 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355182 // Ensure that network delegate is notified.
5183 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505184 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355185 EXPECT_EQ(1, network_delegate.created_requests());
5186 EXPECT_EQ(0, network_delegate.destroyed_requests());
5187 }
5188 EXPECT_EQ(1, network_delegate.destroyed_requests());
5189}
5190
5191// Tests that we can handle when a network request was canceled while we were
5192// waiting for the network delegate.
5193// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5194TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555195 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355196
5197 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305198 BlockingNetworkDelegate network_delegate(
5199 BlockingNetworkDelegate::USER_CALLBACK);
5200 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355201
[email protected]ef2bf422012-05-11 03:27:095202 TestURLRequestContext context(true);
5203 context.set_network_delegate(&network_delegate);
5204 context.Init();
[email protected]9045b8822012-01-13 20:35:355205
5206 {
rhalavatib7bd7c792017-04-27 05:25:165207 std::unique_ptr<URLRequest> r(
5208 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5209 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355210
[email protected]f7022f32014-08-21 16:32:195211 r->Start();
Wez2a31b222018-06-07 22:07:155212 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305213 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5214 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355215 EXPECT_EQ(0, network_delegate.completed_requests());
5216 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195217 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355218 // Ensure that network delegate is notified.
5219 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505220 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355221 EXPECT_EQ(1, network_delegate.created_requests());
5222 EXPECT_EQ(0, network_delegate.destroyed_requests());
5223 }
5224 EXPECT_EQ(1, network_delegate.destroyed_requests());
5225}
5226
5227// Tests that we can handle when a network request was canceled while we were
5228// waiting for the network delegate.
5229// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025230TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555231 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355232
5233 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305234 BlockingNetworkDelegate network_delegate(
5235 BlockingNetworkDelegate::USER_CALLBACK);
5236 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355237
[email protected]ef2bf422012-05-11 03:27:095238 TestURLRequestContext context(true);
5239 context.set_network_delegate(&network_delegate);
5240 context.Init();
[email protected]9045b8822012-01-13 20:35:355241
5242 {
danakj8522a25b2016-04-16 00:17:365243 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165244 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5245 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355246
[email protected]f7022f32014-08-21 16:32:195247 r->Start();
Wez2a31b222018-06-07 22:07:155248 network_delegate.RunUntilBlocked();
[email protected]dc5a5cf2012-09-26 02:49:305249 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5250 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355251 EXPECT_EQ(0, network_delegate.completed_requests());
5252 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195253 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355254 // Ensure that network delegate is notified.
5255 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505256 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355257 EXPECT_EQ(1, network_delegate.created_requests());
5258 EXPECT_EQ(0, network_delegate.destroyed_requests());
5259 }
5260 EXPECT_EQ(1, network_delegate.destroyed_requests());
5261}
5262
tommycli59a63432015-11-06 00:10:555263namespace {
5264
danakj8522a25b2016-04-16 00:17:365265std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555266 const test_server::HttpRequest& request) {
5267 if (request.headers.find("Host") == request.headers.end() ||
5268 request.headers.at("Host") != "www.server-auth.com" ||
5269 request.method != test_server::METHOD_CONNECT) {
5270 return nullptr;
5271 }
5272
danakj8522a25b2016-04-16 00:17:365273 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555274 new test_server::BasicHttpResponse);
5275 http_response->set_code(HTTP_UNAUTHORIZED);
5276 http_response->AddCustomHeader("WWW-Authenticate",
5277 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485278 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555279}
5280
5281} // namespace
5282
5283// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115284// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555285// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355286TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555287 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125288 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555289 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115290
[email protected]ceefd7fd2012-11-29 00:36:245291 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045292 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555293 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505294
[email protected]dc651782009-02-14 01:45:085295 TestDelegate d;
5296 {
danakj8522a25b2016-04-16 00:17:365297 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165298 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5299 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085300
[email protected]f7022f32014-08-21 16:32:195301 r->Start();
5302 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085303
Wez2a31b222018-06-07 22:07:155304 d.RunUntilComplete();
[email protected]dc651782009-02-14 01:45:085305
[email protected]d8fc4722014-06-13 13:17:155306 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475307 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505308 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085309 }
5310}
5311
[email protected]b89290212009-08-14 22:37:355312TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555313 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115314
initial.commit586acc5fe2008-07-26 22:42:525315 TestDelegate d;
5316 {
danakj8522a25b2016-04-16 00:17:365317 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165318 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5319 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525320
[email protected]f7022f32014-08-21 16:32:195321 r->Start();
5322 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525323
Wez2a31b222018-06-07 22:07:155324 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525325
5326 EXPECT_EQ(1, d.response_started_count());
5327 EXPECT_FALSE(d.received_data_before_response());
5328 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555329 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195330 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555331 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195332 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:165333
[email protected]9e743cd2010-03-16 07:03:535334 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525335 }
initial.commit586acc5fe2008-07-26 22:42:525336}
5337
[email protected]263163f2012-06-14 22:40:345338// This test has the server send a large number of cookies to the client.
5339// To ensure that no number of cookies causes a crash, a galloping binary
5340// search is used to estimate that maximum number of cookies that are accepted
5341// by the browser. Beyond the maximum number, the request will fail with
5342// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315343#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305344// http://crbug.com/177916
5345#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5346#else
5347#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5348#endif // defined(OS_WIN)
5349TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555350 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345351
5352 int lower_bound = 0;
5353 int upper_bound = 1;
5354
5355 // Double the number of cookies until the response header limits are
5356 // exceeded.
5357 while (DoManyCookiesRequest(upper_bound)) {
5358 lower_bound = upper_bound;
5359 upper_bound *= 2;
5360 ASSERT_LT(upper_bound, 1000000);
5361 }
5362
pkasting6b68a162014-12-01 22:10:295363 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345364 if (tolerance < 2)
5365 tolerance = 2;
5366
5367 // Perform a binary search to find the highest possible number of cookies,
5368 // within the desired tolerance.
5369 while (upper_bound - lower_bound >= tolerance) {
5370 int num_cookies = (lower_bound + upper_bound) / 2;
5371
5372 if (DoManyCookiesRequest(num_cookies))
5373 lower_bound = num_cookies;
5374 else
5375 upper_bound = num_cookies;
5376 }
5377 // Success: the test did not crash.
5378}
5379
[email protected]b89290212009-08-14 22:37:355380TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555381 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115382
initial.commit586acc5fe2008-07-26 22:42:525383 TestDelegate d;
5384 {
danakj8522a25b2016-04-16 00:17:365385 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165386 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5387 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525388
[email protected]f7022f32014-08-21 16:32:195389 r->Start();
5390 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525391
Wez2a31b222018-06-07 22:07:155392 d.RunUntilComplete();
initial.commit586acc5fe2008-07-26 22:42:525393
5394 EXPECT_EQ(1, d.response_started_count());
5395 EXPECT_FALSE(d.received_data_before_response());
5396 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555397 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195398 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555399 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195400 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:525401 }
[email protected]5d7b373e2009-09-02 07:19:035402}
5403
[email protected]79e1fd62013-06-20 06:50:045404TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555405 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045406
5407 TestDelegate d;
5408 {
tommycli59a63432015-11-06 00:10:555409 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:165410 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5411 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045412
5413 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195414 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045415
[email protected]f7022f32014-08-21 16:32:195416 r->Start();
5417 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045418
Wez2a31b222018-06-07 22:07:155419 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:045420
5421 EXPECT_EQ(1, d.response_started_count());
5422 EXPECT_FALSE(d.received_data_before_response());
5423 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555424 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195425 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555426 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195427 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:045428
5429 EXPECT_TRUE(d.have_full_request_headers());
5430 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5431 }
5432}
5433
[email protected]58e32bb2013-01-21 18:23:255434TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555435 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255436
5437 TestDelegate d;
5438 {
danakj8522a25b2016-04-16 00:17:365439 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165440 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5441 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255442
[email protected]f7022f32014-08-21 16:32:195443 r->Start();
5444 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255445
Wez2a31b222018-06-07 22:07:155446 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255447
5448 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195449 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255450 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5451
5452 EXPECT_EQ(1, d.response_started_count());
5453 EXPECT_FALSE(d.received_data_before_response());
5454 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555455 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195456 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555457 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195458 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255459 }
5460}
5461
tommycli59a63432015-11-06 00:10:555462// TODO(svaldez): Update tests to use EmbeddedTestServer.
5463#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395464TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555465 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555466 base::FilePath(kTestFilePath));
5467
5468 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395469
5470 // Parameter that specifies the Content-Length field in the response:
5471 // C - Compressed length.
5472 // U - Uncompressed length.
5473 // L - Large length (larger than both C & U).
5474 // M - Medium length (between C & U).
5475 // S - Small length (smaller than both C & U).
5476 const char test_parameters[] = "CULMS";
5477 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5478 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445479 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395480 // S has too little data, but we seem to accept it.
5481 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375482 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395483
xunjielifb4da222016-07-14 18:38:595484 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195485 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595486 file_path = file_path.Append(kTestFilePath);
5487 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5488 std::string expected_content;
5489 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5490
5491 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395492 TestDelegate d;
5493 {
tommycli59a63432015-11-06 00:10:555494 std::string test_file = base::StringPrintf(
5495 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395496
[email protected]ceefd7fd2012-11-29 00:36:245497 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095498 TestURLRequestContext context(true);
5499 context.set_network_delegate(&network_delegate);
5500 context.Init();
[email protected]87a09a92011-07-14 15:50:505501
rhalavatib7bd7c792017-04-27 05:25:165502 std::unique_ptr<URLRequest> r(
5503 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5504 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195505 r->Start();
5506 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395507
Wez2a31b222018-06-07 22:07:155508 d.RunUntilComplete();
[email protected]aad63572011-05-24 20:14:395509
5510 EXPECT_EQ(1, d.response_started_count());
5511 EXPECT_FALSE(d.received_data_before_response());
5512 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505513 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395514 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505515 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5516 << "\"";
xunjielifb4da222016-07-14 18:38:595517 if (test_parameters[i] == 'S') {
5518 // When content length is smaller than both compressed length and
5519 // uncompressed length, HttpStreamParser might not read the full
5520 // response body.
5521 continue;
5522 }
5523 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395524 } else {
maksim.sisovb53724b52016-09-16 05:30:505525 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395526 << " Parameter = \"" << test_file << "\"";
5527 }
5528 }
5529 }
5530}
tommycli59a63432015-11-06 00:10:555531#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395532
[email protected]58e32bb2013-01-21 18:23:255533TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555534 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255535
tommycli59a63432015-11-06 00:10:555536 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455537 GURL original_url =
tommycli59a63432015-11-06 00:10:555538 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255539 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165540 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5541 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195542 req->Start();
Wez2a31b222018-06-07 22:07:155543 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:255544
5545 EXPECT_EQ(1, d.response_started_count());
5546 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195547 EXPECT_EQ(destination_url, req->url());
5548 EXPECT_EQ(original_url, req->original_url());
5549 ASSERT_EQ(2U, req->url_chain().size());
5550 EXPECT_EQ(original_url, req->url_chain()[0]);
5551 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255552
5553 LoadTimingInfo load_timing_info_before_redirect;
5554 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5555 &load_timing_info_before_redirect));
5556 TestLoadTimingNotReused(load_timing_info_before_redirect,
5557 CONNECT_TIMING_HAS_DNS_TIMES);
5558
5559 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195560 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255561 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5562
5563 // Check that a new socket was used on redirect, since the server does not
5564 // supposed keep-alive sockets, and that the times before the redirect are
5565 // before the ones recorded for the second request.
5566 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5567 load_timing_info.socket_log_id);
5568 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5569 load_timing_info.connect_timing.connect_start);
5570}
5571
[email protected]8f1ac082011-04-19 21:14:135572TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555573 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135574
tommycli59a63432015-11-06 00:10:555575 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455576 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555577 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5578 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5579 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135580 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165581 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5582 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195583 req->Start();
Wez2a31b222018-06-07 22:07:155584 d.RunUntilComplete();
[email protected]8f1ac082011-04-19 21:14:135585
5586 EXPECT_EQ(1, d.response_started_count());
5587 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195588 EXPECT_EQ(destination_url, req->url());
5589 EXPECT_EQ(original_url, req->original_url());
5590 ASSERT_EQ(3U, req->url_chain().size());
5591 EXPECT_EQ(original_url, req->url_chain()[0]);
5592 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5593 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135594}
5595
[email protected]abe1c4a2013-10-25 19:28:515596// First and second pieces of information logged by delegates to URLRequests.
5597const char kFirstDelegateInfo[] = "Wonderful delegate";
5598const char kSecondDelegateInfo[] = "Exciting delegate";
5599
5600// Logs delegate information to a URLRequest. The first string is logged
5601// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5602// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5603// another asynchronous call is used to clear the delegate information
5604// before calling a callback. The object then deletes itself.
5605class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5606 public:
David Benjamind1f287bf2018-06-12 01:57:205607 using Callback = base::OnceCallback<void()>;
[email protected]abe1c4a2013-10-25 19:28:515608
5609 // Each time delegate information is added to the URLRequest, the resulting
5610 // load state is checked. The expected load state after each request is
5611 // passed in as an argument.
5612 static void Run(URLRequest* url_request,
5613 LoadState expected_first_load_state,
5614 LoadState expected_second_load_state,
5615 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205616 Callback callback) {
[email protected]abe1c4a2013-10-25 19:28:515617 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
David Benjamind1f287bf2018-06-12 01:57:205618 url_request, expected_first_load_state, expected_second_load_state,
5619 expected_third_load_state, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515620 logger->Start();
5621 }
5622
5623 // Checks that the log entries, starting with log_position, contain the
5624 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5625 // recorded. Returns the index of entry after the expected number of
5626 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465627 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515628 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515629 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5630 if (log_position + 3 >= entries.size()) {
5631 ADD_FAILURE() << "Not enough log entries";
5632 return entries.size();
5633 }
5634 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005635 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5636 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075637 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515638 &delegate_info));
5639 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5640
5641 ++log_position;
mikecirone8b85c432016-09-08 19:11:005642 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5643 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515644
5645 ++log_position;
mikecirone8b85c432016-09-08 19:11:005646 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5647 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075648 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515649 &delegate_info));
5650 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5651
5652 ++log_position;
mikecirone8b85c432016-09-08 19:11:005653 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5654 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515655
5656 return log_position + 1;
5657 }
5658
5659 private:
5660 friend class base::RefCounted<AsyncDelegateLogger>;
5661
5662 AsyncDelegateLogger(URLRequest* url_request,
5663 LoadState expected_first_load_state,
5664 LoadState expected_second_load_state,
5665 LoadState expected_third_load_state,
David Benjamind1f287bf2018-06-12 01:57:205666 Callback callback)
[email protected]abe1c4a2013-10-25 19:28:515667 : url_request_(url_request),
5668 expected_first_load_state_(expected_first_load_state),
5669 expected_second_load_state_(expected_second_load_state),
5670 expected_third_load_state_(expected_third_load_state),
David Benjamind1f287bf2018-06-12 01:57:205671 callback_(std::move(callback)) {}
[email protected]abe1c4a2013-10-25 19:28:515672
Chris Watkins7a41d3552017-12-01 02:13:275673 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515674
5675 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535676 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515677 LoadStateWithParam load_state = url_request_->GetLoadState();
5678 EXPECT_EQ(expected_first_load_state_, load_state.state);
5679 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455680 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155681 FROM_HERE,
5682 base::BindOnce(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515683 }
5684
5685 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535686 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515687 LoadStateWithParam load_state = url_request_->GetLoadState();
5688 EXPECT_EQ(expected_second_load_state_, load_state.state);
5689 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5690 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5691 } else {
5692 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5693 }
skyostil4891b25b2015-06-11 11:43:455694 base::ThreadTaskRunnerHandle::Get()->PostTask(
Wez2a31b222018-06-07 22:07:155695 FROM_HERE, base::BindOnce(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515696 }
5697
5698 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535699 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515700 LoadStateWithParam load_state = url_request_->GetLoadState();
5701 EXPECT_EQ(expected_third_load_state_, load_state.state);
5702 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085703 EXPECT_EQ(base::string16(), load_state.param);
David Benjamind1f287bf2018-06-12 01:57:205704 std::move(callback_).Run();
[email protected]abe1c4a2013-10-25 19:28:515705 }
5706
5707 URLRequest* url_request_;
5708 const int expected_first_load_state_;
5709 const int expected_second_load_state_;
5710 const int expected_third_load_state_;
David Benjamind1f287bf2018-06-12 01:57:205711 Callback callback_;
[email protected]abe1c4a2013-10-25 19:28:515712
5713 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5714};
5715
5716// NetworkDelegate that logs delegate information before a request is started,
5717// before headers are sent, when headers are read, and when auth information
5718// is requested. Uses AsyncDelegateLogger.
5719class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5720 public:
Chris Watkins7a41d3552017-12-01 02:13:275721 AsyncLoggingNetworkDelegate() = default;
5722 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515723
5724 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205725 int OnBeforeURLRequest(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205726 CompletionOnceCallback callback,
dchengb03027d2014-10-21 12:00:205727 GURL* new_url) override {
David Benjamind1f287bf2018-06-12 01:57:205728 // TestNetworkDelegate always completes synchronously.
5729 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeURLRequest(
5730 request, base::NullCallback(), new_url));
5731 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515732 }
5733
ryansturm2343cb62016-06-15 01:09:005734 int OnBeforeStartTransaction(URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205735 CompletionOnceCallback callback,
ryansturm2343cb62016-06-15 01:09:005736 HttpRequestHeaders* headers) override {
David Benjamind1f287bf2018-06-12 01:57:205737 // TestNetworkDelegate always completes synchronously.
5738 CHECK_NE(ERR_IO_PENDING, TestNetworkDelegate::OnBeforeStartTransaction(
5739 request, base::NullCallback(), headers));
5740 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515741 }
5742
dchengb03027d2014-10-21 12:00:205743 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515744 URLRequest* request,
David Benjamind1f287bf2018-06-12 01:57:205745 CompletionOnceCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515746 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165747 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135748 GURL* allowed_unsafe_redirect_url) override {
David Benjamind1f287bf2018-06-12 01:57:205749 // TestNetworkDelegate always completes synchronously.
5750 CHECK_NE(ERR_IO_PENDING,
5751 TestNetworkDelegate::OnHeadersReceived(
5752 request, base::NullCallback(), original_response_headers,
5753 override_response_headers, allowed_unsafe_redirect_url));
5754 return RunCallbackAsynchronously(request, std::move(callback));
[email protected]abe1c4a2013-10-25 19:28:515755 }
5756
dchengb03027d2014-10-21 12:00:205757 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515758 URLRequest* request,
5759 const AuthChallengeInfo& auth_info,
David Benjamind1f287bf2018-06-12 01:57:205760 AuthCallback callback,
mostynbba063d6032014-10-09 11:01:135761 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515762 AsyncDelegateLogger::Run(
David Benjamind1f287bf2018-06-12 01:57:205763 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5764 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5765 base::BindOnce(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5766 std::move(callback), credentials));
[email protected]abe1c4a2013-10-25 19:28:515767 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5768 }
5769
5770 private:
David Benjamind1f287bf2018-06-12 01:57:205771 static int RunCallbackAsynchronously(URLRequest* request,
5772 CompletionOnceCallback callback) {
5773 AsyncDelegateLogger::Run(request, LOAD_STATE_WAITING_FOR_DELEGATE,
5774 LOAD_STATE_WAITING_FOR_DELEGATE,
5775 LOAD_STATE_WAITING_FOR_DELEGATE,
5776 base::BindOnce(std::move(callback), OK));
[email protected]abe1c4a2013-10-25 19:28:515777 return ERR_IO_PENDING;
5778 }
5779
David Benjamind1f287bf2018-06-12 01:57:205780 static void SetAuthAndResume(AuthCallback callback,
[email protected]abe1c4a2013-10-25 19:28:515781 AuthCredentials* credentials) {
5782 *credentials = AuthCredentials(kUser, kSecret);
David Benjamind1f287bf2018-06-12 01:57:205783 std::move(callback).Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
[email protected]abe1c4a2013-10-25 19:28:515784 }
5785
5786 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5787};
5788
5789// URLRequest::Delegate that logs delegate information when the headers
5790// are received, when each read completes, and during redirects. Uses
5791// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5792//
5793// Inherits from TestDelegate to reuse the TestDelegate code to handle
5794// advancing to the next step in most cases, as well as cancellation.
5795class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5796 public:
5797 enum CancelStage {
5798 NO_CANCEL = 0,
5799 CANCEL_ON_RECEIVED_REDIRECT,
5800 CANCEL_ON_RESPONSE_STARTED,
5801 CANCEL_ON_READ_COMPLETED
5802 };
5803
5804 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5805 : cancel_stage_(cancel_stage) {
5806 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5807 set_cancel_in_received_redirect(true);
5808 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5809 set_cancel_in_response_started(true);
5810 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5811 set_cancel_in_received_data(true);
5812 }
Chris Watkins7a41d3552017-12-01 02:13:275813 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515814
5815 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205816 void OnReceivedRedirect(URLRequest* request,
5817 const RedirectInfo& redirect_info,
5818 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515819 *defer_redirect = true;
5820 AsyncDelegateLogger::Run(
5821 request,
5822 LOAD_STATE_WAITING_FOR_DELEGATE,
5823 LOAD_STATE_WAITING_FOR_DELEGATE,
5824 LOAD_STATE_WAITING_FOR_DELEGATE,
5825 base::Bind(
5826 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595827 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515828 }
5829
maksim.sisov0f4aa142016-09-05 05:55:285830 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515831 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285832 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5833 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5834 base::Bind(
5835 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5836 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515837 }
5838
dchengb03027d2014-10-21 12:00:205839 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515840 AsyncDelegateLogger::Run(
5841 request,
5842 LOAD_STATE_IDLE,
5843 LOAD_STATE_IDLE,
5844 LOAD_STATE_IDLE,
5845 base::Bind(
5846 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5847 base::Unretained(this), request, bytes_read));
5848 }
5849
5850 private:
5851 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595852 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515853 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595854 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515855 // FollowDeferredRedirect should not be called after cancellation.
5856 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5857 return;
5858 if (!defer_redirect)
Chong Zhang7607f1f2018-06-01 20:52:205859 request->FollowDeferredRedirect(
5860 base::nullopt /* modified_request_headers */);
[email protected]abe1c4a2013-10-25 19:28:515861 }
5862
maksim.sisov0f4aa142016-09-05 05:55:285863 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515864 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285865 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515866 }
5867
5868 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5869 // The parent class continues the request.
5870 TestDelegate::OnReadCompleted(request, bytes_read);
5871 }
5872
5873 const CancelStage cancel_stage_;
5874
5875 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5876};
5877
5878// Tests handling of delegate info before a request starts.
5879TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555880 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515881
5882 TestDelegate request_delegate;
5883 TestURLRequestContext context(true);
5884 context.set_network_delegate(NULL);
5885 context.set_net_log(&net_log_);
5886 context.Init();
5887
5888 {
rhalavatib7bd7c792017-04-27 05:25:165889 std::unique_ptr<URLRequest> r(context.CreateRequest(
5890 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5891 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195892 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515893 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085894 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515895
5896 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195897 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515898 LOAD_STATE_WAITING_FOR_DELEGATE,
5899 LOAD_STATE_WAITING_FOR_DELEGATE,
5900 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195901 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515902
Wez2a31b222018-06-07 22:07:155903 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515904
[email protected]f7022f32014-08-21 16:32:195905 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505906 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515907 }
5908
mmenke43758e62015-05-04 21:09:465909 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515910 net_log_.GetEntries(&entries);
5911 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005912 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515913
5914 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5915
5916 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005917 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5918 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515919}
5920
5921// Tests handling of delegate info from a network delegate.
5922TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555923 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515924
5925 TestDelegate request_delegate;
5926 AsyncLoggingNetworkDelegate network_delegate;
5927 TestURLRequestContext context(true);
5928 context.set_network_delegate(&network_delegate);
5929 context.set_net_log(&net_log_);
5930 context.Init();
5931
5932 {
rhalavatib7bd7c792017-04-27 05:25:165933 std::unique_ptr<URLRequest> r(context.CreateRequest(
5934 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5935 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195936 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515937 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085938 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515939
[email protected]f7022f32014-08-21 16:32:195940 r->Start();
Wez2a31b222018-06-07 22:07:155941 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515942
[email protected]f7022f32014-08-21 16:32:195943 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505944 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515945 EXPECT_EQ(1, network_delegate.created_requests());
5946 EXPECT_EQ(0, network_delegate.destroyed_requests());
5947 }
5948 EXPECT_EQ(1, network_delegate.destroyed_requests());
5949
5950 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465951 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515952 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:155953 static const NetLogEventType kExpectedEvents[] = {
5954 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
5955 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
5956 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
5957 };
5958 for (NetLogEventType event : kExpectedEvents) {
5959 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:515960 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:155961 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515962
5963 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5964 log_position + 1);
5965
5966 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:155967 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:005968 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515969 }
5970
mikecirone8b85c432016-09-08 19:11:005971 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5972 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515973}
5974
5975// Tests handling of delegate info from a network delegate in the case of an
5976// HTTP redirect.
5977TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555978 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515979
5980 TestDelegate request_delegate;
5981 AsyncLoggingNetworkDelegate network_delegate;
5982 TestURLRequestContext context(true);
5983 context.set_network_delegate(&network_delegate);
5984 context.set_net_log(&net_log_);
5985 context.Init();
5986
5987 {
danakj8522a25b2016-04-16 00:17:365988 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555989 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165990 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195991 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515992 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085993 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515994
[email protected]f7022f32014-08-21 16:32:195995 r->Start();
Wez2a31b222018-06-07 22:07:155996 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515997
[email protected]f7022f32014-08-21 16:32:195998 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505999 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516000 EXPECT_EQ(2, network_delegate.created_requests());
6001 EXPECT_EQ(0, network_delegate.destroyed_requests());
6002 }
6003 EXPECT_EQ(1, network_delegate.destroyed_requests());
6004
6005 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466006 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516007 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156008 static const NetLogEventType kExpectedEvents[] = {
6009 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6010 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6011 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6012 };
6013 for (NetLogEventType event : kExpectedEvents) {
6014 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516015 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156016 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516017
David Benjamin9776ca22018-06-13 00:00:156018 log_position =
6019 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516020
6021 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156022 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006023 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516024 }
6025
6026 // The URLRequest::Delegate then gets informed about the redirect.
6027 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156028 entries, log_position + 1,
6029 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
mikecirone8b85c432016-09-08 19:11:006030 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516031
6032 // The NetworkDelegate logged information in the same three events as before.
David Benjamin9776ca22018-06-13 00:00:156033 for (NetLogEventType event : kExpectedEvents) {
6034 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516035 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156036 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516037
6038 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6039 log_position + 1);
6040
6041 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156042 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006043 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516044 }
6045
mikecirone8b85c432016-09-08 19:11:006046 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6047 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516048}
6049
6050// Tests handling of delegate info from a network delegate in the case of HTTP
6051// AUTH.
6052TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556053 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516054
6055 TestDelegate request_delegate;
6056 AsyncLoggingNetworkDelegate network_delegate;
6057 TestURLRequestContext context(true);
6058 context.set_network_delegate(&network_delegate);
6059 context.set_net_log(&net_log_);
6060 context.Init();
6061
6062 {
rhalavatib7bd7c792017-04-27 05:25:166063 std::unique_ptr<URLRequest> r(context.CreateRequest(
6064 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6065 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196066 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516067 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086068 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516069
[email protected]f7022f32014-08-21 16:32:196070 r->Start();
Wez2a31b222018-06-07 22:07:156071 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516072
[email protected]f7022f32014-08-21 16:32:196073 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506074 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516075 EXPECT_EQ(1, network_delegate.created_requests());
6076 EXPECT_EQ(0, network_delegate.destroyed_requests());
6077 }
6078 EXPECT_EQ(1, network_delegate.destroyed_requests());
6079
6080 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466081 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516082 net_log_.GetEntries(&entries);
David Benjamin9776ca22018-06-13 00:00:156083 static const NetLogEventType kExpectedEvents[] = {
6084 NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST,
6085 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6086 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6087 NetLogEventType::NETWORK_DELEGATE_AUTH_REQUIRED,
6088 NetLogEventType::NETWORK_DELEGATE_BEFORE_START_TRANSACTION,
6089 NetLogEventType::NETWORK_DELEGATE_HEADERS_RECEIVED,
6090 };
6091 for (NetLogEventType event : kExpectedEvents) {
6092 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516093 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156094 entries, log_position + 1, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516095
David Benjamin9776ca22018-06-13 00:00:156096 log_position =
6097 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516098
6099 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156100 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006101 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516102 }
6103
mikecirone8b85c432016-09-08 19:11:006104 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6105 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516106}
6107
tommycli59a63432015-11-06 00:10:556108// TODO(svaldez): Update tests to use EmbeddedTestServer.
6109#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516110// Tests handling of delegate info from a URLRequest::Delegate.
6111TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556112 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556113 base::FilePath(kTestFilePath));
6114
6115 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516116
6117 AsyncLoggingUrlRequestDelegate request_delegate(
6118 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6119 TestURLRequestContext context(true);
6120 context.set_network_delegate(NULL);
6121 context.set_net_log(&net_log_);
6122 context.Init();
6123
6124 {
6125 // A chunked response with delays between chunks is used to make sure that
6126 // attempts by the URLRequest delegate to log information while reading the
6127 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486128 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516129 // that it occurs.
danakj8522a25b2016-04-16 00:17:366130 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556131 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166132 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196133 LoadStateWithParam load_state = r->GetLoadState();
6134 r->Start();
Wez2a31b222018-06-07 22:07:156135 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516136
[email protected]f7022f32014-08-21 16:32:196137 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506138 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516139 }
6140
mmenke43758e62015-05-04 21:09:466141 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516142 net_log_.GetEntries(&entries);
6143
[email protected]1826a402014-01-08 15:40:486144 size_t log_position = 0;
6145
[email protected]abe1c4a2013-10-25 19:28:516146 // The delegate info should only have been logged on header complete. Other
6147 // times it should silently be ignored.
David Benjamin9776ca22018-06-13 00:00:156148 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
6149 entries, 0, NetLogEventType::NETWORK_DELEGATE_BEFORE_URL_REQUEST));
mikecirone8b85c432016-09-08 19:11:006150 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156151 entries, log_position + 1,
6152 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
mikecirone8b85c432016-09-08 19:11:006153 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516154
David Benjamin9776ca22018-06-13 00:00:156155 log_position =
6156 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516157
6158 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156159 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6160 entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006161 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516162
mikecirone8b85c432016-09-08 19:11:006163 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6164 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516165 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
David Benjamin9776ca22018-06-13 00:00:156166 entries, log_position + 1,
6167 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED));
[email protected]abe1c4a2013-10-25 19:28:516168}
tommycli59a63432015-11-06 00:10:556169#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516170
6171// Tests handling of delegate info from a URLRequest::Delegate in the case of
6172// an HTTP redirect.
6173TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556174 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516175
6176 AsyncLoggingUrlRequestDelegate request_delegate(
6177 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6178 TestURLRequestContext context(true);
6179 context.set_network_delegate(NULL);
6180 context.set_net_log(&net_log_);
6181 context.Init();
6182
6183 {
danakj8522a25b2016-04-16 00:17:366184 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556185 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166186 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196187 LoadStateWithParam load_state = r->GetLoadState();
6188 r->Start();
Wez2a31b222018-06-07 22:07:156189 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516190
[email protected]f7022f32014-08-21 16:32:196191 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506192 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516193 }
6194
mmenke43758e62015-05-04 21:09:466195 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516196 net_log_.GetEntries(&entries);
6197
6198 // Delegate info should only have been logged in OnReceivedRedirect and
6199 // OnResponseStarted.
6200 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156201 static const NetLogEventType kExpectedEvents[] = {
6202 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6203 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6204 };
6205 for (NetLogEventType event : kExpectedEvents) {
6206 SCOPED_TRACE(NetLog::EventTypeToString(event));
6207 log_position = ExpectLogContainsSomewhereAfter(entries, log_position, event,
6208 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516209
David Benjamin9776ca22018-06-13 00:00:156210 log_position =
6211 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516212
6213 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156214 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006215 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516216 }
6217
mikecirone8b85c432016-09-08 19:11:006218 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6219 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516220}
6221
6222// Tests handling of delegate info from a URLRequest::Delegate in the case of
6223// an HTTP redirect, with cancellation at various points.
6224TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556225 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516226
6227 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6228 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6229 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6230 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6231 };
6232
David Benjamin9776ca22018-06-13 00:00:156233 for (auto cancel_stage : kCancelStages) {
6234 AsyncLoggingUrlRequestDelegate request_delegate(cancel_stage);
vishal.b62985ca92015-04-17 08:45:516235 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046236 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:516237 context.set_network_delegate(NULL);
6238 context.set_net_log(&net_log);
6239 context.Init();
6240
6241 {
danakj8522a25b2016-04-16 00:17:366242 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556243 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166244 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196245 LoadStateWithParam load_state = r->GetLoadState();
6246 r->Start();
Wez2a31b222018-06-07 22:07:156247 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506248 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156249
6250 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6251 // the |request_delegate| completion task.
6252 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516253 }
6254
mmenke43758e62015-05-04 21:09:466255 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516256 net_log.GetEntries(&entries);
6257
6258 // Delegate info is always logged in both OnReceivedRedirect and
6259 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6260 // OnResponseStarted delegate call is after cancellation, but logging is
6261 // still currently supported in that call.
6262 size_t log_position = 0;
David Benjamin9776ca22018-06-13 00:00:156263 static const NetLogEventType kExpectedEvents[] = {
6264 NetLogEventType::URL_REQUEST_DELEGATE_RECEIVED_REDIRECT,
6265 NetLogEventType::URL_REQUEST_DELEGATE_RESPONSE_STARTED,
6266 };
6267 for (NetLogEventType event : kExpectedEvents) {
6268 SCOPED_TRACE(NetLog::EventTypeToString(event));
[email protected]abe1c4a2013-10-25 19:28:516269 log_position = ExpectLogContainsSomewhereAfter(
David Benjamin9776ca22018-06-13 00:00:156270 entries, log_position, event, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516271
David Benjamin9776ca22018-06-13 00:00:156272 log_position =
6273 AsyncDelegateLogger::CheckDelegateInfo(entries, log_position + 1);
[email protected]abe1c4a2013-10-25 19:28:516274
6275 ASSERT_LT(log_position, entries.size());
David Benjamin9776ca22018-06-13 00:00:156276 EXPECT_EQ(event, entries[log_position].type);
mikecirone8b85c432016-09-08 19:11:006277 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516278 }
6279
mikecirone8b85c432016-09-08 19:11:006280 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6281 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516282 }
6283}
6284
[email protected]847c0fa92012-11-06 16:37:426285namespace {
6286
6287const char kExtraHeader[] = "Allow-Snafu";
6288const char kExtraValue[] = "fubar";
6289
6290class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206291 void OnReceivedRedirect(URLRequest* request,
6292 const RedirectInfo& redirect_info,
6293 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596294 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426295 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6296 }
6297};
6298
6299} // namespace
6300
6301TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556302 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426303
tommycli59a63432015-11-06 00:10:556304 GURL destination_url =
6305 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6306 GURL original_url =
6307 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426308 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166309 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6310 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196311 req->Start();
Wez2a31b222018-06-07 22:07:156312 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426313
6314 std::string value;
[email protected]f7022f32014-08-21 16:32:196315 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426316 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6317 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196318 EXPECT_FALSE(req->is_pending());
6319 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426320 EXPECT_EQ(kExtraValue, d.data_received());
6321}
6322
[email protected]251a1b92012-11-13 11:01:096323namespace {
6324
6325const char kExtraHeaderToRemove[] = "To-Be-Removed";
6326
6327class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206328 void OnReceivedRedirect(URLRequest* request,
6329 const RedirectInfo& redirect_info,
6330 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596331 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096332 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6333 }
6334};
6335
6336} // namespace
6337
6338TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556339 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096340
tommycli59a63432015-11-06 00:10:556341 GURL destination_url = http_test_server()->GetURL(
6342 "/echoheader?" + std::string(kExtraHeaderToRemove));
6343 GURL original_url =
6344 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096345 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166346 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6347 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196348 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6349 req->Start();
Wez2a31b222018-06-07 22:07:156350 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096351
6352 std::string value;
[email protected]f7022f32014-08-21 16:32:196353 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096354 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196355 EXPECT_FALSE(req->is_pending());
6356 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096357 EXPECT_EQ("None", d.data_received());
6358}
6359
mmenke94f1bd92016-12-07 21:13:056360TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446361 TestDelegate d;
6362 {
danakj8522a25b2016-04-16 00:17:366363 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166364 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6365 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446366
[email protected]f7022f32014-08-21 16:32:196367 r->Start();
6368 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446369
[email protected]f7022f32014-08-21 16:32:196370 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446371
Wez2a31b222018-06-07 22:07:156372 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446373
6374 // We expect to receive OnResponseStarted even though the request has been
6375 // cancelled.
6376 EXPECT_EQ(1, d.response_started_count());
6377 EXPECT_EQ(0, d.bytes_received());
6378 EXPECT_FALSE(d.received_data_before_response());
6379 }
6380}
6381
mmenke94f1bd92016-12-07 21:13:056382TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556383 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446384
6385 TestDelegate d;
6386 {
danakj8522a25b2016-04-16 00:17:366387 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166388 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6389 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446390
6391 d.set_cancel_in_response_started(true);
6392
[email protected]f7022f32014-08-21 16:32:196393 r->Start();
6394 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446395
Wez2a31b222018-06-07 22:07:156396 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446397
6398 EXPECT_EQ(1, d.response_started_count());
6399 EXPECT_EQ(0, d.bytes_received());
6400 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506401 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446402 }
6403}
6404
mmenke94f1bd92016-12-07 21:13:056405TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556406 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446407
6408 TestDelegate d;
6409 {
danakj8522a25b2016-04-16 00:17:366410 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166411 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6412 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056413
6414 d.set_cancel_in_received_data(true);
6415
6416 r->Start();
6417 EXPECT_TRUE(r->is_pending());
6418
Wez2a31b222018-06-07 22:07:156419 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056420
6421 EXPECT_EQ(1, d.response_started_count());
6422 EXPECT_NE(0, d.received_bytes_count());
6423 EXPECT_FALSE(d.received_data_before_response());
6424 EXPECT_EQ(ERR_ABORTED, d.request_status());
6425 }
6426}
6427
6428TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6429 ASSERT_TRUE(http_test_server()->Start());
6430
6431 TestDelegate d;
6432 {
6433 // This returns an empty response (With headers).
6434 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166435 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6436 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446437
6438 d.set_cancel_in_received_data(true);
6439
[email protected]f7022f32014-08-21 16:32:196440 r->Start();
6441 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446442
Wez2a31b222018-06-07 22:07:156443 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446444
6445 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056446 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446447 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506448 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446449 }
6450}
6451
mmenke94f1bd92016-12-07 21:13:056452TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556453 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446454
6455 TestDelegate d;
6456 {
danakj8522a25b2016-04-16 00:17:366457 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166458 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6459 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446460
[email protected]f7022f32014-08-21 16:32:196461 r->Start();
6462 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446463
6464 // The request will be implicitly canceled when it is destroyed. The
6465 // test delegate must not post a quit message when this happens because
6466 // this test doesn't actually have a message loop. The quit message would
6467 // get put on this thread's message queue and the next test would exit
6468 // early, causing problems.
6469 d.set_quit_on_complete(false);
6470 }
6471 // expect things to just cleanup properly.
6472
kimwjdalsl2bb4ff02015-12-16 22:06:026473 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446474 // message loop
6475 EXPECT_FALSE(d.received_data_before_response());
6476 EXPECT_EQ(0, d.bytes_received());
6477}
6478
mmenke94f1bd92016-12-07 21:13:056479TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556480 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446481
6482 // populate cache
6483 {
6484 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366485 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166486 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6487 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196488 r->Start();
Wez2a31b222018-06-07 22:07:156489 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506490 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446491 }
6492
6493 // cancel read from cache (see bug 990242)
6494 {
6495 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366496 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166497 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6498 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196499 r->Start();
6500 r->Cancel();
Wez2a31b222018-06-07 22:07:156501 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446502
maksim.sisovb53724b52016-09-16 05:30:506503 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446504 EXPECT_EQ(1, d.response_started_count());
6505 EXPECT_EQ(0, d.bytes_received());
6506 EXPECT_FALSE(d.received_data_before_response());
6507 }
6508}
6509
6510TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556511 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446512 HTTPUploadDataOperationTest("POST");
6513}
6514
6515TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556516 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446517 HTTPUploadDataOperationTest("PUT");
6518}
6519
6520TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556521 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446522
6523 TestDelegate d;
6524 {
danakj8522a25b2016-04-16 00:17:366525 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166526 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6527 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196528 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446529
[email protected]f7022f32014-08-21 16:32:196530 r->Start();
6531 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446532
Wez2a31b222018-06-07 22:07:156533 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446534
maksim.sisovb53724b52016-09-16 05:30:506535 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6536 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446537
6538 EXPECT_FALSE(d.received_data_before_response());
6539 EXPECT_TRUE(d.data_received().empty());
6540 }
6541}
6542
6543TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556544 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446545
6546 TestDelegate d;
6547 {
danakj8522a25b2016-04-16 00:17:366548 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166549 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6550 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196551 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446552
[email protected]6cdfd7f2013-02-08 20:40:156553 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196554 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026555 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446556
danakj8522a25b2016-04-16 00:17:366557 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446558
[email protected]6cdfd7f2013-02-08 20:40:156559 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196560 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476561 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446562 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196563 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146564 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076565 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046566 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6567 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446568
[email protected]f7022f32014-08-21 16:32:196569 r->Start();
6570 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446571
Wez2a31b222018-06-07 22:07:156572 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446573
avibf0746c2015-12-09 19:53:146574 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296575 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6576 ASSERT_LE(size64, std::numeric_limits<int>::max());
6577 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366578 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446579
[email protected]7600d0b2013-12-08 21:43:306580 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446581
maksim.sisovb53724b52016-09-16 05:30:506582 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6583 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446584
6585 EXPECT_FALSE(d.received_data_before_response());
6586
[email protected]329b68b2012-11-14 17:54:276587 EXPECT_EQ(size, d.bytes_received());
6588 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446589 }
6590}
6591
[email protected]999dd8c2013-11-12 06:45:546592TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556593 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546594
6595 TestDelegate d;
6596 {
danakj8522a25b2016-04-16 00:17:366597 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166598 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6599 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196600 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546601
danakj8522a25b2016-04-16 00:17:366602 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546603
Jeremy Roman0579ed62017-08-29 15:56:196604 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456605 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546606 base::FilePath(FILE_PATH_LITERAL(
6607 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076608 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046609 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6610 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546611
[email protected]f7022f32014-08-21 16:32:196612 r->Start();
6613 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546614
Wez2a31b222018-06-07 22:07:156615 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546616
[email protected]999dd8c2013-11-12 06:45:546617 EXPECT_TRUE(d.request_failed());
6618 EXPECT_FALSE(d.received_data_before_response());
6619 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506620 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546621 }
6622}
6623
mmenke56b0cbb912016-03-28 21:34:536624namespace {
6625
6626// Adds a standard set of data to an upload for chunked upload integration
6627// tests.
6628void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6629 writer->AppendData("a", 1, false);
6630 writer->AppendData("bcd", 3, false);
6631 writer->AppendData("this is a longer chunk than before.", 35, false);
6632 writer->AppendData("\r\n\r\n", 4, false);
6633 writer->AppendData("0", 1, false);
6634 writer->AppendData("2323", 4, true);
6635}
6636
6637// Checks that the upload data added in AddChunksToUpload() was echoed back from
6638// the server.
6639void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6640 // This should match the chunks sent by AddChunksToUpload().
6641 const std::string expected_data =
6642 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6643
maksim.sisovb53724b52016-09-16 05:30:506644 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6645 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536646
6647 EXPECT_FALSE(d->received_data_before_response());
6648
6649 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6650 EXPECT_EQ(expected_data, d->data_received());
6651}
6652
6653} // namespace
6654
[email protected]316c1e5e2012-09-12 15:17:446655TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556656 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446657
6658 TestDelegate d;
6659 {
danakj8522a25b2016-04-16 00:17:366660 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166661 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6662 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366663 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536664 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366665 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536666 upload_data_stream->CreateWriter();
6667 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196668 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536669 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196670 r->Start();
6671 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446672
Wez2a31b222018-06-07 22:07:156673 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446674
[email protected]f7022f32014-08-21 16:32:196675 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446676 }
6677}
6678
[email protected]329b68b2012-11-14 17:54:276679TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556680 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276681
6682 TestDelegate d;
6683 {
danakj8522a25b2016-04-16 00:17:366684 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166685 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6686 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366687 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536688 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366689 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536690 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046691 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196692 r->set_method("POST");
6693 r->Start();
6694 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536695 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156696 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276697
[email protected]f7022f32014-08-21 16:32:196698 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276699 }
6700}
6701
[email protected]316c1e5e2012-09-12 15:17:446702TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556703 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446704
6705 TestDelegate d;
6706 {
danakj8522a25b2016-04-16 00:17:366707 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166708 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6709 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366710 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536711 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366712 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536713 upload_data_stream->CreateWriter();
6714 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196715 r->set_method("POST");
6716 r->Start();
6717 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446718
[email protected]255620da2013-08-19 13:14:296719 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536720 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156721 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446722
[email protected]f7022f32014-08-21 16:32:196723 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446724 }
6725}
6726
6727TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556728 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446729
6730 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366731 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166732 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6733 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196734 req->Start();
Wez2a31b222018-06-07 22:07:156735 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446736
[email protected]f7022f32014-08-21 16:32:196737 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446738
6739 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196740 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446741
6742 std::string header;
6743 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6744 EXPECT_EQ("private", header);
6745
6746 header.clear();
6747 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6748 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6749
6750 // The response has two "X-Multiple-Entries" headers.
6751 // This verfies our output has them concatenated together.
6752 header.clear();
6753 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6754 EXPECT_EQ("a, b", header);
6755}
6756
tommycli59a63432015-11-06 00:10:556757// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6758// security state. (see http://crbug.com/550977).
6759#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466760TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556761 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6762 https_test_server.SetSSLConfig(
6763 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6764 https_test_server.ServeFilesFromSourceDirectory(
6765 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466766 ASSERT_TRUE(https_test_server.Start());
6767
tommycli59a63432015-11-06 00:10:556768 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466769 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366770 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166771 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6772 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196773 request->Start();
Wez2a31b222018-06-07 22:07:156774 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466775
6776 TransportSecurityState* security_state =
6777 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406778 TransportSecurityState::STSState sts_state;
6779 TransportSecurityState::PKPState pkp_state;
6780 EXPECT_TRUE(
6781 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6782 EXPECT_FALSE(
6783 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6784 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6785 sts_state.upgrade_mode);
6786 EXPECT_TRUE(sts_state.include_subdomains);
6787 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036788#if defined(OS_ANDROID)
6789 // Android's CertVerifyProc does not (yet) handle pins.
6790#else
martijnc0d6b622015-06-30 19:14:406791 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036792#endif
[email protected]37fd55fb2013-06-29 13:13:276793}
6794
estarka5da76702015-04-09 04:00:166795TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556796 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6797 https_test_server.ServeFilesFromSourceDirectory(
6798 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166799 ASSERT_TRUE(https_test_server.Start());
6800 // Make sure this test fails if the test server is changed to not
6801 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556802 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6803 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166804
6805 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366806 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166807 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6808 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166809 request->Start();
Wez2a31b222018-06-07 22:07:156810 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166811 TransportSecurityState* security_state =
6812 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406813 TransportSecurityState::STSState sts_state;
6814 EXPECT_FALSE(
6815 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166816}
6817
estark06e0dac2015-08-07 21:56:016818namespace {
Martijn Croonenb1383da2017-10-11 11:56:356819const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
6820const char kExpectStapleStaticHostname[] = "expect-staple.preloaded.test";
6821const char kExpectStapleReportURI[] =
6822 "http://report-uri.preloaded.test/expect-staple";
estark06e0dac2015-08-07 21:56:016823const char kHPKPReportUri[] = "https://hpkp-report.test";
6824} // namespace
6825
[email protected]37fd55fb2013-06-29 13:13:276826// Tests that enabling HPKP on a domain does not affect the HSTS
6827// validity/expiration.
dadrian2faf2062016-07-16 00:03:176828TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016829 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556830 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6831 https_test_server.SetSSLConfig(
6832 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6833 https_test_server.ServeFilesFromSourceDirectory(
6834 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276835 ASSERT_TRUE(https_test_server.Start());
6836
tommycli59a63432015-11-06 00:10:556837 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166838
[email protected]37fd55fb2013-06-29 13:13:276839 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366840 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166841 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6842 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196843 request->Start();
Wez2a31b222018-06-07 22:07:156844 d.RunUntilComplete();
[email protected]37fd55fb2013-06-29 13:13:276845 TransportSecurityState* security_state =
6846 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406847 TransportSecurityState::STSState sts_state;
6848 TransportSecurityState::PKPState pkp_state;
6849 EXPECT_FALSE(
6850 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6851 EXPECT_TRUE(
6852 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6853 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6854 sts_state.upgrade_mode);
6855 EXPECT_FALSE(sts_state.include_subdomains);
6856 EXPECT_FALSE(pkp_state.include_subdomains);
6857 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016858 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406859 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466860}
6861
estark06e0dac2015-08-07 21:56:016862// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176863TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016864 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556865 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6866 https_test_server.SetSSLConfig(
6867 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6868 https_test_server.ServeFilesFromSourceDirectory(
6869 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016870 ASSERT_TRUE(https_test_server.Start());
6871
tommycli59a63432015-11-06 00:10:556872 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016873
6874 // Set up a pin for |test_server_hostname|.
6875 TransportSecurityState security_state;
6876 const base::Time current_time(base::Time::Now());
6877 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6878 HashValueVector hashes;
6879 HashValue hash1;
6880 HashValue hash2;
6881 // The values here don't matter, as long as they are different from
6882 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446883 ASSERT_TRUE(
6884 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6885 ASSERT_TRUE(
6886 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016887 hashes.push_back(hash1);
6888 hashes.push_back(hash2);
6889 security_state.AddHPKP(test_server_hostname, expiry,
6890 false, /* include subdomains */
6891 hashes, report_uri);
6892
6893 MockCertificateReportSender mock_report_sender;
6894 security_state.SetReportSender(&mock_report_sender);
6895
6896 // Set up a MockCertVerifier to trigger a violation of the previously
6897 // set pin.
6898 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6899 ASSERT_TRUE(cert);
6900
6901 MockCertVerifier cert_verifier;
6902 CertVerifyResult verify_result;
6903 verify_result.verified_cert = cert;
6904 verify_result.is_issued_by_known_root = true;
6905 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446906 ASSERT_TRUE(
6907 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016908 verify_result.public_key_hashes.push_back(hash3);
6909 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6910
6911 TestNetworkDelegate network_delegate;
6912 TestURLRequestContext context(true);
6913 context.set_transport_security_state(&security_state);
6914 context.set_network_delegate(&network_delegate);
6915 context.set_cert_verifier(&cert_verifier);
6916 context.Init();
6917
6918 // Now send a request to trigger the violation.
6919 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366920 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166921 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6922 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016923 violating_request->Start();
Wez2a31b222018-06-07 22:07:156924 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016925
6926 // Check that a report was sent.
6927 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6928 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446929 EXPECT_EQ("application/json; charset=utf-8",
6930 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366931 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016932 base::JSONReader::Read(mock_report_sender.latest_report()));
6933 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086934 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016935 base::DictionaryValue* report_dict;
6936 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6937 std::string report_hostname;
6938 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6939 EXPECT_EQ(test_server_hostname, report_hostname);
6940}
6941
6942// Tests that reports get sent on requests with
6943// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176944TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016945 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556946 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6947 https_test_server.SetSSLConfig(
6948 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6949 https_test_server.ServeFilesFromSourceDirectory(
6950 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016951 ASSERT_TRUE(https_test_server.Start());
6952
tommycli59a63432015-11-06 00:10:556953 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016954
6955 TransportSecurityState security_state;
6956 MockCertificateReportSender mock_report_sender;
6957 security_state.SetReportSender(&mock_report_sender);
6958
6959 // Set up a MockCertVerifier to violate the pin in the Report-Only
6960 // header.
6961 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6962 ASSERT_TRUE(cert);
6963
6964 MockCertVerifier cert_verifier;
6965 CertVerifyResult verify_result;
6966 verify_result.verified_cert = cert;
6967 verify_result.is_issued_by_known_root = true;
6968 HashValue hash;
6969 // This value doesn't matter, as long as it is different from the pins
6970 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446971 ASSERT_TRUE(
6972 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016973 verify_result.public_key_hashes.push_back(hash);
6974 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6975
6976 TestNetworkDelegate network_delegate;
6977 TestURLRequestContext context(true);
6978 context.set_transport_security_state(&security_state);
6979 context.set_network_delegate(&network_delegate);
6980 context.set_cert_verifier(&cert_verifier);
6981 context.Init();
6982
6983 // Now send a request to trigger the violation.
6984 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366985 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556986 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166987 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016988 violating_request->Start();
Wez2a31b222018-06-07 22:07:156989 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016990
6991 // Check that a report was sent.
6992 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6993 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446994 EXPECT_EQ("application/json; charset=utf-8",
6995 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366996 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016997 base::JSONReader::Read(mock_report_sender.latest_report()));
6998 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086999 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:017000 base::DictionaryValue* report_dict;
7001 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
7002 std::string report_hostname;
7003 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
7004 EXPECT_EQ(test_server_hostname, report_hostname);
7005}
7006
7007// Tests that reports do not get sent on requests with
7008// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:177009TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:017010 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:557011 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7012 https_test_server.SetSSLConfig(
7013 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7014 https_test_server.ServeFilesFromSourceDirectory(
7015 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:017016 ASSERT_TRUE(https_test_server.Start());
7017
tommycli59a63432015-11-06 00:10:557018 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:017019
7020 TransportSecurityState security_state;
7021 MockCertificateReportSender mock_report_sender;
7022 security_state.SetReportSender(&mock_report_sender);
7023
7024 TestNetworkDelegate network_delegate;
7025 MockCertVerifier mock_cert_verifier;
7026 TestURLRequestContext context(true);
7027 context.set_transport_security_state(&security_state);
7028 context.set_network_delegate(&network_delegate);
7029 context.set_cert_verifier(&mock_cert_verifier);
7030 mock_cert_verifier.set_default_result(OK);
7031 context.Init();
7032
7033 // Now send a request that does not trigger the violation.
7034 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367035 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557036 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:167037 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:017038 request->Start();
Wez2a31b222018-06-07 22:07:157039 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:017040
7041 // Check that a report was not sent.
7042 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7043 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7044}
7045
estarka5da76702015-04-09 04:00:167046TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:557047 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7048 https_test_server.ServeFilesFromSourceDirectory(
7049 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:167050 ASSERT_TRUE(https_test_server.Start());
7051 // Make sure this test fails if the test server is changed to not
7052 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:557053 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
7054 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167055
7056 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367057 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167058 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7059 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:167060 request->Start();
Wez2a31b222018-06-07 22:07:157061 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:167062
7063 TransportSecurityState* security_state =
7064 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407065 TransportSecurityState::PKPState pkp_state;
7066 EXPECT_FALSE(
7067 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:167068}
7069
dadriandf302c42016-06-10 18:48:597070TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7071 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7072 https_test_server.SetSSLConfig(
7073 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7074 https_test_server.ServeFilesFromSourceDirectory(
7075 base::FilePath(kTestFilePath));
7076 ASSERT_TRUE(https_test_server.Start());
7077
7078 // Set up a MockCertVerifier to be a local root that violates the pin
7079 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7080 ASSERT_TRUE(cert);
7081
7082 MockCertVerifier cert_verifier;
7083 CertVerifyResult verify_result;
7084 verify_result.verified_cert = cert;
7085 verify_result.is_issued_by_known_root = false;
7086 HashValue hash;
7087 ASSERT_TRUE(
7088 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7089 verify_result.public_key_hashes.push_back(hash);
7090 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7091 cert_verifier.set_default_result(OK);
7092
7093 std::string test_server_hostname = https_test_server.GetURL("/").host();
7094
7095 // Set up HPKP
7096 base::Time current_time = base::Time::Now();
7097 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
7098 HashValue pin;
7099 ASSERT_TRUE(
7100 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
7101 HashValueVector hashes;
7102 hashes.push_back(pin);
7103 GURL report_uri(kHPKPReportUri);
7104 TransportSecurityState security_state;
7105 security_state.AddHPKP(test_server_hostname, expiry,
7106 false, /* include subdomains */
7107 hashes, report_uri);
7108
7109 TestNetworkDelegate network_delegate;
7110 TestURLRequestContext context(true);
7111 context.set_transport_security_state(&security_state);
7112 context.set_network_delegate(&network_delegate);
7113 context.set_cert_verifier(&cert_verifier);
7114 context.Init();
7115
7116 TestDelegate d;
7117 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167118 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7119 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597120 request->Start();
Wez2a31b222018-06-07 22:07:157121 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597122
7123 TransportSecurityState::PKPState pkp_state;
7124 EXPECT_TRUE(
7125 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
7126 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7127}
7128
[email protected]242d8562012-10-30 21:20:467129TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557130 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7131 https_test_server.SetSSLConfig(
7132 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7133 https_test_server.ServeFilesFromSourceDirectory(
7134 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467135 ASSERT_TRUE(https_test_server.Start());
7136
tommycli59a63432015-11-06 00:10:557137 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167138
[email protected]242d8562012-10-30 21:20:467139 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367140 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557141 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167142 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197143 request->Start();
Wez2a31b222018-06-07 22:07:157144 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467145
7146 // We should have set parameters from the first header, not the second.
7147 TransportSecurityState* security_state =
7148 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407149 TransportSecurityState::STSState sts_state;
7150 EXPECT_TRUE(
7151 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7152 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7153 sts_state.upgrade_mode);
7154 EXPECT_FALSE(sts_state.include_subdomains);
7155 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467156}
7157
[email protected]9f972ec2013-04-10 20:24:367158TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:557159 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7160 https_test_server.SetSSLConfig(
7161 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7162 https_test_server.ServeFilesFromSourceDirectory(
7163 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:367164 ASSERT_TRUE(https_test_server.Start());
7165
tommycli59a63432015-11-06 00:10:557166 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167167
[email protected]9f972ec2013-04-10 20:24:367168 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367169 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557170 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167171 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197172 request->Start();
Wez2a31b222018-06-07 22:07:157173 d.RunUntilComplete();
[email protected]9f972ec2013-04-10 20:24:367174
7175 // We should have set parameters from the first header, not the second.
7176 TransportSecurityState* security_state =
7177 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407178 TransportSecurityState::STSState sts_state;
7179 TransportSecurityState::PKPState pkp_state;
7180 EXPECT_TRUE(
7181 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7182 EXPECT_TRUE(
7183 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7184 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7185 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037186#if defined(OS_ANDROID)
7187 // Android's CertVerifyProc does not (yet) handle pins.
7188#else
martijnc0d6b622015-06-30 19:14:407189 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037190#endif
martijnc0d6b622015-06-30 19:14:407191 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:367192
[email protected]a165f092013-06-12 16:10:057193 // Even though there is an HSTS header asserting includeSubdomains, it is
7194 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:407195 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:057196 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:407197 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:367198}
7199
[email protected]37fd55fb2013-06-29 13:13:277200// Tests that when multiple HPKP headers are present, asserting different
7201// policies, that only the first such policy is processed.
7202TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:557203 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7204 https_test_server.SetSSLConfig(
7205 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7206 https_test_server.ServeFilesFromSourceDirectory(
7207 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:277208 ASSERT_TRUE(https_test_server.Start());
7209
tommycli59a63432015-11-06 00:10:557210 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167211
[email protected]37fd55fb2013-06-29 13:13:277212 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367213 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557214 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:167215 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197216 request->Start();
Wez2a31b222018-06-07 22:07:157217 d.RunUntilComplete();
[email protected]37fd55fb2013-06-29 13:13:277218
7219 TransportSecurityState* security_state =
7220 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407221 TransportSecurityState::STSState sts_state;
7222 TransportSecurityState::PKPState pkp_state;
7223 EXPECT_TRUE(
7224 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7225 EXPECT_TRUE(
7226 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7227 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7228 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037229#if defined(OS_ANDROID)
7230 // Android's CertVerifyProc does not (yet) handle pins.
7231#else
martijnc0d6b622015-06-30 19:14:407232 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037233#endif
martijnc0d6b622015-06-30 19:14:407234 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:277235
martijnc0d6b622015-06-30 19:14:407236 EXPECT_TRUE(sts_state.include_subdomains);
7237 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:277238}
7239
estark1614475f2016-03-10 03:46:477240// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7241// called.
7242class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7243 public:
7244 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277245 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477246
7247 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7248 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017249 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257250 const X509Certificate* validated_certificate_chain,
7251 const X509Certificate* served_certificate_chain,
7252 const SignedCertificateTimestampAndStatusList&
7253 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477254 num_failures_++;
7255 }
7256
7257 uint32_t num_failures() { return num_failures_; }
7258
7259 private:
7260 uint32_t num_failures_;
7261};
7262
Emily Stark627238f2017-11-29 03:29:547263// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477264// for every certificate.
7265class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7266 public:
7267 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547268 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277269 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477270
Emily Stark627238f2017-11-29 03:29:547271 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477272 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237273 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207274 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477275 return default_result_;
7276 }
7277
Emily Stark627238f2017-11-29 03:29:547278 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477279 default_result_ = default_result;
7280 }
7281
7282 private:
Emily Stark627238f2017-11-29 03:29:547283 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477284};
7285
Emily Stark4cfecf072017-08-08 01:05:517286// Tests that Expect CT headers for the preload list are processed correctly.
7287TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357288 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7289
estark1614475f2016-03-10 03:46:477290 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7291 https_test_server.SetSSLConfig(
7292 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7293 https_test_server.ServeFilesFromSourceDirectory(
7294 base::FilePath(kTestFilePath));
7295 ASSERT_TRUE(https_test_server.Start());
7296
7297 MockExpectCTReporter reporter;
7298 TransportSecurityState transport_security_state;
7299 transport_security_state.enable_static_expect_ct_ = true;
7300 transport_security_state.SetExpectCTReporter(&reporter);
7301
7302 // Set up a MockCertVerifier to accept the certificate that the server sends.
7303 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7304 ASSERT_TRUE(cert);
7305 MockCertVerifier cert_verifier;
7306 CertVerifyResult verify_result;
7307 verify_result.verified_cert = cert;
7308 verify_result.is_issued_by_known_root = true;
7309 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7310
rsleevi22cae1672016-12-28 01:53:367311 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7312 // CT violation.
7313 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477314 MockCTPolicyEnforcer ct_policy_enforcer;
7315 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547316 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477317
7318 TestNetworkDelegate network_delegate;
7319 // Use a MockHostResolver (which by default maps all hosts to
7320 // 127.0.0.1) so that the request can be sent to a site on the Expect
7321 // CT preload list.
7322 MockHostResolver host_resolver;
7323 TestURLRequestContext context(true);
7324 context.set_host_resolver(&host_resolver);
7325 context.set_transport_security_state(&transport_security_state);
7326 context.set_network_delegate(&network_delegate);
7327 context.set_cert_verifier(&cert_verifier);
7328 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467329 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477330 context.Init();
7331
7332 // Now send a request to trigger the violation.
7333 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517334 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477335 GURL::Replacements replace_host;
7336 replace_host.SetHostStr(kExpectCTStaticHostname);
7337 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167338 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7339 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477340 violating_request->Start();
Wez2a31b222018-06-07 22:07:157341 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477342
7343 EXPECT_EQ(1u, reporter.num_failures());
7344}
Emily Stark4cfecf072017-08-08 01:05:517345
7346// Tests that Expect CT HTTP headers are processed correctly.
7347TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7348 base::test::ScopedFeatureList feature_list;
7349 feature_list.InitAndEnableFeature(
7350 TransportSecurityState::kDynamicExpectCTFeature);
7351
7352 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7353 https_test_server.SetSSLConfig(
7354 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7355 https_test_server.ServeFilesFromSourceDirectory(
7356 base::FilePath(kTestFilePath));
7357 ASSERT_TRUE(https_test_server.Start());
7358
7359 MockExpectCTReporter reporter;
7360 TransportSecurityState transport_security_state;
7361 transport_security_state.SetExpectCTReporter(&reporter);
7362
7363 // Set up a MockCertVerifier to accept the certificate that the server sends.
7364 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7365 ASSERT_TRUE(cert);
7366 MockCertVerifier cert_verifier;
7367 CertVerifyResult verify_result;
7368 verify_result.verified_cert = cert;
7369 verify_result.is_issued_by_known_root = true;
7370 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7371
7372 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7373 // compliance.
7374 DoNothingCTVerifier ct_verifier;
7375 MockCTPolicyEnforcer ct_policy_enforcer;
7376 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547377 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517378
7379 TestNetworkDelegate network_delegate;
7380 // Use a MockHostResolver (which by default maps all hosts to
7381 // 127.0.0.1).
7382 MockHostResolver host_resolver;
7383 TestURLRequestContext context(true);
7384 context.set_host_resolver(&host_resolver);
7385 context.set_transport_security_state(&transport_security_state);
7386 context.set_network_delegate(&network_delegate);
7387 context.set_cert_verifier(&cert_verifier);
7388 context.set_cert_transparency_verifier(&ct_verifier);
7389 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7390 context.Init();
7391
7392 // Now send a request to trigger the header processing.
7393 TestDelegate d;
7394 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7395 std::unique_ptr<URLRequest> request(context.CreateRequest(
7396 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7397 request->Start();
Wez2a31b222018-06-07 22:07:157398 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517399
7400 TransportSecurityState::ExpectCTState state;
7401 ASSERT_TRUE(
7402 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7403 EXPECT_TRUE(state.enforce);
7404 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7405}
7406
7407// Tests that if multiple Expect CT HTTP headers are sent, they are all
7408// processed.
7409TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7410 base::test::ScopedFeatureList feature_list;
7411 feature_list.InitAndEnableFeature(
7412 TransportSecurityState::kDynamicExpectCTFeature);
7413
7414 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7415 https_test_server.SetSSLConfig(
7416 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7417 https_test_server.ServeFilesFromSourceDirectory(
7418 base::FilePath(kTestFilePath));
7419 ASSERT_TRUE(https_test_server.Start());
7420
7421 MockExpectCTReporter reporter;
7422 TransportSecurityState transport_security_state;
7423 transport_security_state.SetExpectCTReporter(&reporter);
7424
7425 // Set up a MockCertVerifier to accept the certificate that the server sends.
7426 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7427 ASSERT_TRUE(cert);
7428 MockCertVerifier cert_verifier;
7429 CertVerifyResult verify_result;
7430 verify_result.verified_cert = cert;
7431 verify_result.is_issued_by_known_root = true;
7432 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7433
7434 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7435 // compliance.
7436 DoNothingCTVerifier ct_verifier;
7437 MockCTPolicyEnforcer ct_policy_enforcer;
7438 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547439 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517440
7441 TestNetworkDelegate network_delegate;
7442 // Use a MockHostResolver (which by default maps all hosts to
7443 // 127.0.0.1).
7444 MockHostResolver host_resolver;
7445 TestURLRequestContext context(true);
7446 context.set_host_resolver(&host_resolver);
7447 context.set_transport_security_state(&transport_security_state);
7448 context.set_network_delegate(&network_delegate);
7449 context.set_cert_verifier(&cert_verifier);
7450 context.set_cert_transparency_verifier(&ct_verifier);
7451 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7452 context.Init();
7453
7454 // Now send a request to trigger the header processing.
7455 TestDelegate d;
7456 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7457 std::unique_ptr<URLRequest> request(context.CreateRequest(
7458 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7459 request->Start();
Wez2a31b222018-06-07 22:07:157460 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517461
7462 TransportSecurityState::ExpectCTState state;
7463 ASSERT_TRUE(
7464 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7465 EXPECT_TRUE(state.enforce);
7466 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7467}
7468
mmenkefd9d15c2017-06-29 13:45:547469#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477470
mmenkefd9d15c2017-06-29 13:45:547471#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:417472namespace {
7473
7474class TestReportingService : public ReportingService {
7475 public:
7476 struct Header {
7477 GURL url;
7478 std::string header_value;
7479 };
7480
juliatuttle2b8dd2d12017-04-12 21:27:417481 const std::vector<Header>& headers() { return headers_; }
7482
juliatuttle1d92f0152017-04-28 17:19:217483 // ReportingService implementation:
7484
Chris Watkins7a41d3552017-12-01 02:13:277485 ~TestReportingService() override = default;
juliatuttle1d92f0152017-04-28 17:19:217486
juliatuttle2b8dd2d12017-04-12 21:27:417487 void QueueReport(const GURL& url,
7488 const std::string& group,
7489 const std::string& type,
Julia Tuttle107e30672018-03-29 18:48:427490 std::unique_ptr<const base::Value> body,
7491 int depth) override {
juliatuttle2b8dd2d12017-04-12 21:27:417492 NOTIMPLEMENTED();
7493 }
7494
7495 void ProcessHeader(const GURL& url,
7496 const std::string& header_value) override {
7497 headers_.push_back({url, header_value});
7498 }
7499
Julia Tuttle227a6ff2017-12-19 19:44:247500 void RemoveBrowsingData(int data_type_mask,
7501 const base::RepeatingCallback<bool(const GURL&)>&
7502 origin_filter) override {
juliatuttleaeb1abc2017-05-04 21:14:387503 NOTIMPLEMENTED();
7504 }
7505
Eric Orthb812a442018-05-04 20:26:487506 void RemoveAllBrowsingData(int data_type_mask) override { NOTIMPLEMENTED(); }
7507
Julia Tuttle107e30672018-03-29 18:48:427508 int GetUploadDepth(const URLRequest& request) override {
Julia Tuttle4667c1c2017-12-19 18:27:387509 NOTIMPLEMENTED();
Julia Tuttle107e30672018-03-29 18:48:427510 return 0;
Julia Tuttle4667c1c2017-12-19 18:27:387511 }
7512
Julia Tuttle91a655d2018-01-26 18:03:037513 const ReportingPolicy& GetPolicy() const override {
7514 static ReportingPolicy dummy_policy_;
7515 NOTIMPLEMENTED();
7516 return dummy_policy_;
7517 }
7518
juliatuttle2b8dd2d12017-04-12 21:27:417519 private:
7520 std::vector<Header> headers_;
7521};
7522
7523std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7524 const test_server::HttpRequest& request) {
7525 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7526 new test_server::BasicHttpResponse);
7527 http_response->set_code(HTTP_OK);
7528 http_response->AddCustomHeader("Report-To", "foo");
7529 http_response->AddCustomHeader("Report-To", "bar");
7530 return std::move(http_response);
7531}
7532
7533} // namespace
7534
7535TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
Julia Tuttle7005a2a2017-12-08 21:01:187536 http_test_server()->RegisterRequestHandler(
7537 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417538 ASSERT_TRUE(http_test_server()->Start());
7539 GURL request_url = http_test_server()->GetURL("/");
7540
7541 TestNetworkDelegate network_delegate;
7542 TestURLRequestContext context(true);
7543 context.set_network_delegate(&network_delegate);
7544 context.Init();
7545
7546 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167547 std::unique_ptr<URLRequest> request(context.CreateRequest(
7548 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417549 request->Start();
Wez2a31b222018-06-07 22:07:157550 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417551}
7552
7553TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
Julia Tuttle7005a2a2017-12-08 21:01:187554 http_test_server()->RegisterRequestHandler(
7555 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417556 ASSERT_TRUE(http_test_server()->Start());
7557 GURL request_url = http_test_server()->GetURL("/");
7558
7559 TestNetworkDelegate network_delegate;
7560 TestReportingService reporting_service;
7561 TestURLRequestContext context(true);
7562 context.set_network_delegate(&network_delegate);
7563 context.set_reporting_service(&reporting_service);
7564 context.Init();
7565
7566 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167567 std::unique_ptr<URLRequest> request(context.CreateRequest(
7568 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417569 request->Start();
Wez2a31b222018-06-07 22:07:157570 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417571
7572 EXPECT_TRUE(reporting_service.headers().empty());
7573}
7574
7575TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7576 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187577 https_test_server.RegisterRequestHandler(
7578 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417579 ASSERT_TRUE(https_test_server.Start());
7580 GURL request_url = https_test_server.GetURL("/");
7581
7582 TestNetworkDelegate network_delegate;
7583 TestReportingService reporting_service;
7584 TestURLRequestContext context(true);
7585 context.set_network_delegate(&network_delegate);
7586 context.set_reporting_service(&reporting_service);
7587 context.Init();
7588
7589 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167590 std::unique_ptr<URLRequest> request(context.CreateRequest(
7591 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417592 request->Start();
Wez2a31b222018-06-07 22:07:157593 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417594
7595 ASSERT_EQ(1u, reporting_service.headers().size());
7596 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7597 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7598}
7599
Julia Tuttlef9b74062017-07-27 14:44:057600TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417601 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7602 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187603 https_test_server.RegisterRequestHandler(
7604 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417605 ASSERT_TRUE(https_test_server.Start());
7606 GURL request_url = https_test_server.GetURL("/");
7607
7608 TestNetworkDelegate network_delegate;
7609 TestReportingService reporting_service;
7610 TestURLRequestContext context(true);
7611 context.set_network_delegate(&network_delegate);
7612 context.set_reporting_service(&reporting_service);
7613 context.Init();
7614
7615 TestDelegate d;
7616 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167617 std::unique_ptr<URLRequest> request(context.CreateRequest(
7618 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417619 request->Start();
Wez2a31b222018-06-07 22:07:157620 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417621
7622 EXPECT_TRUE(d.have_certificate_errors());
7623 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7624 EXPECT_TRUE(reporting_service.headers().empty());
7625}
Julia Tuttlefadc26d2017-10-13 18:12:297626
7627// Network Error Logging is dependent on the Reporting API, so only run NEL
7628// tests if Reporting is enabled in the build.
tommycli59a63432015-11-06 00:10:557629
Julia Tuttlef9b74062017-07-27 14:44:057630namespace {
7631
Julia Tuttlecba7d222018-02-23 19:37:277632class TestNetworkErrorLoggingService : public NetworkErrorLoggingService {
Julia Tuttlef9b74062017-07-27 14:44:057633 public:
7634 struct Header {
Chris Watkins7a41d3552017-12-01 02:13:277635 Header() = default;
7636 ~Header() = default;
Julia Tuttlef9b74062017-07-27 14:44:057637
7638 url::Origin origin;
7639 std::string value;
7640 };
7641
Julia Tuttlef9b74062017-07-27 14:44:057642 const std::vector<Header>& headers() { return headers_; }
Douglas Creager1f56bbe2018-02-17 03:58:407643 const std::vector<RequestDetails>& errors() { return errors_; }
Julia Tuttlef9b74062017-07-27 14:44:057644
Julia Tuttlecba7d222018-02-23 19:37:277645 // NetworkErrorLoggingService implementation:
Julia Tuttlef9b74062017-07-27 14:44:057646
Julia Tuttlecba7d222018-02-23 19:37:277647 ~TestNetworkErrorLoggingService() override = default;
Julia Tuttlef9b74062017-07-27 14:44:057648
7649 void OnHeader(const url::Origin& origin, const std::string& value) override {
7650 Header header;
7651 header.origin = origin;
7652 header.value = value;
7653 headers_.push_back(header);
7654 }
7655
Douglas Creager1f56bbe2018-02-17 03:58:407656 void OnRequest(const RequestDetails& details) override {
Julia Tuttleb0d45472017-09-25 20:14:437657 errors_.push_back(details);
Julia Tuttlef9b74062017-07-27 14:44:057658 }
7659
Julia Tuttlea059db82018-01-04 18:46:437660 void RemoveBrowsingData(const base::RepeatingCallback<bool(const GURL&)>&
7661 origin_filter) override {
7662 NOTREACHED();
7663 }
7664
Eric Orth26a408f2018-05-09 15:43:407665 void RemoveAllBrowsingData() override { NOTREACHED(); }
7666
Julia Tuttlef9b74062017-07-27 14:44:057667 private:
7668 std::vector<Header> headers_;
Douglas Creager1f56bbe2018-02-17 03:58:407669 std::vector<RequestDetails> errors_;
Julia Tuttlef9b74062017-07-27 14:44:057670};
7671
7672std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7673 const test_server::HttpRequest& request) {
7674 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7675 new test_server::BasicHttpResponse);
7676 http_response->set_code(HTTP_OK);
Julia Tuttlecba7d222018-02-23 19:37:277677 http_response->AddCustomHeader(NetworkErrorLoggingService::kHeaderName,
Julia Tuttlef9b74062017-07-27 14:44:057678 "foo");
7679 return std::move(http_response);
7680}
7681
Julia Tuttle7005a2a2017-12-08 21:01:187682std::unique_ptr<test_server::HttpResponse> SendEmptyResponse(
7683 const test_server::HttpRequest& request) {
Gyuyoung Kimb480aba2018-01-27 07:00:047684 return std::make_unique<test_server::RawHttpResponse>("", "");
Julia Tuttle7005a2a2017-12-08 21:01:187685}
7686
Julia Tuttlef9b74062017-07-27 14:44:057687} // namespace
7688
7689TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
Julia Tuttle7005a2a2017-12-08 21:01:187690 http_test_server()->RegisterRequestHandler(
7691 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057692 ASSERT_TRUE(http_test_server()->Start());
7693 GURL request_url = http_test_server()->GetURL("/");
7694
7695 TestNetworkDelegate network_delegate;
7696 TestURLRequestContext context(true);
7697 context.set_network_delegate(&network_delegate);
7698 context.Init();
7699
7700 TestDelegate d;
7701 std::unique_ptr<URLRequest> request(context.CreateRequest(
7702 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7703 request->Start();
Wez2a31b222018-06-07 22:07:157704 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057705}
7706
7707TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
Julia Tuttle7005a2a2017-12-08 21:01:187708 http_test_server()->RegisterRequestHandler(
7709 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057710 ASSERT_TRUE(http_test_server()->Start());
7711 GURL request_url = http_test_server()->GetURL("/");
7712
7713 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277714 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057715 TestURLRequestContext context(true);
7716 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277717 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057718 context.Init();
7719
7720 TestDelegate d;
7721 std::unique_ptr<URLRequest> request(context.CreateRequest(
7722 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7723 request->Start();
Wez2a31b222018-06-07 22:07:157724 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057725
Julia Tuttlecba7d222018-02-23 19:37:277726 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057727}
7728
7729TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7730 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187731 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057732 ASSERT_TRUE(https_test_server.Start());
7733 GURL request_url = https_test_server.GetURL("/");
7734
7735 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277736 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057737 TestURLRequestContext context(true);
7738 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277739 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057740 context.Init();
7741
7742 TestDelegate d;
7743 std::unique_ptr<URLRequest> request(context.CreateRequest(
7744 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7745 request->Start();
Wez2a31b222018-06-07 22:07:157746 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057747
Julia Tuttlecba7d222018-02-23 19:37:277748 ASSERT_EQ(1u, nel_service.headers().size());
7749 EXPECT_EQ(url::Origin::Create(request_url), nel_service.headers()[0].origin);
7750 EXPECT_EQ("foo", nel_service.headers()[0].value);
Julia Tuttlef9b74062017-07-27 14:44:057751}
7752
7753TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7754 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7755 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187756 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057757 ASSERT_TRUE(https_test_server.Start());
7758 GURL request_url = https_test_server.GetURL("/");
7759
7760 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277761 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057762 TestURLRequestContext context(true);
7763 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277764 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057765 context.Init();
7766
7767 TestDelegate d;
7768 d.set_allow_certificate_errors(true);
7769 std::unique_ptr<URLRequest> request(context.CreateRequest(
7770 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7771 request->Start();
Wez2a31b222018-06-07 22:07:157772 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057773
7774 EXPECT_TRUE(d.have_certificate_errors());
7775 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
Julia Tuttlecba7d222018-02-23 19:37:277776 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057777}
7778
Julia Tuttlefadc26d2017-10-13 18:12:297779TEST_F(URLRequestTestHTTP, DontForwardErrorToNelNoDelegate) {
7780 URLRequestFailedJob::AddUrlHandler();
7781
7782 GURL request_url =
7783 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7784
7785 TestNetworkDelegate network_delegate;
7786 TestURLRequestContext context(true);
7787 context.set_network_delegate(&network_delegate);
7788 context.Init();
7789
7790 TestDelegate d;
7791 std::unique_ptr<URLRequest> request(context.CreateRequest(
7792 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7793 request->Start();
Wez2a31b222018-06-07 22:07:157794 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297795
7796 URLRequestFilter::GetInstance()->ClearHandlers();
7797}
7798
7799// TODO(juliatuttle): Figure out whether this restriction should be in place,
7800// and either implement it or remove this test.
7801TEST_F(URLRequestTestHTTP, DISABLED_DontForwardErrorToNelHttp) {
7802 URLRequestFailedJob::AddUrlHandler();
7803
7804 GURL request_url =
7805 URLRequestFailedJob::GetMockHttpUrl(ERR_CONNECTION_REFUSED);
7806
7807 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277808 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297809 TestURLRequestContext context(true);
7810 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277811 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297812 context.Init();
7813
7814 TestDelegate d;
7815 std::unique_ptr<URLRequest> request(context.CreateRequest(
7816 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7817 request->Start();
Wez2a31b222018-06-07 22:07:157818 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297819
Julia Tuttlecba7d222018-02-23 19:37:277820 EXPECT_TRUE(nel_service.errors().empty());
Julia Tuttlefadc26d2017-10-13 18:12:297821
7822 URLRequestFilter::GetInstance()->ClearHandlers();
7823}
7824
Julia Tuttle7005a2a2017-12-08 21:01:187825TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Mock) {
Julia Tuttlefadc26d2017-10-13 18:12:297826 URLRequestFailedJob::AddUrlHandler();
7827
7828 GURL request_url =
7829 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7830
7831 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277832 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297833 TestURLRequestContext context(true);
7834 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277835 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297836 context.Init();
7837
7838 TestDelegate d;
7839 std::unique_ptr<URLRequest> request(context.CreateRequest(
7840 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7841 request->Start();
Wez2a31b222018-06-07 22:07:157842 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297843
Julia Tuttlecba7d222018-02-23 19:37:277844 ASSERT_EQ(1u, nel_service.errors().size());
7845 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7846 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7847 EXPECT_EQ(ERR_CONNECTION_REFUSED, nel_service.errors()[0].type);
Julia Tuttlefadc26d2017-10-13 18:12:297848
7849 URLRequestFilter::GetInstance()->ClearHandlers();
7850}
7851
Julia Tuttle7005a2a2017-12-08 21:01:187852// Also test with a real server, to exercise interactions with
7853// URLRequestHttpJob.
7854TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Real) {
7855 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7856 https_test_server.RegisterRequestHandler(
7857 base::BindRepeating(&SendEmptyResponse));
7858 ASSERT_TRUE(https_test_server.Start());
7859 GURL request_url = https_test_server.GetURL("/");
7860
7861 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277862 TestNetworkErrorLoggingService nel_service;
Julia Tuttle7005a2a2017-12-08 21:01:187863 TestURLRequestContext context(true);
7864 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277865 context.set_network_error_logging_service(&nel_service);
Julia Tuttle7005a2a2017-12-08 21:01:187866 context.Init();
7867
7868 TestDelegate d;
7869 std::unique_ptr<URLRequest> request(context.CreateRequest(
7870 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7871 request->Start();
Wez2a31b222018-06-07 22:07:157872 d.RunUntilComplete();
Julia Tuttle7005a2a2017-12-08 21:01:187873
Julia Tuttlecba7d222018-02-23 19:37:277874 ASSERT_EQ(1u, nel_service.errors().size());
7875 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7876 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7877 EXPECT_EQ(ERR_EMPTY_RESPONSE, nel_service.errors()[0].type);
Julia Tuttle7005a2a2017-12-08 21:01:187878}
7879
Julia Tuttlefadc26d2017-10-13 18:12:297880#endif // BUILDFLAG(ENABLE_REPORTING)
7881
[email protected]316c1e5e2012-09-12 15:17:447882TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557883 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447884
7885 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367886 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557887 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167888 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197889 req->Start();
Wez2a31b222018-06-07 22:07:157890 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447891
7892 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197893 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447894 EXPECT_EQ("text/html", mime_type);
7895
7896 std::string charset;
[email protected]f7022f32014-08-21 16:32:197897 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447898 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197899 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447900}
7901
[email protected]02494ec2014-05-07 15:05:297902TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347903 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347904 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347905 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027906 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347907
7908 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507909 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347910}
7911
brettwa1228ebb2016-10-28 03:51:347912#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297913TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7914 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7915 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457916 FileProtocolHandler file_protocol_handler(
7917 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297918 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7919
7920 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507921 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297922}
7923
[email protected]588614c22013-08-16 00:09:027924TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557925 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447926
7927 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367928 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557929 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167930 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197931 req->Start();
Wez2a31b222018-06-07 22:07:157932 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447933
maksim.sisovb53724b52016-09-16 05:30:507934 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307935
7936 // The redirect should have been rejected before reporting it to the caller.
7937 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447938}
brettwa1228ebb2016-10-28 03:51:347939#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447940
[email protected]588614c22013-08-16 00:09:027941TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557942 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027943
7944 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367945 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557946 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167947 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197948 req->Start();
Wez2a31b222018-06-07 22:07:157949 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027950
maksim.sisovb53724b52016-09-16 05:30:507951 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307952
7953 // The redirect should have been rejected before reporting it to the
7954 // caller. See https://crbug.com/723796
7955 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027956}
7957
davidbend894710b2017-06-06 19:28:307958// Test that redirects to invalid URLs are rejected. See
7959// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447960TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557961 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447962
7963 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367964 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557965 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167966 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197967 req->Start();
Wez2a31b222018-06-07 22:07:157968 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447969
davidbend894710b2017-06-06 19:28:307970 EXPECT_EQ(1, d.response_started_count());
7971 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7972
7973 // The redirect should have been rejected before reporting it to the caller.
7974 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447975}
7976
[email protected]e50efea2014-03-24 18:41:007977// Make sure redirects are cached, despite not reading their bodies.
7978TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557979 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007980 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557981 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007982
7983 {
7984 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167985 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7986 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197987 req->Start();
Wez2a31b222018-06-07 22:07:157988 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507989 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007990 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557991 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007992 }
7993
7994 {
7995 TestDelegate d;
7996 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167997 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7998 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197999 req->Start();
Wez2a31b222018-06-07 22:07:158000 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:008001
8002 EXPECT_EQ(1, d.received_redirect_count());
8003 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198004 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:008005
Chong Zhang7607f1f2018-06-01 20:52:208006 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:158007 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:008008 EXPECT_EQ(1, d.received_redirect_count());
8009 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508010 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:558011 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:008012 }
8013}
8014
8015// Make sure a request isn't cached when a NetworkDelegate forces a redirect
8016// when the headers are read, since the body won't have been read.
8017TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:558018 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:008019 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:558020 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:008021
8022 {
8023 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:558024 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:008025 default_network_delegate_.set_redirect_on_headers_received_url(
8026 redirect_to_url);
8027
8028 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168029 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8030 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198031 req->Start();
Wez2a31b222018-06-07 22:07:158032 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508033 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:008034 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198035 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:008036 }
8037
8038 {
8039 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168040 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8041 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198042 req->Start();
Wez2a31b222018-06-07 22:07:158043 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:008044
maksim.sisovb53724b52016-09-16 05:30:508045 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198046 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:008047 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198048 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:008049 }
8050}
8051
[email protected]5f714132014-03-26 10:41:168052// Tests that redirection to an unsafe URL is allowed when it has been marked as
8053// safe.
8054TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:558055 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168056
8057 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
8058 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8059 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8060
8061 TestDelegate d;
8062 {
danakj8522a25b2016-04-16 00:17:368063 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168064 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8065 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168066
[email protected]f7022f32014-08-21 16:32:198067 r->Start();
Wez2a31b222018-06-07 22:07:158068 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168069
maksim.sisovb53724b52016-09-16 05:30:508070 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198071 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:198072 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:168073 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
8074 }
8075}
8076
8077// Tests that a redirect to a different unsafe URL is blocked, even after adding
8078// some other URL to the whitelist.
8079TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:558080 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168081
8082 GURL unsafe_url("data:text/html,something");
8083 GURL different_unsafe_url("data:text/html,something-else");
8084 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8085 default_network_delegate_.set_allowed_unsafe_redirect_url(
8086 different_unsafe_url);
8087
8088 TestDelegate d;
8089 {
danakj8522a25b2016-04-16 00:17:368090 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168091 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8092 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168093
[email protected]f7022f32014-08-21 16:32:198094 r->Start();
Wez2a31b222018-06-07 22:07:158095 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168096
maksim.sisovb53724b52016-09-16 05:30:508097 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:308098
8099 // The redirect should have been rejected before reporting it to the caller.
8100 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:168101 }
8102}
8103
[email protected]5f714132014-03-26 10:41:168104// Redirects from an URL with fragment to an unsafe URL with fragment should
8105// be allowed, and the reference fragment of the target URL should be preserved.
8106TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:558107 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168108
tommycli59a63432015-11-06 00:10:558109 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:168110 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8111 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8112
8113 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8114 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8115
8116 TestDelegate d;
8117 {
rhalavatib7bd7c792017-04-27 05:25:168118 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8119 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168120
[email protected]f7022f32014-08-21 16:32:198121 r->Start();
Wez2a31b222018-06-07 22:07:158122 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168123
[email protected]f7022f32014-08-21 16:32:198124 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508125 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198126 EXPECT_EQ(original_url, r->original_url());
8127 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:168128 }
8129}
8130
8131// When a delegate has specified a safe redirect URL, but it does not match the
8132// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:148133TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:558134 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168135
tommycli59a63432015-11-06 00:10:558136 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168137 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:558138 GURL redirect_url(http_test_server()->GetURL("/target"));
8139 GURL expected_redirect_url(
8140 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168141
8142 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8143 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8144
8145 TestDelegate d;
8146 {
rhalavatib7bd7c792017-04-27 05:25:168147 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8148 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168149
[email protected]f7022f32014-08-21 16:32:198150 r->Start();
Wez2a31b222018-06-07 22:07:158151 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168152
[email protected]f7022f32014-08-21 16:32:198153 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508154 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198155 EXPECT_EQ(original_url, r->original_url());
8156 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:168157 }
8158}
8159
[email protected]f878230e2014-04-03 15:36:148160// When a delegate has specified a safe redirect URL, assume that the redirect
8161// URL should not be changed. In particular, the reference fragment should not
8162// be modified.
8163TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558164 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148165
tommycli59a63432015-11-06 00:10:558166 GURL original_url(
8167 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:148168 GURL redirect_url("data:text/html,expect-no-reference-fragment");
8169
8170 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8171 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
8172
8173 TestDelegate d;
8174 {
rhalavatib7bd7c792017-04-27 05:25:168175 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8176 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148177
[email protected]f7022f32014-08-21 16:32:198178 r->Start();
Wez2a31b222018-06-07 22:07:158179 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148180
[email protected]f7022f32014-08-21 16:32:198181 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508182 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198183 EXPECT_EQ(original_url, r->original_url());
8184 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148185 }
8186}
8187
8188// When a URLRequestRedirectJob is created, the redirection must be followed and
8189// the reference fragment of the target URL must not be modified.
8190TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558191 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148192
tommycli59a63432015-11-06 00:10:558193 GURL original_url(
8194 http_test_server()->GetURL("/original#should-not-be-appended"));
8195 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:148196
8197 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168198 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8199 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148200
danakj8522a25b2016-04-16 00:17:368201 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:198202 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:428203 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8204 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:148205
[email protected]f7022f32014-08-21 16:32:198206 r->Start();
Wez2a31b222018-06-07 22:07:158207 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148208
maksim.sisovb53724b52016-09-16 05:30:508209 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198210 EXPECT_EQ(original_url, r->original_url());
8211 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148212}
8213
lizeb5120f6dc2016-02-19 09:29:448214TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
8215 ASSERT_TRUE(http_test_server()->Start());
8216
8217 const std::string referrer("foobar://totally.legit.referrer");
8218 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368219 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168220 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8221 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:448222 req->SetReferrer(referrer);
8223 req->Start();
Wez2a31b222018-06-07 22:07:158224 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:448225
8226 EXPECT_EQ(std::string("None"), d.data_received());
8227}
8228
[email protected]316c1e5e2012-09-12 15:17:448229TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558230 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448231
8232 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368233 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168234 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8235 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198236 req->SetReferrer("http://user:[email protected]/");
8237 req->Start();
Wez2a31b222018-06-07 22:07:158238 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448239
8240 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8241}
8242
[email protected]99ecf6e2013-04-10 22:46:138243TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558244 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138245
8246 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368247 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168248 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8249 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198250 req->SetReferrer("http://foo.com/test#fragment");
8251 req->Start();
Wez2a31b222018-06-07 22:07:158252 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138253
8254 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8255}
8256
8257TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558258 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138259
8260 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368261 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168262 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8263 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198264 req->SetReferrer("http://foo.com/test#fragment");
8265 req->SetReferrer("");
8266 req->Start();
Wez2a31b222018-06-07 22:07:158267 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138268
8269 EXPECT_EQ(std::string("None"), d.data_received());
8270}
8271
[email protected]316c1e5e2012-09-12 15:17:448272TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558273 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448274
8275 TestDelegate d;
8276 {
8277 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:368278 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168279 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8280 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198281 req->Start();
Wez2a31b222018-06-07 22:07:158282 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448283
8284 EXPECT_EQ(1, d.response_started_count());
8285 EXPECT_EQ(0, d.bytes_received());
8286 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508287 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448288 }
8289}
8290
8291TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558292 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448293
8294 TestDelegate d;
8295 {
8296 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558297 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168298 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8299 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048300
[email protected]f7022f32014-08-21 16:32:198301 req->Start();
Wez2a31b222018-06-07 22:07:158302 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448303
8304 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238305 EXPECT_TRUE(d.have_full_request_headers());
8306 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8307 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448308
Chong Zhang7607f1f2018-06-01 20:52:208309 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:158310 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448311
8312 EXPECT_EQ(1, d.response_started_count());
8313 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508314 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448315
[email protected]6cdfd7f2013-02-08 20:40:158316 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198317 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478318 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448319 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8320
8321 std::string contents;
[email protected]82f84b92013-08-30 18:23:508322 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448323 EXPECT_EQ(contents, d.data_received());
8324 }
8325}
8326
[email protected]79e1fd62013-06-20 06:50:048327TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558328 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048329
8330 TestDelegate d;
8331 {
8332 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558333 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168334 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8335 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048336
8337 EXPECT_FALSE(d.have_full_request_headers());
8338
[email protected]f7022f32014-08-21 16:32:198339 req->Start();
Wez2a31b222018-06-07 22:07:158340 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048341
8342 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048343
Chong Zhang7607f1f2018-06-01 20:52:208344 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:158345 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048346
tommycli59a63432015-11-06 00:10:558347 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048348 EXPECT_EQ(1, d.response_started_count());
8349 EXPECT_TRUE(d.have_full_request_headers());
8350 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8351 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508352 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048353
8354 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198355 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478356 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048357 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8358
8359 std::string contents;
[email protected]82f84b92013-08-30 18:23:508360 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048361 EXPECT_EQ(contents, d.data_received());
8362 }
8363}
8364
Chong Zhang7607f1f2018-06-01 20:52:208365TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedRequestHeaders) {
8366 ASSERT_TRUE(http_test_server()->Start());
8367
8368 TestDelegate d;
8369 {
8370 d.set_quit_on_redirect(true);
8371 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8372 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8373 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8374
8375 // Set initial headers for the request.
8376 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8377 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8378
8379 req->Start();
Wez2a31b222018-06-07 22:07:158380 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208381
8382 // Initial request should only have initial headers.
8383 EXPECT_EQ(1, d.received_redirect_count());
8384 EXPECT_TRUE(d.have_full_request_headers());
8385 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8386 std::string sent_value;
8387 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8388 EXPECT_EQ("Value1", sent_value);
8389 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8390 EXPECT_EQ("Value2", sent_value);
8391 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8392 d.ClearFullRequestHeaders();
8393
8394 // Overwrite Header2 and add Header3.
8395 net::HttpRequestHeaders modified_request_headers;
8396 modified_request_headers.SetHeader("Header2", "");
8397 modified_request_headers.SetHeader("Header3", "Value3");
8398
8399 req->FollowDeferredRedirect(modified_request_headers);
Wez2a31b222018-06-07 22:07:158400 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208401
8402 EXPECT_EQ(1, d.response_started_count());
8403 EXPECT_FALSE(d.received_data_before_response());
8404 EXPECT_EQ(OK, d.request_status());
8405
8406 // Redirected request should also have modified headers.
8407 EXPECT_TRUE(d.have_full_request_headers());
8408 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8409 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8410 EXPECT_EQ("Value1", sent_value);
8411 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8412 EXPECT_EQ("", sent_value);
8413 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8414 EXPECT_EQ("Value3", sent_value);
8415 }
8416}
8417
[email protected]316c1e5e2012-09-12 15:17:448418TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558419 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448420
8421 TestDelegate d;
8422 {
8423 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:368424 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168425 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8426 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198427 req->Start();
Wez2a31b222018-06-07 22:07:158428 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448429
8430 EXPECT_EQ(1, d.received_redirect_count());
8431
[email protected]f7022f32014-08-21 16:32:198432 req->Cancel();
Wez2a31b222018-06-07 22:07:158433 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448434
8435 EXPECT_EQ(1, d.response_started_count());
8436 EXPECT_EQ(0, d.bytes_received());
8437 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508438 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448439 }
8440}
8441
8442TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558443 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448444
[email protected]3b23a222013-05-15 21:33:258445 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448446 {
8447 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368448 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558449 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168450 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448451 HttpRequestHeaders headers;
8452 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198453 req->SetExtraRequestHeaders(headers);
8454 req->Start();
Wez2a31b222018-06-07 22:07:158455 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258456
8457 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198458 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258459 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448460 }
8461
[email protected]3b23a222013-05-15 21:33:258462 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448463 {
8464 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368465 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558466 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168467 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448468 HttpRequestHeaders headers;
8469 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198470 req->SetExtraRequestHeaders(headers);
8471 req->Start();
Wez2a31b222018-06-07 22:07:158472 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448473
[email protected]f7022f32014-08-21 16:32:198474 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258475
8476 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198477 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258478 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448479 }
8480
[email protected]3b23a222013-05-15 21:33:258481 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448482 {
8483 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368484 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558485 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168486 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448487 HttpRequestHeaders headers;
8488 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198489 req->SetExtraRequestHeaders(headers);
8490 req->Start();
Wez2a31b222018-06-07 22:07:158491 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448492
[email protected]f7022f32014-08-21 16:32:198493 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258494
8495 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198496 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258497 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448498 }
8499}
8500
8501TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558502 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448503
8504 // populate the cache
8505 {
8506 TestDelegate d;
8507 d.set_credentials(AuthCredentials(kUser, kSecret));
8508
danakj8522a25b2016-04-16 00:17:368509 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168510 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8511 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198512 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448513
Wez2a31b222018-06-07 22:07:158514 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448515
8516 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8517 }
8518
8519 // repeat request with end-to-end validation. since auth-basic results in a
8520 // cachable page, we expect this test to result in a 304. in which case, the
8521 // response should be fetched from the cache.
8522 {
8523 TestDelegate d;
8524 d.set_credentials(AuthCredentials(kUser, kSecret));
8525
danakj8522a25b2016-04-16 00:17:368526 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168527 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8528 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198529 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8530 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448531
Wez2a31b222018-06-07 22:07:158532 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448533
8534 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8535
8536 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198537 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448538 }
8539}
8540
8541// Check that Set-Cookie headers in 401 responses are respected.
8542// http://crbug.com/6450
8543TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558544 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448545
8546 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558547 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448548
8549 // Request a page that will give a 401 containing a Set-Cookie header.
8550 // Verify that when the transaction is restarted, it includes the new cookie.
8551 {
[email protected]ceefd7fd2012-11-29 00:36:248552 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448553 TestURLRequestContext context(true);
8554 context.set_network_delegate(&network_delegate);
8555 context.Init();
8556
8557 TestDelegate d;
8558 d.set_credentials(AuthCredentials(kUser, kSecret));
8559
danakj8522a25b2016-04-16 00:17:368560 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168561 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8562 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198563 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448564
Wez2a31b222018-06-07 22:07:158565 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448566
8567 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8568
8569 // Make sure we sent the cookie in the restarted transaction.
8570 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8571 != std::string::npos);
8572 }
8573
8574 // Same test as above, except this time the restart is initiated earlier
8575 // (without user intervention since identity is embedded in the URL).
8576 {
[email protected]ceefd7fd2012-11-29 00:36:248577 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448578 TestURLRequestContext context(true);
8579 context.set_network_delegate(&network_delegate);
8580 context.Init();
8581
8582 TestDelegate d;
8583
8584 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188585 replacements.SetUsernameStr("user2");
8586 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448587 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8588
rhalavatib7bd7c792017-04-27 05:25:168589 std::unique_ptr<URLRequest> r(context.CreateRequest(
8590 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198591 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448592
Wez2a31b222018-06-07 22:07:158593 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448594
8595 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8596
8597 // Make sure we sent the cookie in the restarted transaction.
8598 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8599 != std::string::npos);
8600 }
8601}
8602
[email protected]58e32bb2013-01-21 18:23:258603// Tests that load timing works as expected with auth and the cache.
8604TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558605 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258606
8607 // populate the cache
8608 {
8609 TestDelegate d;
8610 d.set_credentials(AuthCredentials(kUser, kSecret));
8611
danakj8522a25b2016-04-16 00:17:368612 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168613 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8614 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198615 r->Start();
[email protected]58e32bb2013-01-21 18:23:258616
Wez2a31b222018-06-07 22:07:158617 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258618
8619 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8620
8621 LoadTimingInfo load_timing_info_before_auth;
8622 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8623 &load_timing_info_before_auth));
8624 TestLoadTimingNotReused(load_timing_info_before_auth,
8625 CONNECT_TIMING_HAS_DNS_TIMES);
8626
8627 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198628 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258629 // The test server does not support keep alive sockets, so the second
8630 // request with auth should use a new socket.
8631 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8632 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8633 load_timing_info.socket_log_id);
8634 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8635 load_timing_info.connect_timing.connect_start);
8636 }
8637
[email protected]3b23a222013-05-15 21:33:258638 // Repeat request with end-to-end validation. Since auth-basic results in a
8639 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258640 // response should be fetched from the cache.
8641 {
8642 TestDelegate d;
8643 d.set_credentials(AuthCredentials(kUser, kSecret));
8644
danakj8522a25b2016-04-16 00:17:368645 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168646 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8647 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198648 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8649 r->Start();
[email protected]58e32bb2013-01-21 18:23:258650
Wez2a31b222018-06-07 22:07:158651 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258652
8653 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8654
8655 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198656 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258657
[email protected]3b23a222013-05-15 21:33:258658 // Since there was a request that went over the wire, the load timing
8659 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258660 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198661 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258662 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258663 }
8664}
8665
[email protected]316c1e5e2012-09-12 15:17:448666// In this test, we do a POST which the server will 302 redirect.
8667// The subsequent transaction should use GET, and should not send the
8668// Content-Type header.
8669// http://code.google.com/p/chromium/issues/detail?id=843
8670TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558671 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448672
8673 const char kData[] = "hello world";
8674
8675 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368676 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168677 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8678 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198679 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078680 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448681
8682 // Set headers (some of which are specific to the POST).
8683 HttpRequestHeaders headers;
8684 headers.AddHeadersFromString(
8685 "Content-Type: multipart/form-data; "
8686 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8687 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8688 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8689 "Accept-Language: en-US,en\r\n"
8690 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8691 "Content-Length: 11\r\n"
8692 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198693 req->SetExtraRequestHeaders(headers);
8694 req->Start();
Wez2a31b222018-06-07 22:07:158695 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448696
8697 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198698 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448699 EXPECT_EQ("text/html", mime_type);
8700
8701 const std::string& data = d.data_received();
8702
8703 // Check that the post-specific headers were stripped:
8704 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8705 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498706 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448707
8708 // These extra request headers should not have been stripped.
8709 EXPECT_TRUE(ContainsString(data, "Accept:"));
8710 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8711 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8712}
8713
jww5fe460ff2015-03-28 00:22:518714// The following tests check that we handle mutating the request for HTTP
8715// redirects as expected.
8716// See https://crbug.com/56373, https://crbug.com/102130, and
8717// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448718
8719TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558720 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448721
tommycli59a63432015-11-06 00:10:558722 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518723 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558724 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448725
8726 HTTPRedirectMethodTest(url, "POST", "GET", true);
8727 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8728 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518729
8730 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8731 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498732 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8733 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8734 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408735 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8736 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448737}
8738
8739TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558740 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448741
tommycli59a63432015-11-06 00:10:558742 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518743 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558744 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448745
8746 HTTPRedirectMethodTest(url, "POST", "GET", true);
8747 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8748 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518749
8750 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8751 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498752 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8753 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8754 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408755 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8756 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448757}
8758
8759TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558760 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448761
tommycli59a63432015-11-06 00:10:558762 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518763 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558764 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448765
8766 HTTPRedirectMethodTest(url, "POST", "GET", true);
8767 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8768 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518769
Alex Clarke1e08882b32017-10-06 14:22:408770 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8771 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8772 std::string());
8773 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8774 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8775 std::string());
jww5fe460ff2015-03-28 00:22:518776 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8777 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408778 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8779 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8780 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8781 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8782 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498783 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8784 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8785 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408786 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8787 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448788}
8789
8790TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558791 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448792
tommycli59a63432015-11-06 00:10:558793 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518794 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558795 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448796
8797 HTTPRedirectMethodTest(url, "POST", "POST", true);
8798 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8799 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518800
8801 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8802 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8803 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8804 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408805 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8806 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448807}
8808
[email protected]0a17aab32014-04-24 03:32:378809TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558810 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378811
tommycli59a63432015-11-06 00:10:558812 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518813 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558814 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378815
8816 HTTPRedirectMethodTest(url, "POST", "POST", true);
8817 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8818 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518819
8820 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8821 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8822 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8823 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408824 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8825 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378826}
8827
8828// Make sure that 308 responses without bodies are not treated as redirects.
8829// Certain legacy apis that pre-date the response code expect this behavior
8830// (Like Google Drive).
8831TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558832 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378833
8834 TestDelegate d;
tommycli59a63432015-11-06 00:10:558835 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378836
rhalavatib7bd7c792017-04-27 05:25:168837 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8838 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378839
[email protected]f7022f32014-08-21 16:32:198840 request->Start();
Wez2a31b222018-06-07 22:07:158841 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508842 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378843 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198844 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378845 EXPECT_EQ("This is not a redirect.", d.data_received());
8846}
8847
[email protected]f878230e2014-04-03 15:36:148848TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558849 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148850
tommycli59a63432015-11-06 00:10:558851 GURL original_url(
8852 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8853 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148854
8855 TestDelegate d;
8856 {
rhalavatib7bd7c792017-04-27 05:25:168857 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8858 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148859
[email protected]f7022f32014-08-21 16:32:198860 r->Start();
Wez2a31b222018-06-07 22:07:158861 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148862
[email protected]f7022f32014-08-21 16:32:198863 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508864 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198865 EXPECT_EQ(original_url, r->original_url());
8866 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148867 }
8868}
8869
[email protected]cba24642014-08-15 20:49:598870TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558871 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598872
tommycli59a63432015-11-06 00:10:558873 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598874 GURL first_party_url("http://example.com");
8875
8876 TestDelegate d;
8877 {
rhalavatib7bd7c792017-04-27 05:25:168878 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8879 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468880 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598881
[email protected]f7022f32014-08-21 16:32:198882 r->Start();
Wez2a31b222018-06-07 22:07:158883 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598884
[email protected]f7022f32014-08-21 16:32:198885 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508886 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468887 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598888 }
8889}
8890
8891TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558892 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598893
tommycli59a63432015-11-06 00:10:558894 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598895 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558896 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598897
8898 TestDelegate d;
8899 {
rhalavatib7bd7c792017-04-27 05:25:168900 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8901 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468902 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198903 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598904 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8905
[email protected]f7022f32014-08-21 16:32:198906 r->Start();
Wez2a31b222018-06-07 22:07:158907 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598908
[email protected]f7022f32014-08-21 16:32:198909 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508910 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468911 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598912 }
8913}
8914
[email protected]316c1e5e2012-09-12 15:17:448915TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558916 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448917
8918 const char kData[] = "hello world";
8919
8920 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368921 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168922 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8923 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198924 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078925 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448926 HttpRequestHeaders headers;
8927 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328928 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198929 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448930
danakj8522a25b2016-04-16 00:17:368931 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558932 req.get(), &default_network_delegate_,
8933 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428934 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8935 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448936
[email protected]f7022f32014-08-21 16:32:198937 req->Start();
Wez2a31b222018-06-07 22:07:158938 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198939 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448940}
8941
8942TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558943 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448944
8945 const char kData[] = "hello world";
8946
8947 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368948 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168949 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8950 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198951 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078952 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448953 HttpRequestHeaders headers;
8954 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328955 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198956 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448957
danakj8522a25b2016-04-16 00:17:368958 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558959 req.get(), &default_network_delegate_,
8960 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098961 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428962 "Very Good Reason"));
8963 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448964
[email protected]f7022f32014-08-21 16:32:198965 req->Start();
Wez2a31b222018-06-07 22:07:158966 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198967 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448968 EXPECT_EQ(kData, d.data_received());
8969}
8970
8971// Check that default A-L header is sent.
8972TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558973 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448974
[email protected]8790210c2013-12-02 05:29:538975 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248976 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448977 TestURLRequestContext context(true);
8978 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438979 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448980 context.Init();
8981
8982 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368983 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558984 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168985 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198986 req->Start();
Wez2a31b222018-06-07 22:07:158987 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448988 EXPECT_EQ("en", d.data_received());
8989}
8990
8991// Check that an empty A-L header is not sent. http://crbug.com/77365.
8992TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558993 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448994
[email protected]8790210c2013-12-02 05:29:538995 std::string empty_string; // Avoid most vexing parse on line below.
8996 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248997 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448998 TestURLRequestContext context(true);
8999 context.set_network_delegate(&network_delegate);
9000 context.Init();
9001 // We override the language after initialization because empty entries
9002 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:439003 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:449004
9005 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369006 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559007 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169008 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199009 req->Start();
Wez2a31b222018-06-07 22:07:159010 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449011 EXPECT_EQ("None", d.data_received());
9012}
9013
9014// Check that if request overrides the A-L header, the default is not appended.
9015// See http://crbug.com/20894
9016TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559017 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449018
9019 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369020 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559021 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169022 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449023 HttpRequestHeaders headers;
9024 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199025 req->SetExtraRequestHeaders(headers);
9026 req->Start();
Wez2a31b222018-06-07 22:07:159027 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449028 EXPECT_EQ(std::string("ru"), d.data_received());
9029}
9030
9031// Check that default A-E header is sent.
9032TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559033 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449034
9035 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369036 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559037 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169038 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449039 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:199040 req->SetExtraRequestHeaders(headers);
9041 req->Start();
Wez2a31b222018-06-07 22:07:159042 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449043 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
9044}
9045
9046// Check that if request overrides the A-E header, the default is not appended.
9047// See http://crbug.com/47381
9048TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559049 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449050
9051 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369052 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559053 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169054 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449055 HttpRequestHeaders headers;
9056 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:199057 req->SetExtraRequestHeaders(headers);
9058 req->Start();
Wez2a31b222018-06-07 22:07:159059 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449060 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
9061 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9062}
9063
[email protected]84f05432013-03-15 01:00:129064// Check that setting the A-C header sends the proper header.
9065TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:559066 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449067
9068 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369069 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559070 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:169071 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449072 HttpRequestHeaders headers;
9073 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:199074 req->SetExtraRequestHeaders(headers);
9075 req->Start();
Wez2a31b222018-06-07 22:07:159076 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449077 EXPECT_EQ(std::string("koi-8r"), d.data_received());
9078}
9079
9080// Check that default User-Agent header is sent.
9081TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559082 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449083
9084 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369085 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559086 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169087 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199088 req->Start();
Wez2a31b222018-06-07 22:07:159089 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199090 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379091 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449092}
9093
9094// Check that if request overrides the User-Agent header,
9095// the default is not appended.
marqf14fff8d2015-12-02 15:52:299096// TODO(crbug.com/564656) This test is flaky on iOS.
9097#if defined(OS_IOS)
9098#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9099#else
9100#define MAYBE_OverrideUserAgent OverrideUserAgent
9101#endif
9102TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559103 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449104
9105 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369106 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559107 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169108 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449109 HttpRequestHeaders headers;
9110 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199111 req->SetExtraRequestHeaders(headers);
9112 req->Start();
Wez2a31b222018-06-07 22:07:159113 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359114 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449115}
9116
[email protected]ee4c30d2012-11-07 15:08:439117// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9118// User-Agent header to be sent but does not send the Accept-Language and
9119// Accept-Charset headers.
9120TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559121 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439122
[email protected]ceefd7fd2012-11-29 00:36:249123 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439124 TestURLRequestContext context(true);
9125 context.set_network_delegate(&network_delegate);
9126 context.Init();
9127 // We override the HttpUserAgentSettings after initialization because empty
9128 // entries get overridden by Init().
9129 context.set_http_user_agent_settings(NULL);
9130
9131 struct {
9132 const char* request;
9133 const char* expected_response;
tommycli59a63432015-11-06 00:10:559134 } tests[] = {{"/echoheader?Accept-Language", "None"},
9135 {"/echoheader?Accept-Charset", "None"},
9136 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439137
viettrungluue4a8b882014-10-16 06:17:389138 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439139 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369140 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169141 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9142 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199143 req->Start();
Wez2a31b222018-06-07 22:07:159144 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439145 EXPECT_EQ(tests[i].expected_response, d.data_received())
9146 << " Request = \"" << tests[i].request << "\"";
9147 }
9148}
9149
[email protected]5033ab82013-03-22 20:17:469150// Make sure that URLRequest passes on its priority updates to
9151// newly-created jobs after the first one.
9152TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559153 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469154
9155 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369156 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169157 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9158 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199159 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469160
danakj8522a25b2016-04-16 00:17:369161 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559162 req.get(), &default_network_delegate_,
9163 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429164 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9165 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469166
[email protected]f7022f32014-08-21 16:32:199167 req->SetPriority(LOW);
9168 req->Start();
9169 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469170
mmenkeed0498b2015-12-08 23:20:429171 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369172 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429173 req.get(), &default_network_delegate_, &job_priority));
9174 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469175
9176 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159177 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429178 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469179}
9180
[email protected]80abdad2014-03-15 00:20:549181// Check that creating a network request while entering/exiting suspend mode
9182// fails as it should. This is the only case where an HttpTransactionFactory
9183// does not return an HttpTransaction.
9184TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9185 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369186 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:179187 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549188 network_layer->OnSuspend();
9189
dchengc7eeda422015-12-26 03:56:489190 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039191 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279192 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549193
9194 TestURLRequestContext context(true);
9195 context.set_http_transaction_factory(&http_cache);
9196 context.Init();
9197
9198 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369199 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169200 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9201 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199202 req->Start();
Wez2a31b222018-06-07 22:07:159203 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549204
9205 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509206 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549207}
9208
mmenke2281f3762015-11-02 20:38:179209namespace {
[email protected]80abdad2014-03-15 00:20:549210
mmenke2281f3762015-11-02 20:38:179211// HttpTransactionFactory that synchronously fails to create transactions.
9212class FailingHttpTransactionFactory : public HttpTransactionFactory {
9213 public:
9214 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9215 : network_session_(network_session) {}
9216
Chris Watkins7a41d3552017-12-01 02:13:279217 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179218
9219 // HttpTransactionFactory methods:
9220 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369221 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179222 return ERR_FAILED;
9223 }
9224
9225 HttpCache* GetCache() override { return nullptr; }
9226
9227 HttpNetworkSession* GetSession() override { return network_session_; }
9228
9229 private:
9230 HttpNetworkSession* network_session_;
9231
9232 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9233};
9234
9235} // namespace
9236
9237// Check that when a request that fails to create an HttpTransaction can be
9238// cancelled while the failure notification is pending, and doesn't send two
9239// failure notifications.
9240//
9241// This currently only happens when in suspend mode and there's no cache, but
9242// just use a special HttpTransactionFactory, to avoid depending on those
9243// behaviors.
9244TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9245 FailingHttpTransactionFactory http_transaction_factory(
9246 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549247 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179248 context.set_http_transaction_factory(&http_transaction_factory);
9249 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549250 context.Init();
9251
9252 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369253 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169254 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9255 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179256 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9257 // try to create an HttpNetworkTransaction synchronously on start).
9258 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199259 req->Start();
mmenke2281f3762015-11-02 20:38:179260 req->Cancel();
Wez2a31b222018-06-07 22:07:159261 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179262 // Run pending error task, if there is one.
9263 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549264
9265 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179266 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509267 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179268
9269 // NetworkDelegate should see the cancellation, but not the error.
9270 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9271 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549272}
9273
ttuttlec0c828492015-05-15 01:25:559274TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559275 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559276
9277 TestDelegate d;
tommycli59a63432015-11-06 00:10:559278 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169279 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9280 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559281
9282 req->Start();
Wez2a31b222018-06-07 22:07:159283 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559284
9285 EXPECT_TRUE(req->response_info().network_accessed);
9286}
9287
9288TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559289 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559290
9291 // Populate the cache.
9292 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369293 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169294 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9295 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559296 req->Start();
Wez2a31b222018-06-07 22:07:159297 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559298
maksim.sisovb53724b52016-09-16 05:30:509299 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559300 EXPECT_TRUE(req->response_info().network_accessed);
9301 EXPECT_FALSE(req->response_info().was_cached);
9302
tommycli59a63432015-11-06 00:10:559303 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:169304 DEFAULT_PRIORITY, &d,
9305 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559306 req->Start();
Wez2a31b222018-06-07 22:07:159307 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559308
maksim.sisovb53724b52016-09-16 05:30:509309 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559310 EXPECT_FALSE(req->response_info().network_accessed);
9311 EXPECT_TRUE(req->response_info().was_cached);
9312}
9313
9314TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559315 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559316
9317 TestDelegate d;
tommycli59a63432015-11-06 00:10:559318 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169319 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9320 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339321 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559322
9323 req->Start();
Wez2a31b222018-06-07 22:07:159324 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559325
9326 EXPECT_FALSE(req->response_info().network_accessed);
9327}
9328
rdsmithbf8c3c12016-11-18 18:16:249329// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089330// correctly in the absence of contention.
9331TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9332 ASSERT_TRUE(http_test_server()->Start());
9333
9334 TestDelegate d;
9335 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169336 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9337 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089338 req->Start();
Wez2a31b222018-06-07 22:07:159339 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089340
9341 EXPECT_TRUE(req->status().is_success());
9342}
9343
ricea3a1c71f2016-06-17 10:05:269344TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9345 ASSERT_TRUE(http_test_server()->Start());
9346
9347 TestDelegate d;
9348 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169349 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9350 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269351 req->Start();
Wez2a31b222018-06-07 22:07:159352 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269353
9354 EXPECT_EQ(5, req->GetRawBodyBytes());
9355}
9356
9357TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9358 ASSERT_TRUE(http_test_server()->Start());
9359
9360 TestDelegate d;
9361 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169362 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9363 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269364 req->Start();
Wez2a31b222018-06-07 22:07:159365 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269366
9367 EXPECT_EQ(30, req->GetRawBodyBytes());
9368}
9369
jamd3f5a3c2016-10-27 18:52:029370// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9371// the delegate isn't called back synchronously.
9372TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9373 ASSERT_TRUE(http_test_server()->Start());
9374 default_network_delegate_.set_before_start_transaction_fails();
9375
9376 TestDelegate d;
9377 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169378 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9379 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029380 req->Start();
9381 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159382 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029383 DCHECK(d.response_completed());
9384 EXPECT_EQ(ERR_FAILED, d.request_status());
9385}
9386
bengr1bf8e942014-11-07 01:36:509387class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9388 public:
9389 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9390 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9391 // tests into the factory tests.
9392 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
9393 }
9394
9395 void SetUpFactory() override {
9396 interceptor_ = new MockURLRequestInterceptor();
9397 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369398 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509399 }
9400
9401 MockURLRequestInterceptor* interceptor() const {
9402 return interceptor_;
9403 }
9404
9405 private:
9406 MockURLRequestInterceptor* interceptor_;
9407};
9408
9409TEST_F(URLRequestInterceptorTestHTTP,
9410 NetworkDelegateNotificationOnRedirectIntercept) {
9411 interceptor()->set_intercept_redirect(true);
9412 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9413 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9414
tommycli59a63432015-11-06 00:10:559415 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509416
9417 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369418 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169419 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9420 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509421 req->Start();
Wez2a31b222018-06-07 22:07:159422 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509423
9424 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9425 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509426 int status = d.request_status();
9427 EXPECT_EQ(OK, status);
9428 if (status == OK)
bengr1bf8e942014-11-07 01:36:509429 EXPECT_EQ(200, req->response_headers()->response_code());
9430
9431 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9432 EXPECT_EQ(1, d.response_started_count());
9433 EXPECT_EQ(0, d.received_redirect_count());
9434
9435 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009436 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509437 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9438}
9439
9440TEST_F(URLRequestInterceptorTestHTTP,
9441 NetworkDelegateNotificationOnErrorIntercept) {
9442 // Intercept that error and respond with an OK response.
9443 interceptor()->set_intercept_final_response(true);
9444 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9445 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9446 default_network_delegate()->set_can_be_intercepted_on_error(true);
9447
tommycli59a63432015-11-06 00:10:559448 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509449
9450 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369451 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559452 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169453 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509454 req->set_method("GET");
9455 req->Start();
Wez2a31b222018-06-07 22:07:159456 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509457
9458 EXPECT_TRUE(interceptor()->did_intercept_final());
9459
9460 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509461 int status = d.request_status();
9462 EXPECT_EQ(OK, status);
9463 if (status == OK)
bengr1bf8e942014-11-07 01:36:509464 EXPECT_EQ(200, req->response_headers()->response_code());
9465 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9466 EXPECT_EQ(1, d.response_started_count());
9467 EXPECT_EQ(0, d.received_redirect_count());
9468
9469 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009470 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509471 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9472}
9473
9474TEST_F(URLRequestInterceptorTestHTTP,
9475 NetworkDelegateNotificationOnResponseIntercept) {
9476 // Intercept that error and respond with an OK response.
9477 interceptor()->set_intercept_final_response(true);
9478
9479 // Intercept with a real URLRequestHttpJob.
9480 interceptor()->set_use_url_request_http_job(true);
9481
tommycli59a63432015-11-06 00:10:559482 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509483
9484 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369485 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169486 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9487 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509488 req->set_method("GET");
9489 req->Start();
Wez2a31b222018-06-07 22:07:159490 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509491
9492 EXPECT_TRUE(interceptor()->did_intercept_final());
9493
9494 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509495 int status = d.request_status();
9496 EXPECT_EQ(OK, status);
9497 if (status == OK)
bengr1bf8e942014-11-07 01:36:509498 EXPECT_EQ(200, req->response_headers()->response_code());
9499 EXPECT_EQ("hello", d.data_received());
9500 EXPECT_EQ(1, d.response_started_count());
9501 EXPECT_EQ(0, d.received_redirect_count());
9502
9503 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009504 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509505 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9506}
9507
mkwst0c5eab872014-11-21 14:18:549508class URLRequestTestReferrerPolicy : public URLRequestTest {
9509 public:
Chris Watkins7a41d3552017-12-01 02:13:279510 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549511
tommycli59a63432015-11-06 00:10:559512 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9513 origin_server_.reset(new EmbeddedTestServer(type));
9514 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9515 origin_server_->AddDefaultHandlers(
9516 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9517 } else {
9518 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9519 }
mkwst0c5eab872014-11-21 14:18:549520 ASSERT_TRUE(origin_server_->Start());
9521 }
9522
tommycli59a63432015-11-06 00:10:559523 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9524 net::EmbeddedTestServer::Type dest_type) {
9525 origin_server_.reset(new EmbeddedTestServer(origin_type));
9526 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9527 origin_server_->AddDefaultHandlers(
9528 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9529 } else {
9530 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9531 }
mkwst0c5eab872014-11-21 14:18:549532 ASSERT_TRUE(origin_server_->Start());
9533
tommycli59a63432015-11-06 00:10:559534 destination_server_.reset(new EmbeddedTestServer(dest_type));
9535 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9536 destination_server_->AddDefaultHandlers(
9537 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9538 } else {
9539 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9540 }
mkwst0c5eab872014-11-21 14:18:549541 ASSERT_TRUE(destination_server_->Start());
9542 }
9543
9544 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9545 const GURL& referrer,
9546 const GURL& expected) {
9547 // Create and execute the request: we'll only have a |destination_server_|
9548 // if the origins are meant to be distinct. Otherwise, we'll use the
9549 // |origin_server_| for both endpoints.
9550 GURL destination_url =
tommycli59a63432015-11-06 00:10:559551 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9552 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549553 GURL origin_url =
tommycli59a63432015-11-06 00:10:559554 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549555
9556 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169557 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9558 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549559 req->set_referrer_policy(policy);
9560 req->SetReferrer(referrer.spec());
9561 req->Start();
Wez2a31b222018-06-07 22:07:159562 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549563
9564 EXPECT_EQ(1, d.response_started_count());
9565 EXPECT_EQ(1, d.received_redirect_count());
9566 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509567 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549568 EXPECT_EQ(200, req->response_headers()->response_code());
9569
9570 EXPECT_EQ(expected.spec(), req->referrer());
9571 if (expected.is_empty())
9572 EXPECT_EQ("None", d.data_received());
9573 else
9574 EXPECT_EQ(expected.spec(), d.data_received());
9575 }
9576
tommycli59a63432015-11-06 00:10:559577 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549578
9579 private:
danakj8522a25b2016-04-16 00:17:369580 std::unique_ptr<EmbeddedTestServer> origin_server_;
9581 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549582};
9583
9584TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559585 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549586
estarkc8ccba82017-06-13 22:37:409587 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549588 VerifyReferrerAfterRedirect(
9589 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409590 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549591
9592 VerifyReferrerAfterRedirect(
9593 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409594 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549595
9596 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409597 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549598
estarkc8ccba82017-06-13 22:37:409599 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9600 referrer);
9601
9602 // The original referrer set on the request is expected to obey the referrer
9603 // policy and already be stripped to the origin; thus this test case just
9604 // checks that this policy doesn't cause the referrer to change when following
9605 // a redirect.
9606 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9607 referrer.GetOrigin());
9608
9609 VerifyReferrerAfterRedirect(
9610 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9611 referrer);
9612
9613 // The original referrer set on the request is expected to obey the referrer
9614 // policy and already be stripped to the origin; thus this test case just
9615 // checks that this policy doesn't cause the referrer to change when following
9616 // a redirect.
9617 VerifyReferrerAfterRedirect(
9618 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9619 referrer.GetOrigin(), referrer.GetOrigin());
9620
9621 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549622}
9623
tommycli59a63432015-11-06 00:10:559624TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9625 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9626 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409627 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549628
9629 VerifyReferrerAfterRedirect(
9630 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409631 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549632
9633 VerifyReferrerAfterRedirect(
9634 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409635 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549636
9637 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409638 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9639 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549640
estarkc8ccba82017-06-13 22:37:409641 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9642 referrer);
9643
9644 // The original referrer set on the request is expected to obey the referrer
9645 // policy and already be stripped to the origin; thus this test case just
9646 // checks that this policy doesn't cause the referrer to change when following
9647 // a redirect.
9648 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9649 referrer.GetOrigin());
9650
9651 VerifyReferrerAfterRedirect(
9652 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9653
9654 // The original referrer set on the request is expected to obey the referrer
9655 // policy and already be stripped to the origin; thus this test case just
9656 // checks that this policy doesn't cause the referrer to change when following
9657 // a redirect.
9658 VerifyReferrerAfterRedirect(
9659 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9660 referrer.GetOrigin(), referrer.GetOrigin());
9661
9662 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549663}
9664
9665TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559666 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409667 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549668
9669 VerifyReferrerAfterRedirect(
9670 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409671 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549672
9673 VerifyReferrerAfterRedirect(
9674 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409675 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549676
9677 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409678 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549679
estarkc8ccba82017-06-13 22:37:409680 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9681 referrer);
9682
9683 // The original referrer set on the request is expected to obey the referrer
9684 // policy and already be stripped to the origin; thus this test case just
9685 // checks that this policy doesn't cause the referrer to change when following
9686 // a redirect.
9687 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9688 referrer.GetOrigin());
9689
9690 VerifyReferrerAfterRedirect(
9691 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9692 referrer);
9693
9694 // The original referrer set on the request is expected to obey the referrer
9695 // policy and already be stripped to the origin; thus this test case just
9696 // checks that this policy doesn't cause the referrer to change when following
9697 // a redirect.
9698 VerifyReferrerAfterRedirect(
9699 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9700 referrer.GetOrigin(), referrer.GetOrigin());
9701
9702 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549703}
9704
tommycli59a63432015-11-06 00:10:559705TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9706 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9707 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409708 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549709
9710 VerifyReferrerAfterRedirect(
9711 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409712 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549713
9714 VerifyReferrerAfterRedirect(
9715 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409716 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549717
9718 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409719 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559720 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549721
estarkc8ccba82017-06-13 22:37:409722 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9723 referrer);
9724
9725 // The original referrer set on the request is expected to obey the referrer
9726 // policy and already be stripped to the origin; thus this test case just
9727 // checks that this policy doesn't cause the referrer to change when following
9728 // a redirect.
9729 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9730 referrer.GetOrigin());
9731
9732 VerifyReferrerAfterRedirect(
9733 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9734
9735 // The original referrer set on the request is expected to obey the referrer
9736 // policy and already be stripped to the origin; thus this test case just
9737 // checks that this policy doesn't cause the referrer to change when following
9738 // a redirect.
9739 VerifyReferrerAfterRedirect(
9740 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9741 referrer.GetOrigin(), referrer.GetOrigin());
9742
9743 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549744}
9745
tommycli59a63432015-11-06 00:10:559746TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9747 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9748 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409749 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549750
9751 VerifyReferrerAfterRedirect(
9752 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409753 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549754
9755 VerifyReferrerAfterRedirect(
9756 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409757 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549758
9759 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409760 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559761 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549762
estarkc8ccba82017-06-13 22:37:409763 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9764 referrer);
9765
9766 // The original referrer set on the request is expected to obey the referrer
9767 // policy and already be stripped to the origin; thus this test case just
9768 // checks that this policy doesn't cause the referrer to change when following
9769 // a redirect.
9770 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9771 referrer.GetOrigin());
9772
9773 VerifyReferrerAfterRedirect(
9774 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9775
9776 // The original referrer set on the request is expected to obey the referrer
9777 // policy and already be stripped to the origin; thus this test case just
9778 // checks that this policy doesn't cause the referrer to change when following
9779 // a redirect.
9780 VerifyReferrerAfterRedirect(
9781 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9782 referrer.GetOrigin(), referrer.GetOrigin());
9783
9784 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549785}
9786
tommycli59a63432015-11-06 00:10:559787TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9788 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9789 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409790 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549791
9792 VerifyReferrerAfterRedirect(
9793 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409794 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549795
9796 VerifyReferrerAfterRedirect(
9797 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409798 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549799
9800 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409801 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559802 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549803
estarkc8ccba82017-06-13 22:37:409804 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9805 referrer);
9806
9807 // The original referrer set on the request is expected to obey the referrer
9808 // policy and already be stripped to the origin; thus this test case just
9809 // checks that this policy doesn't cause the referrer to change when following
9810 // a redirect.
9811 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9812 referrer.GetOrigin());
9813
9814 VerifyReferrerAfterRedirect(
9815 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9816
9817 // The original referrer set on the request is expected to obey the referrer
9818 // policy and already be stripped to the origin, though it should be
9819 // subsequently cleared during the downgrading redirect.
9820 VerifyReferrerAfterRedirect(
9821 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9822 referrer.GetOrigin(), GURL());
9823
9824 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549825}
9826
Bence Béky98447b12018-05-08 03:14:019827class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509828 public:
fdorayf33fede2017-05-11 21:18:109829 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099830 default_context_.set_network_delegate(&default_network_delegate_);
9831 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509832 }
Martijn Croonenb1383da2017-10-11 11:56:359833 ~HTTPSRequestTest() override {
9834 SetTransportSecurityStateSourceForTesting(nullptr);
9835 }
[email protected]87a09a92011-07-14 15:50:509836
9837 protected:
[email protected]ceefd7fd2012-11-29 00:36:249838 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099839 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469840};
9841
[email protected]c044616e2013-02-20 02:01:269842TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559843 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9844 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229845 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119846 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469847
[email protected]ea224582008-12-07 20:25:469848 TestDelegate d;
9849 {
danakj8522a25b2016-04-16 00:17:369850 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169851 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9852 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199853 r->Start();
9854 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469855
Wez2a31b222018-06-07 22:07:159856 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469857
9858 EXPECT_EQ(1, d.response_started_count());
9859 EXPECT_FALSE(d.received_data_before_response());
9860 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199861 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199862 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199863 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199864 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199865 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469866 }
[email protected]ea224582008-12-07 20:25:469867}
9868
[email protected]5774ada2010-07-15 06:30:549869TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559870 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9871 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9872 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229873 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119874 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339875
9876 bool err_allowed = true;
9877 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9878 TestDelegate d;
9879 {
9880 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369881 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169882 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9883 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339884
[email protected]f7022f32014-08-21 16:32:199885 r->Start();
9886 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339887
Wez2a31b222018-06-07 22:07:159888 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339889
9890 EXPECT_EQ(1, d.response_started_count());
9891 EXPECT_FALSE(d.received_data_before_response());
9892 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179893 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339894 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199895 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179896 } else {
[email protected]bacff652009-03-31 17:50:339897 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179898 }
[email protected]bacff652009-03-31 17:50:339899 }
9900 }
9901}
9902
[email protected]5774ada2010-07-15 06:30:549903TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559904 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9905 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9906 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229907 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119908 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339909
9910 // Iterate from false to true, just so that we do the opposite of the
9911 // previous test in order to increase test coverage.
9912 bool err_allowed = false;
9913 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9914 TestDelegate d;
9915 {
9916 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369917 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169918 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9919 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339920
[email protected]f7022f32014-08-21 16:32:199921 r->Start();
9922 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339923
Wez2a31b222018-06-07 22:07:159924 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339925
9926 EXPECT_EQ(1, d.response_started_count());
9927 EXPECT_FALSE(d.received_data_before_response());
9928 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179929 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339930 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199931 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179932 } else {
[email protected]bacff652009-03-31 17:50:339933 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179934 }
[email protected]bacff652009-03-31 17:50:339935 }
9936 }
9937}
[email protected]73e0bba2009-02-19 22:57:099938
tommycli59a63432015-11-06 00:10:559939// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9940// security state. (see http://crbug.com/550977).
9941#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359942// This tests that a load of a domain with preloaded HSTS and HPKP with a
9943// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9944// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449945TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359946 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9947
tommycli59a63432015-11-06 00:10:559948 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9949 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9950 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449951 ASSERT_TRUE(test_server.Start());
9952
Martijn Croonenb1383da2017-10-11 11:56:359953 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9954 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9955 // means that we have to use a MockHostResolver in order to direct
9956 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9957 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449958
9959 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249960 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449961 TestURLRequestContext context(true);
9962 context.set_network_delegate(&network_delegate);
9963 context.set_host_resolver(&host_resolver);
9964 TransportSecurityState transport_security_state;
9965 context.set_transport_security_state(&transport_security_state);
9966 context.Init();
9967
9968 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369969 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359970 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369971 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169972 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449973
[email protected]f7022f32014-08-21 16:32:199974 r->Start();
9975 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449976
Wez2a31b222018-06-07 22:07:159977 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449978
9979 EXPECT_EQ(1, d.response_started_count());
9980 EXPECT_FALSE(d.received_data_before_response());
9981 EXPECT_TRUE(d.have_certificate_errors());
9982 EXPECT_TRUE(d.certificate_errors_are_fatal());
9983}
9984
9985// This tests that cached HTTPS page loads do not cause any updates to the
9986// TransportSecurityState.
9987TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359988 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9989
[email protected]316c1e5e2012-09-12 15:17:449990 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9991 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559992 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9993 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9994 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449995 ASSERT_TRUE(test_server.Start());
9996
Martijn Croonenb1383da2017-10-11 11:56:359997 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9998 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9999 // means that we have to use a MockHostResolver in order to direct
10000 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
10001 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:4410002
10003 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:2410004 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:4410005 TestURLRequestContext context(true);
10006 context.set_network_delegate(&network_delegate);
10007 context.set_host_resolver(&host_resolver);
10008 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:2610009
martijnc0d6b622015-06-30 19:14:4010010 TransportSecurityState::STSState static_sts_state;
10011 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610012 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510013 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:4410014 context.set_transport_security_state(&transport_security_state);
10015 context.Init();
10016
martijnc0d6b622015-06-30 19:14:4010017 TransportSecurityState::STSState dynamic_sts_state;
10018 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510019 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10020 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10021 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10022 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610023
[email protected]316c1e5e2012-09-12 15:17:4410024 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610025 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510026 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610027 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610028 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410029
[email protected]f7022f32014-08-21 16:32:1910030 r->Start();
10031 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410032
Wez2a31b222018-06-07 22:07:1510033 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410034
10035 EXPECT_EQ(1, d.response_started_count());
10036 EXPECT_FALSE(d.received_data_before_response());
10037 EXPECT_TRUE(d.have_certificate_errors());
10038 EXPECT_TRUE(d.certificate_errors_are_fatal());
10039
[email protected]9e6968d2014-05-07 21:46:2610040 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010041 TransportSecurityState::STSState new_static_sts_state;
10042 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610043 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510044 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10045 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010046 TransportSecurityState::STSState new_dynamic_sts_state;
10047 TransportSecurityState::PKPState new_dynamic_pkp_state;
10048 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510049 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010050 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510051 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610052
martijnc0d6b622015-06-30 19:14:4010053 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10054 EXPECT_EQ(new_static_sts_state.include_subdomains,
10055 static_sts_state.include_subdomains);
10056 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10057 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810058 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10059 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10060 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410061}
10062
[email protected]8ccc69f2012-11-28 19:52:1410063// Make sure HSTS preserves a POST request's method and body.
10064TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10065 static const char kData[] = "hello world";
10066
tommycli59a63432015-11-06 00:10:5510067 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10068 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210069 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410070 ASSERT_TRUE(test_server.Start());
10071
10072
10073 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10074 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510075 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210076 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410077 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410078
10079 // Force https for www.somewhere.com.
10080 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010081 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10082 bool include_subdomains = false;
10083 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10084 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410085
10086 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10087
10088 TestURLRequestContext context(true);
10089 context.set_host_resolver(&host_resolver);
10090 context.set_transport_security_state(&transport_security_state);
10091 context.set_network_delegate(&network_delegate);
10092 context.Init();
10093
10094 TestDelegate d;
10095 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10096 // cause a certificate error. Ignore the error.
10097 d.set_allow_certificate_errors(true);
10098
danakj8522a25b2016-04-16 00:17:3610099 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910100 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610101 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610102 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910103 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710104 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410105
[email protected]f7022f32014-08-21 16:32:1910106 req->Start();
Wez2a31b222018-06-07 22:07:1510107 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410108
[email protected]f7022f32014-08-21 16:32:1910109 EXPECT_EQ("https", req->url().scheme());
10110 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410111 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010112
10113 LoadTimingInfo load_timing_info;
10114 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10115 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10116 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410117}
10118
rob4e0be1f2014-09-11 23:40:2210119// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10120TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10121 static const char kOriginHeaderValue[] = "http://www.example.com";
10122
tommycli59a63432015-11-06 00:10:5510123 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10124 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210125 ASSERT_TRUE(test_server.Start());
10126
10127 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10128 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510129 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10130 // default.
rob4e0be1f2014-09-11 23:40:2210131 MockHostResolver host_resolver;
10132
10133 TransportSecurityState transport_security_state;
10134 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10135 bool include_subdomains = false;
10136 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10137
10138 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10139
10140 MockCertVerifier cert_verifier;
10141 cert_verifier.set_default_result(OK);
10142
10143 TestURLRequestContext context(true);
10144 context.set_host_resolver(&host_resolver);
10145 context.set_transport_security_state(&transport_security_state);
10146 context.set_network_delegate(&network_delegate);
10147 context.set_cert_verifier(&cert_verifier);
10148 context.Init();
10149
10150 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10151 test_server.host_port_pair().port()));
10152 url::Replacements<char> replacements;
10153 const char kNewScheme[] = "https";
10154 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10155 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10156
10157 TestDelegate d;
10158 // Quit on redirect to allow response header inspection upon redirect.
10159 d.set_quit_on_redirect(true);
10160
rhalavatib7bd7c792017-04-27 05:25:1610161 std::unique_ptr<URLRequest> req(context.CreateRequest(
10162 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210163 // Set Origin header to simulate a cross-origin request.
10164 HttpRequestHeaders request_headers;
10165 request_headers.SetHeader("Origin", kOriginHeaderValue);
10166 req->SetExtraRequestHeaders(request_headers);
10167
10168 req->Start();
Wez2a31b222018-06-07 22:07:1510169 d.RunUntilComplete();
rob4e0be1f2014-09-11 23:40:2210170
10171 EXPECT_EQ(1, d.received_redirect_count());
10172
10173 const HttpResponseHeaders* headers = req->response_headers();
10174 std::string redirect_location;
10175 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
10176 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10177
10178 std::string received_cors_header;
10179 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
10180 &received_cors_header));
10181 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10182}
10183
[email protected]316c1e5e2012-09-12 15:17:4410184namespace {
10185
10186class SSLClientAuthTestDelegate : public TestDelegate {
10187 public:
10188 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
10189 }
dchengb03027d2014-10-21 12:00:2010190 void OnCertificateRequested(URLRequest* request,
10191 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410192 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:2310193 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:4410194 }
10195 int on_certificate_requested_count() {
10196 return on_certificate_requested_count_;
10197 }
10198 private:
10199 int on_certificate_requested_count_;
10200};
10201
David Benjamin76a40ad2018-02-24 22:22:0810202class TestSSLPrivateKey : public SSLPrivateKey {
10203 public:
10204 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10205 : key_(std::move(key)) {}
10206
10207 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10208 int sign_count() const { return sign_count_; }
10209
10210 std::vector<uint16_t> GetAlgorithmPreferences() override {
10211 return key_->GetAlgorithmPreferences();
10212 }
10213 void Sign(uint16_t algorithm,
10214 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610215 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810216 sign_count_++;
10217 if (fail_signing_) {
10218 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610219 FROM_HERE, base::BindOnce(std::move(callback),
10220 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10221 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810222 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610223 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810224 }
10225 }
10226
10227 private:
10228 ~TestSSLPrivateKey() override = default;
10229
10230 scoped_refptr<SSLPrivateKey> key_;
10231 bool fail_signing_ = false;
10232 int sign_count_ = 0;
10233};
10234
[email protected]316c1e5e2012-09-12 15:17:4410235} // namespace
10236
10237// TODO(davidben): Test the rest of the code. Specifically,
10238// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410239// - Getting a certificate request in an SSL renegotiation sending the
10240// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810241TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510242 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10243 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210244 ssl_config.client_cert_type =
10245 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810246 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510247 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210248 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410249 ASSERT_TRUE(test_server.Start());
10250
10251 SSLClientAuthTestDelegate d;
10252 {
danakj8522a25b2016-04-16 00:17:3610253 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610254 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10255 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410256
[email protected]f7022f32014-08-21 16:32:1910257 r->Start();
10258 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410259
Wez2a31b222018-06-07 22:07:1510260 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410261
10262 EXPECT_EQ(1, d.on_certificate_requested_count());
10263 EXPECT_FALSE(d.received_data_before_response());
10264 EXPECT_EQ(0, d.bytes_received());
10265
10266 // Send no certificate.
10267 // TODO(davidben): Get temporary client cert import (with keys) working on
10268 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410269 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410270
Wez2a31b222018-06-07 22:07:1510271 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410272
David Benjamin76a40ad2018-02-24 22:22:0810273 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410274 EXPECT_EQ(1, d.response_started_count());
10275 EXPECT_FALSE(d.received_data_before_response());
10276 EXPECT_NE(0, d.bytes_received());
10277 }
10278}
10279
David Benjamin76a40ad2018-02-24 22:22:0810280TEST_F(HTTPSRequestTest, ClientAuth) {
10281 std::unique_ptr<FakeClientCertIdentity> identity =
10282 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10283 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10284 ASSERT_TRUE(identity);
10285 scoped_refptr<TestSSLPrivateKey> private_key =
10286 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10287
10288 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10289 net::SSLServerConfig ssl_config;
10290 ssl_config.client_cert_type =
10291 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10292 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10293 test_server.AddDefaultHandlers(
10294 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10295 ASSERT_TRUE(test_server.Start());
10296
10297 {
10298 SSLClientAuthTestDelegate d;
10299 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10300 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10301 TRAFFIC_ANNOTATION_FOR_TESTS));
10302
10303 r->Start();
10304 EXPECT_TRUE(r->is_pending());
10305
Wez2a31b222018-06-07 22:07:1510306 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810307
10308 EXPECT_EQ(1, d.on_certificate_requested_count());
10309 EXPECT_FALSE(d.received_data_before_response());
10310 EXPECT_EQ(0, d.bytes_received());
10311
10312 // Send a certificate.
10313 r->ContinueWithCertificate(identity->certificate(), private_key);
10314
Wez2a31b222018-06-07 22:07:1510315 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810316
10317 EXPECT_EQ(OK, d.request_status());
10318 EXPECT_EQ(1, d.response_started_count());
10319 EXPECT_FALSE(d.received_data_before_response());
10320 EXPECT_NE(0, d.bytes_received());
10321
10322 // The private key should have been used.
10323 EXPECT_EQ(1, private_key->sign_count());
10324 }
10325
10326 // Close all connections and clear the session cache to force a new handshake.
10327 default_context_.http_transaction_factory()
10328 ->GetSession()
10329 ->CloseAllConnections();
10330 SSLClientSocket::ClearSessionCache();
10331
10332 // Connecting again should not call OnCertificateRequested. The identity is
10333 // taken from the client auth cache.
10334 {
10335 SSLClientAuthTestDelegate d;
10336 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10337 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10338 TRAFFIC_ANNOTATION_FOR_TESTS));
10339
10340 r->Start();
10341 EXPECT_TRUE(r->is_pending());
10342
Wez2a31b222018-06-07 22:07:1510343 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810344
10345 EXPECT_EQ(OK, d.request_status());
10346 EXPECT_EQ(0, d.on_certificate_requested_count());
10347 EXPECT_FALSE(d.received_data_before_response());
10348 EXPECT_EQ(1, d.response_started_count());
10349 EXPECT_FALSE(d.received_data_before_response());
10350 EXPECT_NE(0, d.bytes_received());
10351
10352 // The private key should have been used.
10353 EXPECT_EQ(2, private_key->sign_count());
10354 }
10355}
10356
10357// Test that private keys that fail to sign anything get evicted from the cache.
10358TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10359 std::unique_ptr<FakeClientCertIdentity> identity =
10360 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10361 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10362 ASSERT_TRUE(identity);
10363 scoped_refptr<TestSSLPrivateKey> private_key =
10364 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10365 private_key->set_fail_signing(true);
10366
10367 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10368 net::SSLServerConfig ssl_config;
10369 ssl_config.client_cert_type =
10370 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10371 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10372 test_server.AddDefaultHandlers(
10373 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10374 ASSERT_TRUE(test_server.Start());
10375
10376 {
10377 SSLClientAuthTestDelegate d;
10378 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10379 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10380 TRAFFIC_ANNOTATION_FOR_TESTS));
10381
10382 r->Start();
10383 EXPECT_TRUE(r->is_pending());
Wez2a31b222018-06-07 22:07:1510384 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810385
10386 EXPECT_EQ(1, d.on_certificate_requested_count());
10387 EXPECT_FALSE(d.received_data_before_response());
10388 EXPECT_EQ(0, d.bytes_received());
10389
10390 // Send a certificate.
10391 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510392 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810393
10394 // The private key cannot sign anything, so we report an error.
10395 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10396 EXPECT_EQ(1, d.response_started_count());
10397 EXPECT_FALSE(d.received_data_before_response());
10398 EXPECT_EQ(0, d.bytes_received());
10399
10400 // The private key should have been used.
10401 EXPECT_EQ(1, private_key->sign_count());
10402 }
10403
10404 // Close all connections and clear the session cache to force a new handshake.
10405 default_context_.http_transaction_factory()
10406 ->GetSession()
10407 ->CloseAllConnections();
10408 SSLClientSocket::ClearSessionCache();
10409
10410 // The bad identity should have been evicted from the cache, so connecting
10411 // again should call OnCertificateRequested again.
10412 {
10413 SSLClientAuthTestDelegate d;
10414 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10415 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10416 TRAFFIC_ANNOTATION_FOR_TESTS));
10417
10418 r->Start();
10419 EXPECT_TRUE(r->is_pending());
10420
Wez2a31b222018-06-07 22:07:1510421 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810422
10423 EXPECT_EQ(1, d.on_certificate_requested_count());
10424 EXPECT_FALSE(d.received_data_before_response());
10425 EXPECT_EQ(0, d.bytes_received());
10426
10427 // There should have been no additional uses of the private key.
10428 EXPECT_EQ(1, private_key->sign_count());
10429 }
10430}
10431
10432// Test that cached private keys that fail to sign anything trigger a
10433// retry. This is so we handle unplugged smartcards
10434// gracefully. https://crbug.com/813022.
10435TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10436 std::unique_ptr<FakeClientCertIdentity> identity =
10437 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10438 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10439 ASSERT_TRUE(identity);
10440 scoped_refptr<TestSSLPrivateKey> private_key =
10441 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10442
10443 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10444 net::SSLServerConfig ssl_config;
10445 ssl_config.client_cert_type =
10446 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10447 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10448 test_server.AddDefaultHandlers(
10449 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10450 ASSERT_TRUE(test_server.Start());
10451
10452 // Connect with a client certificate to put it in the client auth cache.
10453 {
10454 SSLClientAuthTestDelegate d;
10455 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10456 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10457 TRAFFIC_ANNOTATION_FOR_TESTS));
10458
10459 r->Start();
10460 EXPECT_TRUE(r->is_pending());
10461
Wez2a31b222018-06-07 22:07:1510462 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810463
10464 EXPECT_EQ(1, d.on_certificate_requested_count());
10465 EXPECT_FALSE(d.received_data_before_response());
10466 EXPECT_EQ(0, d.bytes_received());
10467
10468 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510469 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810470
10471 EXPECT_EQ(OK, d.request_status());
10472 EXPECT_EQ(1, d.response_started_count());
10473 EXPECT_FALSE(d.received_data_before_response());
10474 EXPECT_NE(0, d.bytes_received());
10475
10476 // The private key should have been used.
10477 EXPECT_EQ(1, private_key->sign_count());
10478 }
10479
10480 // Close all connections and clear the session cache to force a new handshake.
10481 default_context_.http_transaction_factory()
10482 ->GetSession()
10483 ->CloseAllConnections();
10484 SSLClientSocket::ClearSessionCache();
10485
10486 // Cause the private key to fail. Connecting again should attempt to use it,
10487 // notice the failure, and then request a new identity via
10488 // OnCertificateRequested.
10489 private_key->set_fail_signing(true);
10490
10491 {
10492 SSLClientAuthTestDelegate d;
10493 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10494 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10495 TRAFFIC_ANNOTATION_FOR_TESTS));
10496
10497 r->Start();
10498 EXPECT_TRUE(r->is_pending());
10499
Wez2a31b222018-06-07 22:07:1510500 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810501
10502 // There was an additional signing call on the private key (the one which
10503 // failed).
10504 EXPECT_EQ(2, private_key->sign_count());
10505
10506 // That caused another OnCertificateRequested call.
10507 EXPECT_EQ(1, d.on_certificate_requested_count());
10508 EXPECT_FALSE(d.received_data_before_response());
10509 EXPECT_EQ(0, d.bytes_received());
10510 }
10511}
10512
[email protected]316c1e5e2012-09-12 15:17:4410513TEST_F(HTTPSRequestTest, ResumeTest) {
10514 // Test that we attempt a session resume when making two connections to the
10515 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210516 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410517 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210518 SpawnedTestServer test_server(
10519 SpawnedTestServer::TYPE_HTTPS,
10520 ssl_options,
10521 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410522 ASSERT_TRUE(test_server.Start());
10523
10524 SSLClientSocket::ClearSessionCache();
10525
10526 {
10527 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610528 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610529 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10530 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410531
[email protected]f7022f32014-08-21 16:32:1910532 r->Start();
10533 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410534
Wez2a31b222018-06-07 22:07:1510535 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410536
10537 EXPECT_EQ(1, d.response_started_count());
10538 }
10539
10540 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10541 CloseAllConnections();
10542
10543 {
10544 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610545 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610546 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10547 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410548
[email protected]f7022f32014-08-21 16:32:1910549 r->Start();
10550 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410551
Wez2a31b222018-06-07 22:07:1510552 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410553
10554 // The response will look like;
10555 // insert abc
10556 // lookup abc
10557 // insert xyz
10558 //
10559 // With a newline at the end which makes the split think that there are
10560 // four lines.
10561
10562 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910563 std::vector<std::string> lines = base::SplitString(
10564 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410565 ASSERT_EQ(4u, lines.size()) << d.data_received();
10566
10567 std::string session_id;
10568
10569 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910570 std::vector<std::string> parts = base::SplitString(
10571 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410572 ASSERT_EQ(2u, parts.size());
10573 if (i == 0) {
10574 EXPECT_EQ("insert", parts[0]);
10575 session_id = parts[1];
10576 } else {
10577 EXPECT_EQ("lookup", parts[0]);
10578 EXPECT_EQ(session_id, parts[1]);
10579 }
10580 }
10581 }
10582}
10583
Adam Langley32352ad2014-10-14 22:31:0010584// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
10585// the result of fetching "ssl-session-cache" from the test server, indicates
10586// that exactly two different sessions were inserted, with no lookups etc.
10587static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:2910588 std::vector<std::string> lines = base::SplitString(
10589 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010590 ASSERT_EQ(3u, lines.size()) << session_info;
10591
10592 std::string session_id;
10593 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910594 std::vector<std::string> parts = base::SplitString(
10595 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010596 ASSERT_EQ(2u, parts.size());
10597 EXPECT_EQ("insert", parts[0]);
10598 if (i == 0) {
10599 session_id = parts[1];
10600 } else {
10601 EXPECT_NE(session_id, parts[1]);
10602 }
10603 }
10604}
10605
[email protected]316c1e5e2012-09-12 15:17:4410606TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10607 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10608 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210609 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410610 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210611 SpawnedTestServer test_server(
10612 SpawnedTestServer::TYPE_HTTPS,
10613 ssl_options,
10614 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410615 ASSERT_TRUE(test_server.Start());
10616
10617 SSLClientSocket::ClearSessionCache();
10618
10619 {
10620 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610621 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610622 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10623 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410624
[email protected]f7022f32014-08-21 16:32:1910625 r->Start();
10626 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410627
Wez2a31b222018-06-07 22:07:1510628 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410629
10630 EXPECT_EQ(1, d.response_started_count());
10631 }
10632
10633 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110634 HttpNetworkSession::Context session_context;
10635 session_context.host_resolver = default_context_.host_resolver();
10636 session_context.cert_verifier = default_context_.cert_verifier();
10637 session_context.transport_security_state =
10638 default_context_.transport_security_state();
10639 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010640 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110641 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910642 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110643 session_context.ssl_config_service = default_context_.ssl_config_service();
10644 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410645 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110646 session_context.http_server_properties =
10647 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410648
mmenke6ddfbea2017-05-31 21:48:4110649 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10650 session_context);
zhongyi4928bd52017-02-08 02:16:2710651 std::unique_ptr<HttpCache> cache(
10652 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10653 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410654
10655 default_context_.set_http_transaction_factory(cache.get());
10656
10657 {
10658 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610659 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610660 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10661 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410662
[email protected]f7022f32014-08-21 16:32:1910663 r->Start();
10664 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410665
Wez2a31b222018-06-07 22:07:1510666 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410667
10668 // The response will look like;
10669 // insert abc
10670 // insert xyz
10671 //
10672 // With a newline at the end which makes the split think that there are
10673 // three lines.
10674
10675 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010676 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410677 }
10678}
10679
Bence Béky98447b12018-05-08 03:14:0110680class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510681 public:
fdorayf33fede2017-05-11 21:18:1010682 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410683 ssl_config_service_ = new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5610684 false /* online revocation checking */,
davidben095ebb52017-04-12 22:23:3410685 false /* require rev. checking for local anchors */,
10686 false /* token binding enabled */);
10687 context_.set_ssl_config_service(ssl_config_service_.get());
10688 }
Chris Watkins7a41d3552017-12-01 02:13:2710689 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510690
10691 protected:
davidben095ebb52017-04-12 22:23:3410692 TestSSLConfigService* ssl_config_service() {
10693 return ssl_config_service_.get();
10694 }
10695
[email protected]48d2b7c52014-06-27 01:16:5510696 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10697 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010698 context_.Init();
10699 delegate_.set_allow_certificate_errors(true);
10700
[email protected]48d2b7c52014-06-27 01:16:5510701 SpawnedTestServer test_server(
10702 SpawnedTestServer::TYPE_HTTPS,
10703 ssl_options,
10704 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10705 ASSERT_TRUE(test_server.Start());
10706
tommycli59a63432015-11-06 00:10:5510707 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610708 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510709 request_->Start();
10710
Wez2a31b222018-06-07 22:07:1510711 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510712 }
10713
davidben095ebb52017-04-12 22:23:3410714 void ExpectConnection(int version) {
10715 EXPECT_EQ(1, delegate_.response_started_count());
10716 EXPECT_NE(0, delegate_.bytes_received());
10717 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10718 request_->ssl_info().connection_status));
10719 }
10720
[email protected]48d2b7c52014-06-27 01:16:5510721 void ExpectFailure(int error) {
10722 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010723 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510724 }
10725
10726 private:
10727 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710728 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610729 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410730 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510731};
10732
davidbenb127ca82015-06-15 19:05:4210733// Tests the TLS 1.0 fallback doesn't happen.
10734TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510735 SpawnedTestServer::SSLOptions ssl_options(
10736 SpawnedTestServer::SSLOptions::CERT_OK);
10737 ssl_options.tls_intolerant =
10738 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10739
10740 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510741 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210742}
10743
davidben5a312152016-06-27 22:11:4710744// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510745TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210746 SpawnedTestServer::SSLOptions ssl_options(
10747 SpawnedTestServer::SSLOptions::CERT_OK);
10748 ssl_options.tls_intolerant =
10749 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10750
10751 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510752 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10753}
10754
davidben095ebb52017-04-12 22:23:3410755// Tests that TLS 1.3 interference results in a dedicated error code.
10756TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10757 SpawnedTestServer::SSLOptions ssl_options(
10758 SpawnedTestServer::SSLOptions::CERT_OK);
10759 ssl_options.tls_intolerant =
10760 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10761 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10762
10763 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10764 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10765}
10766
10767// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10768TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10769 SpawnedTestServer::SSLOptions ssl_options(
10770 SpawnedTestServer::SSLOptions::CERT_OK);
10771 ssl_options.tls_intolerant =
10772 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10773 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10774
10775 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10776 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10777}
10778
Bence Béky98447b12018-05-08 03:14:0110779class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410780 public:
fdorayf33fede2017-05-11 21:18:1010781 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910782 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410783
10784 default_context_.set_network_delegate(&default_network_delegate_);
10785 default_context_.set_cert_verifier(&cert_verifier_);
10786 default_context_.Init();
10787 }
Chris Watkins7a41d3552017-12-01 02:13:2710788 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410789
10790 protected:
10791 MockCertVerifier cert_verifier_;
10792 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10793 TestURLRequestContext default_context_;
10794};
10795
10796// Tests that session resumption is not attempted if an invalid certificate
10797// is presented.
10798TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10799 SpawnedTestServer::SSLOptions ssl_options;
10800 ssl_options.record_resume = true;
10801 SpawnedTestServer test_server(
10802 SpawnedTestServer::TYPE_HTTPS,
10803 ssl_options,
10804 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10805 ASSERT_TRUE(test_server.Start());
10806
10807 SSLClientSocket::ClearSessionCache();
10808
10809 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910810 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410811 {
10812 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610813 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610814 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10815 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410816
[email protected]f7022f32014-08-21 16:32:1910817 r->Start();
10818 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410819
Wez2a31b222018-06-07 22:07:1510820 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410821
10822 EXPECT_EQ(1, d.response_started_count());
10823 }
10824
10825 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10826 CloseAllConnections();
10827
10828 // Now change the certificate to be acceptable (so that the response is
10829 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910830 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410831 {
10832 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610833 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610834 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10835 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410836
[email protected]f7022f32014-08-21 16:32:1910837 r->Start();
10838 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410839
Wez2a31b222018-06-07 22:07:1510840 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410841
10842 // The response will look like;
10843 // insert abc
10844 // insert xyz
10845 //
10846 // With a newline at the end which makes the split think that there are
10847 // three lines.
10848 //
10849 // If a session was presented (eg: a bug), then the response would look
10850 // like;
10851 // insert abc
10852 // lookup abc
10853 // insert xyz
10854
10855 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010856 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410857 }
10858}
10859
[email protected]dffe8242012-03-20 15:14:2710860// This the fingerprint of the "Testing CA" certificate used by the testserver.
10861// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810862static const SHA256HashValue kOCSPTestCertFingerprint = {{
10863 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10864 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10865 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510866}};
[email protected]dffe8242012-03-20 15:14:2710867
[email protected]51523f52013-07-31 21:57:2810868// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10869// testserver.
mattm0b12a6f2016-11-29 19:57:1610870static const SHA256HashValue kOCSPTestCertSPKI = {{
10871 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10872 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10873 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10874}};
[email protected]51523f52013-07-31 21:57:2810875
[email protected]dffe8242012-03-20 15:14:2710876// This is the policy OID contained in the certificates that testserver
10877// generates.
10878static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10879
10880class HTTPSOCSPTest : public HTTPSRequestTest {
10881 public:
10882 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910883 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810884 ev_test_policy_(
10885 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10886 kOCSPTestCertFingerprint,
10887 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210888 }
10889
dcheng67be2b1f2014-10-27 21:47:2910890 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310891 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010892 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910893 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710894
[email protected]cba24642014-08-15 20:49:5910895 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010896 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210897 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010898 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710899
Matt Muellerfb271992018-01-30 18:10:4810900#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510901 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10902#endif
10903
svaldez2135be52016-04-20 16:34:5310904#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910905 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710906#endif
10907 }
10908
dadrian612337a2016-07-20 22:36:5810909 void DoConnectionWithDelegate(
10910 const SpawnedTestServer::SSLOptions& ssl_options,
10911 TestDelegate* delegate,
10912 SSLInfo* out_ssl_info) {
10913 // Always overwrite |out_ssl_info|.
10914 out_ssl_info->Reset();
10915
[email protected]ce7d0cbc2013-05-03 18:57:2210916 SpawnedTestServer test_server(
10917 SpawnedTestServer::TYPE_HTTPS,
10918 ssl_options,
10919 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710920 ASSERT_TRUE(test_server.Start());
10921
dadrian612337a2016-07-20 22:36:5810922 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610923 std::unique_ptr<URLRequest> r(
10924 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10925 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910926 r->Start();
[email protected]dffe8242012-03-20 15:14:2710927
Wez2a31b222018-06-07 22:07:1510928 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810929 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710930
dadrian612337a2016-07-20 22:36:5810931 *out_ssl_info = r->ssl_info();
10932 }
10933
10934 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10935 CertStatus* out_cert_status) {
10936 // Always overwrite |out_cert_status|.
10937 *out_cert_status = 0;
10938
10939 TestDelegate d;
10940 SSLInfo ssl_info;
10941 ASSERT_NO_FATAL_FAILURE(
10942 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10943
10944 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710945 }
10946
dcheng67be2b1f2014-10-27 21:47:2910947 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810948#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510949 ShutdownGlobalCertNetFetcher();
10950#endif
10951
svaldez2135be52016-04-20 16:34:5310952#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810953 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710954#endif
10955 }
10956
[email protected]a13234c2012-03-20 21:45:0210957 protected:
10958 // SetupContext configures the URLRequestContext that will be used for making
10959 // connetions to testserver. This can be overridden in test subclasses for
10960 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010961 virtual void SetupContext() {
Ryan Sleevi5b4702a2018-04-06 22:23:5610962 context_.set_ssl_config_service(
10963 new TestSSLConfigService(true /* online revocation checking */,
10964 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1410965 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5610966 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210967 }
10968
danakj8522a25b2016-04-16 00:17:3610969 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910970 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610971 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710972};
10973
[email protected]a13234c2012-03-20 21:45:0210974static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010975#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210976 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10977 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410978 // TODO(eroman): Should this also be the return value for
10979 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210980 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10981#else
10982 return 0;
10983#endif
10984}
10985
[email protected]3a86a712013-07-30 07:16:2010986// SystemSupportsHardFailRevocationChecking returns true iff the current
10987// operating system supports revocation checking and can distinguish between
10988// situations where a given certificate lacks any revocation information (eg:
10989// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10990// revocation information cannot be obtained (eg: the CRL was unreachable).
10991// If it does not, then tests which rely on 'hard fail' behaviour should be
10992// skipped.
10993static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410994#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10995 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010996 return true;
10997#else
10998 return false;
10999#endif
11000}
11001
[email protected]a13234c2012-03-20 21:45:0211002// SystemUsesChromiumEVMetadata returns true iff the current operating system
11003// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
11004// several tests are effected because our testing EV certificate won't be
11005// recognised as EV.
11006static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5211007#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0111008 return true;
Eric Roman5f8d9d22017-10-17 02:32:5211009#else
11010 return false;
[email protected]05454a432012-03-20 20:04:0111011#endif
11012}
11013
mattmaf868e72016-09-23 23:25:2011014// Returns the expected CertStatus for tests that expect an online revocation
11015// check failure as a result of checking a test EV cert, which will not
11016// actually trigger an online revocation check on some platforms.
11017static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11018 if (SystemUsesChromiumEVMetadata()) {
11019 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11020 } else {
11021 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11022 // be enabled, and thus there will not be a revocation check to fail.
11023 return 0u;
11024 }
11025}
11026
[email protected]b6f2de32012-08-17 04:35:0811027static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911028#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211029 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11030 return false;
11031#else
11032 return true;
11033#endif
11034}
11035
davidbend1fb2f12014-11-08 02:51:0011036static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0411037#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
11038 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0311039 return true;
mathpc992e602015-10-21 20:34:0311040#else
11041 return false;
11042#endif
davidbend1fb2f12014-11-08 02:51:0011043}
11044
[email protected]dffe8242012-03-20 15:14:2711045TEST_F(HTTPSOCSPTest, Valid) {
11046 if (!SystemSupportsOCSP()) {
11047 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11048 return;
11049 }
11050
[email protected]ce7d0cbc2013-05-03 18:57:2211051 SpawnedTestServer::SSLOptions ssl_options(
11052 SpawnedTestServer::SSLOptions::CERT_AUTO);
11053 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711054
[email protected]924e9f92012-12-16 22:00:5311055 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211056 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711057
11058 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11059
[email protected]a13234c2012-03-20 21:45:0211060 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11061 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711062
11063 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11064}
11065
11066TEST_F(HTTPSOCSPTest, Revoked) {
11067 if (!SystemSupportsOCSP()) {
11068 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11069 return;
11070 }
11071
[email protected]ce7d0cbc2013-05-03 18:57:2211072 SpawnedTestServer::SSLOptions ssl_options(
11073 SpawnedTestServer::SSLOptions::CERT_AUTO);
11074 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711075
11076 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211077 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711078
[email protected]dffe8242012-03-20 15:14:2711079 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711080 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11081 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11082}
11083
11084TEST_F(HTTPSOCSPTest, Invalid) {
11085 if (!SystemSupportsOCSP()) {
11086 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11087 return;
11088 }
11089
[email protected]ce7d0cbc2013-05-03 18:57:2211090 SpawnedTestServer::SSLOptions ssl_options(
11091 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811092 ssl_options.ocsp_status =
11093 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711094
[email protected]924e9f92012-12-16 22:00:5311095 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211096 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711097
Eric Roman1b628daa2017-10-19 19:52:0411098#if defined(USE_BUILTIN_CERT_VERIFIER)
11099 // TODO(649017): This test uses soft-fail revocation checking, but returns an
11100 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11101 // doesn't consider this a candidate for soft-fail (only considers
11102 // network-level failures as skippable).
11103 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11104 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11105#else
[email protected]a13234c2012-03-20 21:45:0211106 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2711107 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0411108#endif
[email protected]dffe8242012-03-20 15:14:2711109
11110 // Without a positive OCSP response, we shouldn't show the EV status.
11111 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11112 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11113}
[email protected]a13234c2012-03-20 21:45:0211114
Matt Mueller5339d862018-05-02 18:53:5711115TEST_F(HTTPSOCSPTest, IntermediateValid) {
11116 if (!SystemSupportsOCSP()) {
11117 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11118 return;
11119 }
11120
11121 SpawnedTestServer::SSLOptions ssl_options(
11122 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11123 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11124 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11125
11126 CertStatus cert_status;
11127 DoConnection(ssl_options, &cert_status);
11128
11129 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11130
11131 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11132 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11133
11134 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11135}
11136
11137TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11138 if (!SystemSupportsOCSP()) {
11139 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11140 return;
11141 }
11142
11143 SpawnedTestServer::SSLOptions ssl_options(
11144 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11145 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11146 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11147 // Use an OCSP response for the intermediate that would be too old for a leaf
11148 // cert, but is still valid for an intermediate.
11149 ssl_options.ocsp_intermediate_date =
11150 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11151
11152 CertStatus cert_status;
11153 DoConnection(ssl_options, &cert_status);
11154
11155 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11156
11157 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11158 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11159
11160 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11161}
11162
11163TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11164 if (!SystemSupportsOCSP()) {
11165 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11166 return;
11167 }
11168
11169 SpawnedTestServer::SSLOptions ssl_options(
11170 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11171 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11172 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11173 ssl_options.ocsp_intermediate_date =
11174 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11175
11176 CertStatus cert_status;
11177 DoConnection(ssl_options, &cert_status);
11178
11179#if defined(USE_BUILTIN_CERT_VERIFIER)
11180 // The builtin verifier enforces the baseline requirements for max age of an
11181 // intermediate's OCSP response.
11182 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11183 cert_status & CERT_STATUS_ALL_ERRORS);
11184 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11185#else
11186 // The platform verifiers are more lenient.
11187 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11188 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11189 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11190#endif
11191 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11192}
11193
11194TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11195 if (!SystemSupportsOCSP()) {
11196 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11197 return;
11198 }
11199
11200 SpawnedTestServer::SSLOptions ssl_options(
11201 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11202 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11203 ssl_options.ocsp_intermediate_status =
11204 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11205
11206 CertStatus cert_status;
11207 DoConnection(ssl_options, &cert_status);
11208
11209#if defined(OS_WIN)
11210 // TODO(mattm): why does CertVerifyProcWin accept this?
11211 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11212#else
11213 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11214#endif
11215 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11216 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11217}
11218
davidbend1fb2f12014-11-08 02:51:0011219TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311220 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011221 LOG(WARNING)
11222 << "Skipping test because system doesn't support OCSP stapling";
11223 return;
11224 }
11225
11226 SpawnedTestServer::SSLOptions ssl_options(
11227 SpawnedTestServer::SSLOptions::CERT_AUTO);
11228 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11229 ssl_options.staple_ocsp_response = true;
11230 ssl_options.ocsp_server_unavailable = true;
11231
11232 CertStatus cert_status;
11233 DoConnection(ssl_options, &cert_status);
11234
11235 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11236
11237 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11238 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11239
11240 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11241}
11242
davidben6c3191b2014-11-21 22:38:0411243// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811244#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411245#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11246#else
11247#define MAYBE_RevokedStapled RevokedStapled
11248#endif
11249TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311250 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011251 LOG(WARNING)
11252 << "Skipping test because system doesn't support OCSP stapling";
11253 return;
11254 }
11255
11256 SpawnedTestServer::SSLOptions ssl_options(
11257 SpawnedTestServer::SSLOptions::CERT_AUTO);
11258 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11259 ssl_options.staple_ocsp_response = true;
11260 ssl_options.ocsp_server_unavailable = true;
11261
11262 CertStatus cert_status;
11263 DoConnection(ssl_options, &cert_status);
11264
11265 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11266 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11267 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11268}
11269
dadriand476e652016-07-26 21:33:2411270TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
Martijn Croonenb1383da2017-10-11 11:56:3511271 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
11272
dadriand476e652016-07-26 21:33:2411273 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11274 https_test_server.SetSSLConfig(
11275 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11276 https_test_server.ServeFilesFromSourceDirectory(
11277 base::FilePath(kTestFilePath));
11278 ASSERT_TRUE(https_test_server.Start());
11279
11280 // Set up a MockCertVerifier to accept the certificate that the server sends,
11281 // but not provide any OCSP information.
11282 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11283 ASSERT_TRUE(cert);
11284 MockCertVerifier cert_verifier;
11285 CertVerifyResult verify_result;
11286 verify_result.verified_cert = cert;
11287 verify_result.is_issued_by_known_root = true;
11288 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11289 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11290
11291 // Catch the Expect-Staple report.
11292 TransportSecurityState transport_security_state;
11293 MockCertificateReportSender mock_report_sender;
11294 transport_security_state.SetReportSender(&mock_report_sender);
11295
11296 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11297 // that the request can be sent to a site on the Expect-Staple preload list.
11298 MockHostResolver host_resolver;
11299 TestNetworkDelegate network_delegate;
11300 TestURLRequestContext context(true);
11301 context.set_host_resolver(&host_resolver);
11302 context.set_transport_security_state(&transport_security_state);
11303 context.set_network_delegate(&network_delegate);
11304 context.set_cert_verifier(&cert_verifier);
11305 context.Init();
11306
11307 // Now send a request to trigger the violation.
11308 TestDelegate d;
11309 GURL url = https_test_server.GetURL("/");
11310 GURL::Replacements replace_host;
11311 replace_host.SetHostStr(kExpectStapleStaticHostname);
11312 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611313 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11314 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411315 violating_request->Start();
Wez2a31b222018-06-07 22:07:1511316 d.RunUntilComplete();
dadriand476e652016-07-26 21:33:2411317
11318 // Confirm a report was sent.
11319 EXPECT_FALSE(mock_report_sender.latest_report().empty());
11320 EXPECT_EQ(GURL(kExpectStapleReportURI),
11321 mock_report_sender.latest_report_uri());
11322}
11323
estark13e0b312016-12-22 23:52:3211324// Tests that Expect-Staple reports are not sent for connections on which there
11325// is a certificate error.
11326TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
11327 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11328 https_test_server.SetSSLConfig(
11329 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11330 https_test_server.ServeFilesFromSourceDirectory(
11331 base::FilePath(kTestFilePath));
11332 ASSERT_TRUE(https_test_server.Start());
11333
11334 // Set up a MockCertVerifier to report an error for the certificate
11335 // and indicate that there was no stapled OCSP response.
11336 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11337 ASSERT_TRUE(cert);
11338 MockCertVerifier cert_verifier;
11339 CertVerifyResult verify_result;
11340 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
11341 verify_result.verified_cert = cert;
11342 verify_result.is_issued_by_known_root = true;
11343 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11344 cert_verifier.AddResultForCert(cert.get(), verify_result,
11345 ERR_CERT_DATE_INVALID);
11346
11347 // Set up a mock report sender so that the test can check that an
11348 // Expect-Staple report is not sent.
11349 TransportSecurityState transport_security_state;
11350 MockCertificateReportSender mock_report_sender;
11351 transport_security_state.SetReportSender(&mock_report_sender);
11352
11353 TestNetworkDelegate network_delegate;
11354 TestURLRequestContext context(true);
11355
11356 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11357 MockHostResolver host_resolver;
11358 context.set_host_resolver(&host_resolver);
11359
11360 context.set_transport_security_state(&transport_security_state);
11361 context.set_network_delegate(&network_delegate);
11362 context.set_cert_verifier(&cert_verifier);
11363 context.Init();
11364
11365 // Make a connection to |kExpectStapleStaticHostname|. Because the
11366 // |verify_result| used with the |cert_verifier| will indicate a certificate
11367 // error, an Expect-Staple report should not be sent.
11368 TestDelegate d;
11369 GURL url = https_test_server.GetURL("/");
11370 GURL::Replacements replace_host;
11371 replace_host.SetHostStr(kExpectStapleStaticHostname);
11372 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611373 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11374 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211375 violating_request->Start();
Wez2a31b222018-06-07 22:07:1511376 d.RunUntilComplete();
estark13e0b312016-12-22 23:52:3211377
11378 // Confirm a report was not sent.
11379 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11380 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11381}
11382
dadriand476e652016-07-26 21:33:2411383TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
11384 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11385 https_test_server.SetSSLConfig(
11386 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11387 https_test_server.ServeFilesFromSourceDirectory(
11388 base::FilePath(kTestFilePath));
11389 ASSERT_TRUE(https_test_server.Start());
11390
11391 // Set up a MockCertVerifier to accept the certificate that the server sends,
11392 // and provide GOOD revocation status.
11393 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11394 ASSERT_TRUE(cert);
11395 MockCertVerifier cert_verifier;
11396 CertVerifyResult verify_result;
11397 verify_result.verified_cert = cert;
11398 verify_result.is_issued_by_known_root = true;
11399 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
11400 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
11401 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11402
11403 // Catch the Expect-Staple report.
11404 TransportSecurityState transport_security_state;
11405 MockCertificateReportSender mock_report_sender;
11406 transport_security_state.SetReportSender(&mock_report_sender);
11407
11408 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11409 // that the request can be sent to a site on the Expect-Staple preload list.
11410 MockHostResolver host_resolver;
11411 TestNetworkDelegate network_delegate;
11412 TestURLRequestContext context(true);
11413 context.set_host_resolver(&host_resolver);
11414 context.set_transport_security_state(&transport_security_state);
11415 context.set_network_delegate(&network_delegate);
11416 context.set_cert_verifier(&cert_verifier);
11417 context.Init();
11418
11419 // This request should not not trigger an Expect-Staple violation.
11420 TestDelegate d;
11421 GURL url = https_test_server.GetURL("/");
11422 GURL::Replacements replace_host;
11423 replace_host.SetHostStr(kExpectStapleStaticHostname);
11424 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611425 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11426 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411427 ok_request->Start();
Wez2a31b222018-06-07 22:07:1511428 d.RunUntilComplete();
dadriand476e652016-07-26 21:33:2411429
11430 // Check that no report was sent.
11431 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11432 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11433}
11434
estark13e0b312016-12-22 23:52:3211435// Tests that an Expect-Staple report is not sent when OCSP details are not
11436// checked on the connection.
11437TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
11438 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11439 https_test_server.SetSSLConfig(
11440 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11441 https_test_server.ServeFilesFromSourceDirectory(
11442 base::FilePath(kTestFilePath));
11443 ASSERT_TRUE(https_test_server.Start());
11444
11445 // Set up a MockCertVerifier to accept the certificate that the server sends,
11446 // and set |ocsp_result| to indicate that OCSP stapling details were not
11447 // checked on the connection.
11448 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11449 ASSERT_TRUE(cert);
11450 MockCertVerifier cert_verifier;
11451 CertVerifyResult verify_result;
11452 verify_result.verified_cert = cert;
11453 verify_result.is_issued_by_known_root = true;
11454 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
11455 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11456
11457 // Set up a mock report sender so that the test can check that an
11458 // Expect-Staple report is not sent.
11459 TransportSecurityState transport_security_state;
11460 MockCertificateReportSender mock_report_sender;
11461 transport_security_state.SetReportSender(&mock_report_sender);
11462
11463 TestNetworkDelegate network_delegate;
11464 TestURLRequestContext context(true);
11465
11466 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11467 MockHostResolver host_resolver;
11468 context.set_host_resolver(&host_resolver);
11469
11470 context.set_transport_security_state(&transport_security_state);
11471 context.set_network_delegate(&network_delegate);
11472 context.set_cert_verifier(&cert_verifier);
11473 context.Init();
11474
11475 // Make a connection to |kExpectStapleStaticHostname|. Because the
11476 // |verify_result| used with the |cert_verifier| will indicate that OCSP
11477 // stapling details were not checked on the connection, an Expect-Staple
11478 // report should not be sent.
11479 TestDelegate d;
11480 GURL url = https_test_server.GetURL("/");
11481 GURL::Replacements replace_host;
11482 replace_host.SetHostStr(kExpectStapleStaticHostname);
11483 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611484 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11485 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211486 ok_request->Start();
Wez2a31b222018-06-07 22:07:1511487 d.RunUntilComplete();
estark13e0b312016-12-22 23:52:3211488
11489 // Check that no report was sent.
11490 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11491 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11492}
11493
dadrian612337a2016-07-20 22:36:5811494static const struct OCSPVerifyTestData {
11495 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11496 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11497 OCSPVerifyResult::ResponseStatus response_status;
11498 bool has_revocation_status;
11499 OCSPRevocationStatus cert_status;
11500} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111501 // 0
dadrian612337a2016-07-20 22:36:5811502 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11503 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11504 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11505 OCSPVerifyResult::PROVIDED,
11506 true,
11507 OCSPRevocationStatus::GOOD},
11508
Eric Roman8673b812017-09-20 18:57:3111509 // 1
dadrian612337a2016-07-20 22:36:5811510 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11511 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11512 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11513 OCSPVerifyResult::INVALID_DATE,
11514 false,
11515 OCSPRevocationStatus::UNKNOWN},
11516
Eric Roman8673b812017-09-20 18:57:3111517 // 2
dadrian612337a2016-07-20 22:36:5811518 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11519 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11520 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11521 OCSPVerifyResult::INVALID_DATE,
11522 false,
11523 OCSPRevocationStatus::UNKNOWN},
11524
Eric Roman8673b812017-09-20 18:57:3111525 // 3
dadrian612337a2016-07-20 22:36:5811526 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11527 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11528 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11529 OCSPVerifyResult::INVALID_DATE,
11530 false,
11531 OCSPRevocationStatus::UNKNOWN},
11532
Eric Roman8673b812017-09-20 18:57:3111533 // 4
dadrian612337a2016-07-20 22:36:5811534 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11535 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11536 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11537 OCSPVerifyResult::INVALID_DATE,
11538 false,
11539 OCSPRevocationStatus::UNKNOWN},
11540
Eric Roman8673b812017-09-20 18:57:3111541 // 5
dadrian612337a2016-07-20 22:36:5811542 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11543 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11544 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11545 OCSPVerifyResult::ERROR_RESPONSE,
11546 false,
11547 OCSPRevocationStatus::UNKNOWN},
11548
Eric Roman8673b812017-09-20 18:57:3111549 // 6
dadrian612337a2016-07-20 22:36:5811550 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11551 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11552 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11553 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11554 false,
11555 OCSPRevocationStatus::UNKNOWN},
11556
Eric Roman8673b812017-09-20 18:57:3111557 // 7
dadrian612337a2016-07-20 22:36:5811558 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11559 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11560 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11561 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11562 false,
11563 OCSPRevocationStatus::UNKNOWN},
11564
Eric Roman8673b812017-09-20 18:57:3111565 // 8
dadrian612337a2016-07-20 22:36:5811566 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11567 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11568 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11569 OCSPVerifyResult::INVALID_DATE,
11570 false,
11571 OCSPRevocationStatus::UNKNOWN},
11572
Eric Roman8673b812017-09-20 18:57:3111573 // 9
dadrian612337a2016-07-20 22:36:5811574 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11575 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11576 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11577 OCSPVerifyResult::PROVIDED,
11578 true,
11579 OCSPRevocationStatus::UNKNOWN},
11580
Eric Roman8673b812017-09-20 18:57:3111581 // 10
dadrian612337a2016-07-20 22:36:5811582 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11583 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11584 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11585 OCSPVerifyResult::INVALID_DATE,
11586 false,
11587 OCSPRevocationStatus::UNKNOWN},
11588
Eric Roman8673b812017-09-20 18:57:3111589 // 11
dadrian612337a2016-07-20 22:36:5811590 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11591 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11592 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11593 OCSPVerifyResult::INVALID_DATE,
11594 false,
11595 OCSPRevocationStatus::UNKNOWN},
11596
Eric Roman8673b812017-09-20 18:57:3111597 // 12
dadrian612337a2016-07-20 22:36:5811598 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11599 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11600 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11601 OCSPVerifyResult::BAD_PRODUCED_AT,
11602 false,
11603 OCSPRevocationStatus::UNKNOWN},
11604
Eric Roman8673b812017-09-20 18:57:3111605 // 13
dadrian612337a2016-07-20 22:36:5811606 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11607 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11608 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11609 OCSPVerifyResult::BAD_PRODUCED_AT,
11610 false,
11611 OCSPRevocationStatus::UNKNOWN},
11612
Eric Roman8673b812017-09-20 18:57:3111613 // 14
dadrian612337a2016-07-20 22:36:5811614 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11615 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11616 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11617 OCSPVerifyResult::BAD_PRODUCED_AT,
11618 false,
11619 OCSPRevocationStatus::UNKNOWN},
11620
Eric Roman8673b812017-09-20 18:57:3111621 // 15
dadrian612337a2016-07-20 22:36:5811622 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11623 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11624 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11625 OCSPVerifyResult::PROVIDED,
11626 true,
11627 OCSPRevocationStatus::GOOD},
11628
Eric Roman8673b812017-09-20 18:57:3111629 // 16
dadrian612337a2016-07-20 22:36:5811630 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11631 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11632 {SpawnedTestServer::SSLOptions::OCSP_OK,
11633 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11634 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11635 OCSPVerifyResult::PROVIDED,
11636 true,
11637 OCSPRevocationStatus::GOOD},
11638
Eric Roman8673b812017-09-20 18:57:3111639 // 17
dadrian612337a2016-07-20 22:36:5811640 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11641 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11642 {SpawnedTestServer::SSLOptions::OCSP_OK,
11643 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11644 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11645 OCSPVerifyResult::PROVIDED,
11646 true,
11647 OCSPRevocationStatus::GOOD},
11648
Eric Roman8673b812017-09-20 18:57:3111649 // 18
dadrian612337a2016-07-20 22:36:5811650 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11651 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11652 {SpawnedTestServer::SSLOptions::OCSP_OK,
11653 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11654 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11655 OCSPVerifyResult::PROVIDED,
11656 true,
11657 OCSPRevocationStatus::GOOD},
11658
Eric Roman8673b812017-09-20 18:57:3111659 // 19
dadrian612337a2016-07-20 22:36:5811660 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11661 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11662 {SpawnedTestServer::SSLOptions::OCSP_OK,
11663 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11664 {SpawnedTestServer::SSLOptions::OCSP_OK,
11665 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11666 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11667 OCSPVerifyResult::INVALID_DATE,
11668 false,
11669 OCSPRevocationStatus::UNKNOWN},
11670
Eric Roman8673b812017-09-20 18:57:3111671 // 20
dadrian612337a2016-07-20 22:36:5811672 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11673 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11674 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11675 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11676 {SpawnedTestServer::SSLOptions::OCSP_OK,
11677 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11678 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11679 OCSPVerifyResult::PROVIDED,
11680 true,
11681 OCSPRevocationStatus::REVOKED},
11682
Eric Roman8673b812017-09-20 18:57:3111683 // 21
dadrian612337a2016-07-20 22:36:5811684 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11685 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11686 {SpawnedTestServer::SSLOptions::OCSP_OK,
11687 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11688 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11689 OCSPVerifyResult::PROVIDED,
11690 true,
11691 OCSPRevocationStatus::UNKNOWN},
11692
Eric Roman8673b812017-09-20 18:57:3111693 // 22
dadrian612337a2016-07-20 22:36:5811694 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11695 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11696 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11697 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11698 {SpawnedTestServer::SSLOptions::OCSP_OK,
11699 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11700 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11701 OCSPVerifyResult::PROVIDED,
11702 true,
11703 OCSPRevocationStatus::UNKNOWN},
11704
Eric Roman8673b812017-09-20 18:57:3111705 // 23
dadrian612337a2016-07-20 22:36:5811706 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11707 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11708 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11709 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11710 false,
11711 OCSPRevocationStatus::UNKNOWN},
11712
Eric Roman8673b812017-09-20 18:57:3111713 // 24
dadrian612337a2016-07-20 22:36:5811714 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11715 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11716 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11717 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11718 false,
11719 OCSPRevocationStatus::UNKNOWN},
11720
Eric Roman8673b812017-09-20 18:57:3111721// These tests fail when using NSS for certificate verification, as NSS fails
11722// and doesn't return the partial path. As a result the OCSP checks being done
11723// at the CertVerifyProc layer cannot access the issuer certificate.
11724#if !defined(USE_NSS_CERTS)
11725 // 25
11726 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11727 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11728 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11729 OCSPVerifyResult::PROVIDED,
11730 true,
11731 OCSPRevocationStatus::REVOKED},
11732
11733 // 26
11734 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11735 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11736 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11737 OCSPVerifyResult::INVALID_DATE,
11738 false,
11739 OCSPRevocationStatus::UNKNOWN},
11740
11741 // 27
11742 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11743 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11744 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11745 OCSPVerifyResult::INVALID_DATE,
11746 false,
11747 OCSPRevocationStatus::UNKNOWN},
11748#endif
dadrian612337a2016-07-20 22:36:5811749};
11750
11751class HTTPSOCSPVerifyTest
11752 : public HTTPSOCSPTest,
11753 public testing::WithParamInterface<OCSPVerifyTestData> {};
11754
11755TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11756 SpawnedTestServer::SSLOptions ssl_options(
11757 SpawnedTestServer::SSLOptions::CERT_AUTO);
11758 OCSPVerifyTestData test = GetParam();
11759
11760 ssl_options.ocsp_responses = test.ocsp_responses;
11761 ssl_options.ocsp_produced = test.ocsp_produced;
11762 ssl_options.staple_ocsp_response = true;
11763
11764 SSLInfo ssl_info;
11765 OCSPErrorTestDelegate delegate;
11766 ASSERT_NO_FATAL_FAILURE(
11767 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11768
11769 // The SSLInfo must be extracted from |delegate| on error, due to how
11770 // URLRequest caches certificate errors.
11771 if (delegate.have_certificate_errors()) {
11772 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11773 ssl_info = delegate.ssl_info();
11774 }
11775
11776 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11777
11778 if (test.has_revocation_status)
11779 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11780}
11781
11782INSTANTIATE_TEST_CASE_P(OCSPVerify,
11783 HTTPSOCSPVerifyTest,
11784 testing::ValuesIn(kOCSPVerifyData));
11785
mattm0b12a6f2016-11-29 19:57:1611786class HTTPSAIATest : public HTTPSOCSPTest {
11787 public:
11788 void SetupContext() override {
11789 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611790 false /* online revocation checking */,
mattm0b12a6f2016-11-29 19:57:1611791 false /* require rev. checking for local anchors */,
11792 false /* token binding enabled */));
11793 }
11794};
11795
11796TEST_F(HTTPSAIATest, AIAFetching) {
11797 SpawnedTestServer::SSLOptions ssl_options(
11798 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11799 SpawnedTestServer test_server(
11800 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11801 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11802 ASSERT_TRUE(test_server.Start());
11803
Ryan Sleevi5b4702a2018-04-06 22:23:5611804 // Unmark the certificate's OID as EV, which will disable revocation
11805 // checking.
11806 ev_test_policy_.reset();
11807
mattm0b12a6f2016-11-29 19:57:1611808 TestDelegate d;
11809 d.set_allow_certificate_errors(true);
11810 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611811 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11812 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611813
11814 r->Start();
11815 EXPECT_TRUE(r->is_pending());
11816
Wez2a31b222018-06-07 22:07:1511817 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611818
11819 EXPECT_EQ(1, d.response_started_count());
11820
11821 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811822 EXPECT_EQ(OK, d.request_status());
11823 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11824 ASSERT_TRUE(r->ssl_info().cert);
11825 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611826 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411827 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611828}
11829
[email protected]3a86a712013-07-30 07:16:2011830class HTTPSHardFailTest : public HTTPSOCSPTest {
11831 protected:
rsleevid6de8302016-06-21 01:33:2011832 void SetupContext() override {
11833 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611834 false /* online revocation checking */,
11835 true /* require rev. checking for local anchors */,
nharperb7441ef2016-01-25 23:54:1411836 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011837 }
11838};
11839
[email protected]3a86a712013-07-30 07:16:2011840TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11841 if (!SystemSupportsOCSP()) {
11842 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11843 return;
11844 }
11845
11846 if (!SystemSupportsHardFailRevocationChecking()) {
11847 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11848 << "revocation checking";
11849 return;
11850 }
11851
11852 SpawnedTestServer::SSLOptions ssl_options(
11853 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811854 ssl_options.ocsp_status =
11855 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011856
11857 CertStatus cert_status;
11858 DoConnection(ssl_options, &cert_status);
11859
Eric Roman1b628daa2017-10-19 19:52:0411860#if defined(USE_BUILTIN_CERT_VERIFIER)
11861 // TODO(crbug.com/649017): Should we consider invalid response as
11862 // affirmatively revoked?
11863 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11864 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11865#else
11866 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11867#endif
[email protected]3a86a712013-07-30 07:16:2011868
11869 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411870 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011871 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11872}
11873
[email protected]a13234c2012-03-20 21:45:0211874class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11875 protected:
rsleevid6de8302016-06-21 01:33:2011876 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611877 context_.set_ssl_config_service(
11878 new TestSSLConfigService(false /* online revocation checking */,
11879 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411880 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611881 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211882 }
11883};
11884
Eric Romane2243cc62017-10-17 03:59:1311885// Helper class to set the global CRLSet, and on destruction restore the
11886// previously set one.
11887class ScopedSetCRLSet {
11888 public:
11889 ScopedSetCRLSet(scoped_refptr<CRLSet> crl_set) {
11890 prev_crl_set_ = SSLConfigService::GetCRLSet();
11891 SSLConfigService::SetCRLSetForTesting(std::move(crl_set));
11892 }
11893
11894 ~ScopedSetCRLSet() {
11895 SSLConfigService::SetCRLSetForTesting(std::move(prev_crl_set_));
11896 }
11897
11898 private:
11899 scoped_refptr<CRLSet> prev_crl_set_;
11900};
11901
[email protected]a13234c2012-03-20 21:45:0211902TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11903 if (!SystemSupportsOCSP()) {
11904 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11905 return;
11906 }
11907
[email protected]ce7d0cbc2013-05-03 18:57:2211908 SpawnedTestServer::SSLOptions ssl_options(
11909 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811910 ssl_options.ocsp_status =
11911 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311912 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211913
[email protected]924e9f92012-12-16 22:00:5311914 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211915 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211916
mattmaf868e72016-09-23 23:25:2011917 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211918 cert_status & CERT_STATUS_ALL_ERRORS);
11919
11920 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811921 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11922 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211923}
11924
[email protected]be0fff62013-08-29 23:37:4811925TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11926 if (!SystemSupportsOCSP()) {
11927 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11928 return;
11929 }
11930
11931 SpawnedTestServer::SSLOptions ssl_options(
11932 SpawnedTestServer::SSLOptions::CERT_AUTO);
11933 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Eric Romane2243cc62017-10-17 03:59:1311934 ScopedSetCRLSet set_crlset(nullptr);
[email protected]be0fff62013-08-29 23:37:4811935
11936 CertStatus cert_status;
11937 DoConnection(ssl_options, &cert_status);
11938
mattm1a282f52016-11-10 21:49:4211939// Currently only works for Windows and OS X. When using NSS, it's not
11940// possible to determine whether the check failed because of actual
11941// revocation or because there was an OCSP failure.
11942#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811943 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11944#else
11945 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11946#endif
11947
11948 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11949 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11950 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11951}
11952
[email protected]a13234c2012-03-20 21:45:0211953TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11954 if (!SystemSupportsOCSP()) {
11955 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11956 return;
11957 }
11958
[email protected]ce7d0cbc2013-05-03 18:57:2211959 SpawnedTestServer::SSLOptions ssl_options(
11960 SpawnedTestServer::SSLOptions::CERT_AUTO);
11961 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
Eric Romane2243cc62017-10-17 03:59:1311962 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211963
11964 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211965 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211966
11967 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11968
11969 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11970 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811971 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11972 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211973}
11974
11975TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11976 if (!SystemSupportsOCSP()) {
11977 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11978 return;
11979 }
11980
[email protected]ce7d0cbc2013-05-03 18:57:2211981 SpawnedTestServer::SSLOptions ssl_options(
11982 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811983 ssl_options.ocsp_status =
11984 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311985 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211986
11987 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211988 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211989
mattmaf868e72016-09-23 23:25:2011990 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211991 cert_status & CERT_STATUS_ALL_ERRORS);
11992
11993 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811994 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11995 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211996}
11997
[email protected]51523f52013-07-31 21:57:2811998TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11999 if (!SystemSupportsOCSP()) {
12000 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12001 return;
12002 }
12003
12004 SpawnedTestServer::SSLOptions ssl_options(
12005 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812006 ssl_options.ocsp_status =
12007 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Adam Langleyea6d6782017-12-05 23:57:3312008 ScopedSetCRLSet set_crlset(
12009 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {}));
[email protected]51523f52013-07-31 21:57:2812010
12011 CertStatus cert_status;
12012 DoConnection(ssl_options, &cert_status);
12013
12014 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
12015 // revocation check for EV.
12016 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12017 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12018 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
12019 EXPECT_FALSE(
12020 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12021}
12022
12023TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
12024 if (!SystemSupportsOCSP()) {
12025 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12026 return;
12027 }
12028
[email protected]ce7d0cbc2013-05-03 18:57:2212029 SpawnedTestServer::SSLOptions ssl_options(
12030 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812031 ssl_options.ocsp_status =
12032 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1312033 ScopedSetCRLSet set_crlset(CRLSet::EmptyCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0212034
[email protected]51523f52013-07-31 21:57:2812035 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1212036 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212037
[email protected]51523f52013-07-31 21:57:2812038 // Even with a fresh CRLSet, we should still do online revocation checks when
12039 // the certificate chain isn't covered by the CRLSet, which it isn't in this
12040 // test.
mattmaf868e72016-09-23 23:25:2012041 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2812042 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0212043
[email protected]51523f52013-07-31 21:57:2812044 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0212045 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2812046 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212047}
12048
12049class HTTPSCRLSetTest : public HTTPSOCSPTest {
12050 protected:
rsleevid6de8302016-06-21 01:33:2012051 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5612052 context_.set_ssl_config_service(
12053 new TestSSLConfigService(false /* online revocation checking */,
12054 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1412055 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5612056 false /* token binding enabled */));
12057 }
12058
12059 void SetUp() override {
12060 HTTPSOCSPTest::SetUp();
12061
12062 // Unmark the certificate's OID as EV, which should disable revocation
12063 // checking (as per the user preference).
12064 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0212065 }
12066};
12067
12068TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2212069 SpawnedTestServer::SSLOptions ssl_options(
12070 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812071 ssl_options.ocsp_status =
12072 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1312073 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0212074
[email protected]924e9f92012-12-16 22:00:5312075 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212076 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212077
12078 // If we're not trying EV verification then, even if the CRLSet has expired,
12079 // we don't fall back to online revocation checks.
12080 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12081 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12082 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12083}
[email protected]51523f52013-07-31 21:57:2812084
Ryan Sleevi5b4702a2018-04-06 22:23:5612085TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
12086 // Test that when online revocation checking is disabled, and the leaf
12087 // certificate is not EV, that no revocation checking actually happens.
12088 if (!SystemSupportsOCSP()) {
12089 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12090 return;
12091 }
12092
12093 SpawnedTestServer::SSLOptions ssl_options(
12094 SpawnedTestServer::SSLOptions::CERT_AUTO);
12095 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
12096 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
12097
12098 CertStatus cert_status;
12099 DoConnection(ssl_options, &cert_status);
12100
12101 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12102
12103 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12104 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12105}
12106
[email protected]51523f52013-07-31 21:57:2812107TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512108#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812109 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12110 return;
12111#endif
12112
12113 SpawnedTestServer::SSLOptions ssl_options(
12114 SpawnedTestServer::SSLOptions::CERT_AUTO);
12115 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12116 ssl_options.cert_serial = 10;
Eric Romane2243cc62017-10-17 03:59:1312117 ScopedSetCRLSet set_crlset(
Adam Langleyea6d6782017-12-05 23:57:3312118 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {}));
[email protected]51523f52013-07-31 21:57:2812119
12120 CertStatus cert_status = 0;
12121 DoConnection(ssl_options, &cert_status);
12122
12123 // If the certificate is recorded as revoked in the CRLSet, that should be
12124 // reflected without online revocation checking.
12125 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12126 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612127 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812128}
Adam Langleyea6d6782017-12-05 23:57:3312129
12130TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12131#if defined(OS_ANDROID)
12132 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12133 return;
12134#endif
12135
12136 SpawnedTestServer::SSLOptions ssl_options(
12137 SpawnedTestServer::SSLOptions::CERT_AUTO);
12138 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12139 static const char kCommonName[] = "Test CN";
12140 ssl_options.cert_common_name = kCommonName;
12141
12142 {
12143 ScopedSetCRLSet set_crlset(
12144 CRLSet::ForTesting(false, nullptr, "", kCommonName, {}));
12145
12146 CertStatus cert_status = 0;
12147 DoConnection(ssl_options, &cert_status);
12148
12149 // If the certificate is recorded as revoked in the CRLSet, that should be
12150 // reflected without online revocation checking.
12151 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12152 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612153 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312154 }
12155
12156 const uint8_t kTestServerSPKISHA256[32] = {
12157 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12158 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12159 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12160 };
12161 const std::string spki_hash(
12162 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12163 sizeof(kTestServerSPKISHA256));
12164
12165 {
12166 ScopedSetCRLSet set_crlset(
12167 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash}));
12168
12169 CertStatus cert_status = 0;
12170 DoConnection(ssl_options, &cert_status);
12171
12172 // When the correct SPKI hash is specified, the connection should succeed
12173 // even though the subject is listed in the CRLSet.
12174 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12175 }
12176}
[email protected]316c1e5e2012-09-12 15:17:4412177#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712178
Sergey Ulanovc4580e72017-09-13 23:30:1112179#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12180 !defined(OS_FUCHSIA)
12181// FTP uses a second TCP connection with the port number allocated dynamically
12182// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12183// connections reliably. FTP tests are disabled on platforms that use
12184// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112185class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112186 public:
[email protected]d9fca99a2012-02-24 16:16:2012187 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512188 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512189 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712190 // Can't use |default_context_|'s HostResolver to set up the
12191 // FTPTransactionFactory because it hasn't been created yet.
12192 default_context_.set_host_resolver(&host_resolver_);
12193 }
12194
12195 // URLRequestTest interface:
12196 void SetUpFactory() override {
12197 // Add FTP support to the default URLRequestContext.
12198 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0512199 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4712200 }
12201
12202 std::string GetTestFileContents() {
12203 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912204 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712205 path = path.Append(kTestFilePath);
12206 path = path.AppendASCII(kFtpTestFile);
12207 std::string contents;
12208 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12209 return contents;
[email protected]95409e12010-08-17 20:07:1112210 }
12211
[email protected]b89ca032009-08-31 21:41:3112212 protected:
mmenkecd4c7532016-10-19 18:36:0512213 // Note that this is destroyed before the FtpProtocolHandler that references
12214 // it, which is owned by the parent class. Since no requests are made during
12215 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4712216 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4712217
tommycli59a63432015-11-06 00:10:5512218 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112219};
12220
[email protected]d2a133182012-08-05 16:44:0812221// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912222TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812223 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812224
12225 TestDelegate d;
12226 {
rhalavatib7bd7c792017-04-27 05:25:1612227 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12228 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912229 r->Start();
12230 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812231
Wez2a31b222018-06-07 22:07:1512232 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812233
[email protected]f7022f32014-08-21 16:32:1912234 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012235 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812236 }
12237}
12238
mmenke9f2ec60c2015-06-01 20:59:4712239TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512240 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112241
[email protected]a25e90e2009-09-09 17:05:3712242 TestDelegate d;
12243 {
danakj8522a25b2016-04-16 00:17:3612244 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612245 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12246 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912247 r->Start();
12248 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712249
Wez2a31b222018-06-07 22:07:1512250 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712251
[email protected]f7022f32014-08-21 16:32:1912252 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712253 EXPECT_EQ(1, d.response_started_count());
12254 EXPECT_FALSE(d.received_data_before_response());
12255 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512256 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912257 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512258 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912259 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3712260 }
12261}
12262
mmenke9f2ec60c2015-06-01 20:59:4712263TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512264 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112265
[email protected]dd265012009-01-08 20:45:2712266 TestDelegate d;
12267 {
danakj8522a25b2016-04-16 00:17:3612268 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612269 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12270 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912271 r->Start();
12272 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712273
Wez2a31b222018-06-07 22:07:1512274 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712275
[email protected]f7022f32014-08-21 16:32:1912276 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712277 EXPECT_EQ(1, d.response_started_count());
12278 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712279 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512280 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912281 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512282 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912283 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2712284 }
12285}
12286
mmenke9f2ec60c2015-06-01 20:59:4712287TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512288 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112289
[email protected]dd265012009-01-08 20:45:2712290 TestDelegate d;
12291 {
danakj8522a25b2016-04-16 00:17:3612292 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512293 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12294 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612295 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912296 r->Start();
12297 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712298
Wez2a31b222018-06-07 22:07:1512299 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712300
[email protected]f7022f32014-08-21 16:32:1912301 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712302 EXPECT_EQ(1, d.response_started_count());
12303 EXPECT_FALSE(d.received_data_before_response());
12304 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512305 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912306 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512307 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912308 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2512309
12310 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912311 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512312 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712313 }
12314}
12315
mmenke9f2ec60c2015-06-01 20:59:4712316TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512317 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112318
[email protected]dd265012009-01-08 20:45:2712319 TestDelegate d;
12320 {
danakj8522a25b2016-04-16 00:17:3612321 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512322 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12323 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612324 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912325 r->Start();
12326 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712327
Wez2a31b222018-06-07 22:07:1512328 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712329
[email protected]f7022f32014-08-21 16:32:1912330 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712331 EXPECT_EQ(1, d.response_started_count());
12332 EXPECT_FALSE(d.received_data_before_response());
12333 EXPECT_EQ(d.bytes_received(), 0);
12334 }
12335}
12336
mmenke9f2ec60c2015-06-01 20:59:4712337TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512338 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112339
[email protected]8b8a197d2009-08-26 15:57:5812340 TestDelegate d;
12341 // Set correct login credentials. The delegate will be asked for them when
12342 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812343 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812344 {
danakj8522a25b2016-04-16 00:17:3612345 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512346 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12347 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612348 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912349 r->Start();
12350 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812351
Wez2a31b222018-06-07 22:07:1512352 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812353
[email protected]f7022f32014-08-21 16:32:1912354 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812355 EXPECT_EQ(1, d.response_started_count());
12356 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712357 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812358 }
12359}
12360
mmenke9f2ec60c2015-06-01 20:59:4712361TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512362 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112363
[email protected]dd265012009-01-08 20:45:2712364 TestDelegate d;
12365 {
danakj8522a25b2016-04-16 00:17:3612366 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512367 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12368 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612369 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912370 r->Start();
12371 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712372
Wez2a31b222018-06-07 22:07:1512373 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712374
[email protected]f7022f32014-08-21 16:32:1912375 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712376 EXPECT_EQ(1, d.response_started_count());
12377 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712378 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712379 }
12380}
[email protected]8b8a197d2009-08-26 15:57:5812381
mmenke9f2ec60c2015-06-01 20:59:4712382TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512383 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112384
[email protected]8b8a197d2009-08-26 15:57:5812385 TestDelegate d;
12386 // Set correct login credentials. The delegate will be asked for them when
12387 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812388 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812389 {
danakj8522a25b2016-04-16 00:17:3612390 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512391 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12392 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612393 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912394 r->Start();
12395 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812396
Wez2a31b222018-06-07 22:07:1512397 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812398
[email protected]f7022f32014-08-21 16:32:1912399 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812400 EXPECT_EQ(1, d.response_started_count());
12401 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712402 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812403 }
12404}
[email protected]60a3df52009-09-22 16:13:2412405
mmenke9f2ec60c2015-06-01 20:59:4712406TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512407 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112408
danakj8522a25b2016-04-16 00:17:3612409 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412410 {
12411 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3612412 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512413 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12414 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612415 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912416 r->Start();
12417 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412418
Wez2a31b222018-06-07 22:07:1512419 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412420
[email protected]f7022f32014-08-21 16:32:1912421 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412422 EXPECT_EQ(1, d->response_started_count());
12423 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712424 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412425 }
12426
12427 d.reset(new TestDelegate);
12428 {
12429 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3612430 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612431 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12432 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912433 r->Start();
12434 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412435
Wez2a31b222018-06-07 22:07:1512436 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412437
[email protected]f7022f32014-08-21 16:32:1912438 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412439 EXPECT_EQ(1, d->response_started_count());
12440 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712441 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412442 }
12443}
12444
mmenke9f2ec60c2015-06-01 20:59:4712445TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512446 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112447
danakj8522a25b2016-04-16 00:17:3612448 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412449 // Set correct login credentials. The delegate will be asked for them when
12450 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812451 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412452 {
danakj8522a25b2016-04-16 00:17:3612453 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512454 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12455 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612456 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912457 r->Start();
12458 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412459
Wez2a31b222018-06-07 22:07:1512460 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412461
[email protected]f7022f32014-08-21 16:32:1912462 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412463 EXPECT_EQ(1, d->response_started_count());
12464 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712465 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412466 }
12467
12468 // Use a new delegate without explicit credentials. The cached ones should be
12469 // used.
12470 d.reset(new TestDelegate);
12471 {
12472 // Don't pass wrong credentials in the URL, they would override valid cached
12473 // ones.
danakj8522a25b2016-04-16 00:17:3612474 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612475 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12476 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912477 r->Start();
12478 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412479
Wez2a31b222018-06-07 22:07:1512480 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412481
[email protected]f7022f32014-08-21 16:32:1912482 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412483 EXPECT_EQ(1, d->response_started_count());
12484 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712485 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412486 }
12487}
ricea3a1c71f2016-06-17 10:05:2612488
12489TEST_F(URLRequestTestFTP, RawBodyBytes) {
12490 ASSERT_TRUE(ftp_test_server_.Start());
12491
12492 TestDelegate d;
12493 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612494 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12495 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612496 req->Start();
Wez2a31b222018-06-07 22:07:1512497 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612498
12499 EXPECT_EQ(6, req->GetRawBodyBytes());
12500}
12501
brettwa1228ebb2016-10-28 03:51:3412502#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112503
ttuttlec0c828492015-05-15 01:25:5512504TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12505 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612506 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12507 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512508
12509 EXPECT_FALSE(req->response_info().network_accessed);
12510
12511 req->Start();
Wez2a31b222018-06-07 22:07:1512512 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512513
12514 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12515 EXPECT_FALSE(req->response_info().network_accessed);
12516}
12517
12518TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12519 MockHostResolver host_resolver;
12520 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12521 TestURLRequestContext context(true);
12522 context.set_network_delegate(&network_delegate);
12523 context.set_host_resolver(&host_resolver);
12524 host_resolver.rules()->AddSimulatedFailure("*");
12525 context.Init();
12526
12527 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612528 std::unique_ptr<URLRequest> req(
12529 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12530 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512531
12532 EXPECT_FALSE(req->response_info().network_accessed);
12533
12534 req->Start();
Wez2a31b222018-06-07 22:07:1512535 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512536 EXPECT_TRUE(req->response_info().network_accessed);
12537}
12538
mmenkeed0498b2015-12-08 23:20:4212539// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212540// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212541TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212542 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3612543 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612544 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12545 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212546
danakj8522a25b2016-04-16 00:17:3612547 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212548 req.get(), &default_network_delegate_,
12549 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212550 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12551 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212552
12553 req->Start();
12554 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212555 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012556 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212557 EXPECT_EQ(0, d.received_redirect_count());
12558}
12559
Andrey Kosyakov2e893e62017-08-31 17:00:5212560TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412561 ASSERT_TRUE(http_test_server()->Start());
12562 TestURLRequestContext context;
12563 GURL url(http_test_server()->GetURL("/cachetime"));
12564 TestDelegate delegate;
12565 HttpRequestHeaders extra_headers;
12566 extra_headers.SetHeader("X-Foo", "bar");
12567
12568 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212569 HttpRawRequestHeaders raw_req_headers;
12570 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12571
Andrey Kosyakov83a6eee2017-08-14 19:20:0412572 std::unique_ptr<URLRequest> r(context.CreateRequest(
12573 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12574 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212575 r->SetRequestHeadersCallback(base::Bind(
12576 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12577 r->SetResponseHeadersCallback(base::Bind(
12578 [](scoped_refptr<const HttpResponseHeaders>* left,
12579 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12580 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412581 r->Start();
12582 while (!delegate.response_started_count())
12583 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212584 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412585 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212586 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412587 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212588 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412589 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212590 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12591 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12592 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12593 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412594 }
12595 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412596 std::unique_ptr<URLRequest> r(context.CreateRequest(
12597 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12598 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212599 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412600 FAIL() << "Callback should not be called unless request is sent";
12601 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212602 r->SetResponseHeadersCallback(
12603 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12604 FAIL() << "Callback should not be called unless request is sent";
12605 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412606 r->Start();
Wez2a31b222018-06-07 22:07:1512607 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412608 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412609 }
12610}
12611
Andrey Kosyakov2e893e62017-08-31 17:00:5212612TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412613 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212614 HttpRawRequestHeaders raw_req_headers;
12615 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12616
Andrey Kosyakov83a6eee2017-08-14 19:20:0412617 TestURLRequestContext context;
12618 TestDelegate delegate;
12619 HttpRequestHeaders extra_headers;
12620 extra_headers.SetHeader("X-Foo", "bar");
12621 delegate.set_quit_on_redirect(true);
12622 GURL url(http_test_server()->GetURL("/redirect-test.html"));
12623 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12624 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12625 r->SetExtraRequestHeaders(extra_headers);
12626 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212627 base::Unretained(&raw_req_headers)));
12628 r->SetResponseHeadersCallback(base::Bind(
12629 [](scoped_refptr<const HttpResponseHeaders>* left,
12630 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12631 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412632 r->Start();
Wez2a31b222018-06-07 22:07:1512633 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412634
12635 ASSERT_EQ(1, delegate.received_redirect_count());
12636 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212637 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412638 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212639 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412640 EXPECT_EQ("gzip, deflate", value);
12641 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212642 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12643 raw_req_headers.request_line());
12644 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12645 EXPECT_EQ(302, raw_resp_headers->response_code());
12646 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412647
Andrey Kosyakov2e893e62017-08-31 17:00:5212648 raw_req_headers = HttpRawRequestHeaders();
12649 raw_resp_headers = nullptr;
Chong Zhang7607f1f2018-06-01 20:52:2012650 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:1512651 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212652 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412653 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212654 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412655 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212656 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12657 raw_req_headers.request_line());
12658 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412659}
12660
Andrey Kosyakov2e893e62017-08-31 17:00:5212661TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412662 TestDelegate request_delegate;
12663
12664 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12665 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12666 TRAFFIC_ANNOTATION_FOR_TESTS));
12667 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12668 FAIL() << "Callback should not be called unless request is sent";
12669 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212670 r->SetResponseHeadersCallback(
12671 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12672 FAIL() << "Callback should not be called unless request is sent";
12673 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412674 r->Start();
Wez2a31b222018-06-07 22:07:1512675 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412676 EXPECT_FALSE(r->is_pending());
12677}
12678
Andrey Kosyakov2e893e62017-08-31 17:00:5212679TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412680 ASSERT_TRUE(http_test_server()->Start());
12681 GURL url(http_test_server()->GetURL("/auth-basic"));
12682
12683 TestURLRequestContext context;
12684 TestDelegate delegate;
12685
12686 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12687 HttpRequestHeaders extra_headers;
12688 extra_headers.SetHeader("X-Foo", "bar");
12689
Andrey Kosyakov2e893e62017-08-31 17:00:5212690 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12691 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412692
Andrey Kosyakov2e893e62017-08-31 17:00:5212693 using RespHeadersVector =
12694 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12695 RespHeadersVector raw_resp_headers;
12696
12697 auto req_headers_callback = base::Bind(
12698 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12699 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12700 },
12701 &raw_req_headers);
12702 auto resp_headers_callback = base::Bind(
12703 [](RespHeadersVector* vec,
12704 scoped_refptr<const HttpResponseHeaders> headers) {
12705 vec->push_back(headers);
12706 },
12707 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412708 std::unique_ptr<URLRequest> r(context.CreateRequest(
12709 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12710 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212711 r->SetRequestHeadersCallback(req_headers_callback);
12712 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412713 r->Start();
Wez2a31b222018-06-07 22:07:1512714 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412715 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212716 ASSERT_EQ(raw_req_headers.size(), 2u);
12717 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412718 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212719 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12720 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412721 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212722 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12723 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412724 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212725 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12726 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12727 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12728 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12729
12730 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12731 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12732 r2->SetExtraRequestHeaders(extra_headers);
12733 r2->SetRequestHeadersCallback(req_headers_callback);
12734 r2->SetResponseHeadersCallback(resp_headers_callback);
12735 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12736 r2->Start();
Wez2a31b222018-06-07 22:07:1512737 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212738 EXPECT_FALSE(r2->is_pending());
12739 ASSERT_EQ(raw_req_headers.size(), 3u);
12740 ASSERT_EQ(raw_resp_headers.size(), 3u);
12741 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12742 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12743 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12744 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412745}
12746
Andrey Kosyakov2e893e62017-08-31 17:00:5212747TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412748 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12749 TestDelegate d;
12750 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12751 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12752 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212753 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412754 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212755 r->SetResponseHeadersCallback(
12756 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12757 FAIL() << "Callback should not be called for non-HTTP schemes";
12758 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412759 r->Start();
Wez2a31b222018-06-07 22:07:1512760 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412761 EXPECT_FALSE(r->is_pending());
12762}
12763
Carlos ILaef65d62018-06-04 21:24:1312764TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12765 TestDelegate d;
12766 BlockingNetworkDelegate network_delegate(
12767 BlockingNetworkDelegate::SYNCHRONOUS);
12768 const GURL kOriginalUrl("https://original.test");
12769 const GURL kRedirectUrl("http://redirect.test");
12770 network_delegate.set_redirect_url(kRedirectUrl);
12771 TestURLRequestContext context(true /* delay_initialization */);
12772 context.set_network_delegate(&network_delegate);
12773 context.Init();
12774
12775 std::unique_ptr<URLRequest> r(context.CreateRequest(
12776 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12777 r->set_upgrade_if_insecure(true);
12778 d.set_quit_on_redirect(true);
12779 r->Start();
12780 base::RunLoop().Run();
12781 GURL::Replacements replacements;
12782 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12783 // was set.
12784 replacements.SetSchemeStr("https");
12785 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12786 d.redirect_info().new_url);
12787}
12788
12789TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12790 TestDelegate d;
12791 BlockingNetworkDelegate network_delegate(
12792 BlockingNetworkDelegate::SYNCHRONOUS);
12793 const GURL kOriginalUrl("https://original.test");
12794 const GURL kRedirectUrl("http://redirect.test:80");
12795 network_delegate.set_redirect_url(kRedirectUrl);
12796 TestURLRequestContext context(true /* delay_initialization */);
12797 context.set_network_delegate(&network_delegate);
12798 context.Init();
12799
12800 std::unique_ptr<URLRequest> r(context.CreateRequest(
12801 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12802 r->set_upgrade_if_insecure(true);
12803 d.set_quit_on_redirect(true);
12804 r->Start();
12805 base::RunLoop().Run();
12806 GURL::Replacements replacements;
12807 // The URL host should have not been changed.
12808 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12809 // The scheme should now be https, and the effective port should now be 443.
12810 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12811 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
12812}
12813
12814TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12815 TestDelegate d;
12816 BlockingNetworkDelegate network_delegate(
12817 BlockingNetworkDelegate::SYNCHRONOUS);
12818 const GURL kOriginalUrl("https://original.test");
12819 const GURL kRedirectUrl("http://redirect.test:1234");
12820 network_delegate.set_redirect_url(kRedirectUrl);
12821 TestURLRequestContext context(true /* delay_initialization */);
12822 context.set_network_delegate(&network_delegate);
12823 context.Init();
12824
12825 std::unique_ptr<URLRequest> r(context.CreateRequest(
12826 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12827 r->set_upgrade_if_insecure(true);
12828 d.set_quit_on_redirect(true);
12829 r->Start();
12830 base::RunLoop().Run();
12831 GURL::Replacements replacements;
12832 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12833 // was set, nonstandard port should not have been modified.
12834 replacements.SetSchemeStr("https");
12835 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12836 d.redirect_info().new_url);
12837}
12838
12839TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12840 TestDelegate d;
12841 BlockingNetworkDelegate network_delegate(
12842 BlockingNetworkDelegate::SYNCHRONOUS);
12843 const GURL kOriginalUrl("https://original.test");
12844 const GURL kRedirectUrl("http://redirect.test");
12845 network_delegate.set_redirect_url(kRedirectUrl);
12846 TestURLRequestContext context(true /* delay_initialization */);
12847 context.set_network_delegate(&network_delegate);
12848 context.Init();
12849 std::unique_ptr<URLRequest> r(context.CreateRequest(
12850 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12851 r->set_upgrade_if_insecure(false);
12852 d.set_quit_on_redirect(true);
12853 r->Start();
12854 base::RunLoop().Run();
12855 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12856 // not set.
12857 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
12858}
12859
Paul Jensen60e45532018-02-19 16:04:1812860// Test that URLRequests get properly tagged.
12861#if defined(OS_ANDROID)
12862TEST_F(URLRequestTestHTTP, TestTagging) {
12863 ASSERT_TRUE(http_test_server()->Start());
12864
12865 // The tag under which the system reports untagged traffic.
12866 static const int32_t UNTAGGED_TAG = 0;
12867
12868 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12869
12870 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12871 TestDelegate delegate;
12872 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12873 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12874 TRAFFIC_ANNOTATION_FOR_TESTS));
12875 EXPECT_EQ(SocketTag(), req->socket_tag());
12876 req->Start();
Wez2a31b222018-06-07 22:07:1512877 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812878
12879 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12880
12881 int32_t tag_val1 = 0x12345678;
12882 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12883 old_traffic = GetTaggedBytes(tag_val1);
12884
12885 // Test specific tag value.
12886 req = default_context_.CreateRequest(http_test_server()->GetURL("/"),
12887 DEFAULT_PRIORITY, &delegate,
12888 TRAFFIC_ANNOTATION_FOR_TESTS);
12889 req->set_socket_tag(tag1);
12890 EXPECT_EQ(tag1, req->socket_tag());
12891 req->Start();
Wez2a31b222018-06-07 22:07:1512892 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812893
12894 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12895}
12896#endif
12897
[email protected]7461a402011-03-24 23:19:5112898} // namespace net