blob: 377fb8ea58a49e3d755675953f256efe8ad534e2 [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);
5953 for (size_t i = 0; i < 3; ++i) {
5954 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005955 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5956 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515957
5958 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5959 log_position + 1);
5960
5961 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005962 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5963 entries[log_position].type);
5964 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515965 }
5966
mikecirone8b85c432016-09-08 19:11:005967 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5968 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515969}
5970
5971// Tests handling of delegate info from a network delegate in the case of an
5972// HTTP redirect.
5973TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555974 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515975
5976 TestDelegate request_delegate;
5977 AsyncLoggingNetworkDelegate network_delegate;
5978 TestURLRequestContext context(true);
5979 context.set_network_delegate(&network_delegate);
5980 context.set_net_log(&net_log_);
5981 context.Init();
5982
5983 {
danakj8522a25b2016-04-16 00:17:365984 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555985 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165986 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195987 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515988 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085989 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515990
[email protected]f7022f32014-08-21 16:32:195991 r->Start();
Wez2a31b222018-06-07 22:07:155992 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:515993
[email protected]f7022f32014-08-21 16:32:195994 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505995 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515996 EXPECT_EQ(2, network_delegate.created_requests());
5997 EXPECT_EQ(0, network_delegate.destroyed_requests());
5998 }
5999 EXPECT_EQ(1, network_delegate.destroyed_requests());
6000
6001 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466002 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516003 net_log_.GetEntries(&entries);
6004 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:006005 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:516006 for (size_t i = 0; i < 3; ++i) {
6007 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006008 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6009 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516010
6011 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6012 log_position + 1);
6013
6014 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006015 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6016 entries[log_position].type);
6017 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516018 }
6019
6020 // The URLRequest::Delegate then gets informed about the redirect.
6021 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006022 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6023 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516024
6025 // The NetworkDelegate logged information in the same three events as before.
6026 for (size_t i = 0; i < 3; ++i) {
6027 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006028 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6029 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516030
6031 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6032 log_position + 1);
6033
6034 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006035 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6036 entries[log_position].type);
6037 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516038 }
6039
mikecirone8b85c432016-09-08 19:11:006040 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6041 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516042}
6043
6044// Tests handling of delegate info from a network delegate in the case of HTTP
6045// AUTH.
6046TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556047 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516048
6049 TestDelegate request_delegate;
6050 AsyncLoggingNetworkDelegate network_delegate;
6051 TestURLRequestContext context(true);
6052 context.set_network_delegate(&network_delegate);
6053 context.set_net_log(&net_log_);
6054 context.Init();
6055
6056 {
rhalavatib7bd7c792017-04-27 05:25:166057 std::unique_ptr<URLRequest> r(context.CreateRequest(
6058 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6059 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196060 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516061 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086062 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516063
[email protected]f7022f32014-08-21 16:32:196064 r->Start();
Wez2a31b222018-06-07 22:07:156065 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516066
[email protected]f7022f32014-08-21 16:32:196067 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506068 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516069 EXPECT_EQ(1, network_delegate.created_requests());
6070 EXPECT_EQ(0, network_delegate.destroyed_requests());
6071 }
6072 EXPECT_EQ(1, network_delegate.destroyed_requests());
6073
6074 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466075 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516076 net_log_.GetEntries(&entries);
6077 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:006078 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
6079 // in
6080 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:516081 for (size_t i = 0; i < 6; ++i) {
6082 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006083 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6084 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516085
6086 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6087 log_position + 1);
6088
6089 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006090 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6091 entries[log_position].type);
6092 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516093 }
6094
mikecirone8b85c432016-09-08 19:11:006095 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6096 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516097}
6098
tommycli59a63432015-11-06 00:10:556099// TODO(svaldez): Update tests to use EmbeddedTestServer.
6100#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516101// Tests handling of delegate info from a URLRequest::Delegate.
6102TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556103 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556104 base::FilePath(kTestFilePath));
6105
6106 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516107
6108 AsyncLoggingUrlRequestDelegate request_delegate(
6109 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6110 TestURLRequestContext context(true);
6111 context.set_network_delegate(NULL);
6112 context.set_net_log(&net_log_);
6113 context.Init();
6114
6115 {
6116 // A chunked response with delays between chunks is used to make sure that
6117 // attempts by the URLRequest delegate to log information while reading the
6118 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486119 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516120 // that it occurs.
danakj8522a25b2016-04-16 00:17:366121 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556122 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166123 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196124 LoadStateWithParam load_state = r->GetLoadState();
6125 r->Start();
Wez2a31b222018-06-07 22:07:156126 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516127
[email protected]f7022f32014-08-21 16:32:196128 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506129 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516130 }
6131
mmenke43758e62015-05-04 21:09:466132 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516133 net_log_.GetEntries(&entries);
6134
[email protected]1826a402014-01-08 15:40:486135 size_t log_position = 0;
6136
[email protected]abe1c4a2013-10-25 19:28:516137 // The delegate info should only have been logged on header complete. Other
6138 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:006139 log_position = ExpectLogContainsSomewhereAfter(
6140 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6141 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516142
6143 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6144 log_position + 1);
6145
6146 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006147 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
6148 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516149
mikecirone8b85c432016-09-08 19:11:006150 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6151 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516152 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006153 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516154}
tommycli59a63432015-11-06 00:10:556155#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516156
6157// Tests handling of delegate info from a URLRequest::Delegate in the case of
6158// an HTTP redirect.
6159TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556160 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516161
6162 AsyncLoggingUrlRequestDelegate request_delegate(
6163 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6164 TestURLRequestContext context(true);
6165 context.set_network_delegate(NULL);
6166 context.set_net_log(&net_log_);
6167 context.Init();
6168
6169 {
danakj8522a25b2016-04-16 00:17:366170 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556171 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166172 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196173 LoadStateWithParam load_state = r->GetLoadState();
6174 r->Start();
Wez2a31b222018-06-07 22:07:156175 request_delegate.RunUntilComplete();
[email protected]abe1c4a2013-10-25 19:28:516176
[email protected]f7022f32014-08-21 16:32:196177 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506178 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516179 }
6180
mmenke43758e62015-05-04 21:09:466181 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516182 net_log_.GetEntries(&entries);
6183
6184 // Delegate info should only have been logged in OnReceivedRedirect and
6185 // OnResponseStarted.
6186 size_t log_position = 0;
6187 for (int i = 0; i < 2; ++i) {
6188 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006189 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
6190 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516191
6192 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6193 log_position + 1);
6194
6195 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006196 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6197 entries[log_position].type);
6198 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516199 }
6200
mikecirone8b85c432016-09-08 19:11:006201 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6202 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516203 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006204 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516205}
6206
6207// Tests handling of delegate info from a URLRequest::Delegate in the case of
6208// an HTTP redirect, with cancellation at various points.
6209TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556210 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516211
6212 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6213 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6214 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6215 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6216 };
6217
6218 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
6219 ++test_case) {
6220 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:516221 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046222 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:516223 context.set_network_delegate(NULL);
6224 context.set_net_log(&net_log);
6225 context.Init();
6226
6227 {
danakj8522a25b2016-04-16 00:17:366228 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556229 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166230 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196231 LoadStateWithParam load_state = r->GetLoadState();
6232 r->Start();
Wez2a31b222018-06-07 22:07:156233 request_delegate.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506234 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
Wez2a31b222018-06-07 22:07:156235
6236 // Spin the message loop to run AsyncDelegateLogger task(s) posted after
6237 // the |request_delegate| completion task.
6238 base::RunLoop().RunUntilIdle();
[email protected]abe1c4a2013-10-25 19:28:516239 }
6240
mmenke43758e62015-05-04 21:09:466241 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516242 net_log.GetEntries(&entries);
6243
6244 // Delegate info is always logged in both OnReceivedRedirect and
6245 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6246 // OnResponseStarted delegate call is after cancellation, but logging is
6247 // still currently supported in that call.
6248 size_t log_position = 0;
6249 for (int i = 0; i < 2; ++i) {
6250 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006251 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
6252 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516253
6254 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6255 log_position + 1);
6256
6257 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006258 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6259 entries[log_position].type);
6260 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516261 }
6262
mikecirone8b85c432016-09-08 19:11:006263 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6264 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516265 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006266 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516267 }
6268}
6269
[email protected]847c0fa92012-11-06 16:37:426270namespace {
6271
6272const char kExtraHeader[] = "Allow-Snafu";
6273const char kExtraValue[] = "fubar";
6274
6275class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206276 void OnReceivedRedirect(URLRequest* request,
6277 const RedirectInfo& redirect_info,
6278 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596279 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426280 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6281 }
6282};
6283
6284} // namespace
6285
6286TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556287 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426288
tommycli59a63432015-11-06 00:10:556289 GURL destination_url =
6290 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6291 GURL original_url =
6292 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426293 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166294 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6295 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196296 req->Start();
Wez2a31b222018-06-07 22:07:156297 d.RunUntilComplete();
[email protected]847c0fa92012-11-06 16:37:426298
6299 std::string value;
[email protected]f7022f32014-08-21 16:32:196300 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426301 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6302 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196303 EXPECT_FALSE(req->is_pending());
6304 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426305 EXPECT_EQ(kExtraValue, d.data_received());
6306}
6307
[email protected]251a1b92012-11-13 11:01:096308namespace {
6309
6310const char kExtraHeaderToRemove[] = "To-Be-Removed";
6311
6312class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206313 void OnReceivedRedirect(URLRequest* request,
6314 const RedirectInfo& redirect_info,
6315 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596316 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096317 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6318 }
6319};
6320
6321} // namespace
6322
6323TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556324 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096325
tommycli59a63432015-11-06 00:10:556326 GURL destination_url = http_test_server()->GetURL(
6327 "/echoheader?" + std::string(kExtraHeaderToRemove));
6328 GURL original_url =
6329 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096330 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166331 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6332 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196333 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6334 req->Start();
Wez2a31b222018-06-07 22:07:156335 d.RunUntilComplete();
[email protected]251a1b92012-11-13 11:01:096336
6337 std::string value;
[email protected]f7022f32014-08-21 16:32:196338 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096339 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196340 EXPECT_FALSE(req->is_pending());
6341 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096342 EXPECT_EQ("None", d.data_received());
6343}
6344
mmenke94f1bd92016-12-07 21:13:056345TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446346 TestDelegate d;
6347 {
danakj8522a25b2016-04-16 00:17:366348 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166349 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6350 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446351
[email protected]f7022f32014-08-21 16:32:196352 r->Start();
6353 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446354
[email protected]f7022f32014-08-21 16:32:196355 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446356
Wez2a31b222018-06-07 22:07:156357 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446358
6359 // We expect to receive OnResponseStarted even though the request has been
6360 // cancelled.
6361 EXPECT_EQ(1, d.response_started_count());
6362 EXPECT_EQ(0, d.bytes_received());
6363 EXPECT_FALSE(d.received_data_before_response());
6364 }
6365}
6366
mmenke94f1bd92016-12-07 21:13:056367TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556368 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446369
6370 TestDelegate d;
6371 {
danakj8522a25b2016-04-16 00:17:366372 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166373 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6374 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446375
6376 d.set_cancel_in_response_started(true);
6377
[email protected]f7022f32014-08-21 16:32:196378 r->Start();
6379 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446380
Wez2a31b222018-06-07 22:07:156381 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446382
6383 EXPECT_EQ(1, d.response_started_count());
6384 EXPECT_EQ(0, d.bytes_received());
6385 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506386 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446387 }
6388}
6389
mmenke94f1bd92016-12-07 21:13:056390TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556391 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446392
6393 TestDelegate d;
6394 {
danakj8522a25b2016-04-16 00:17:366395 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166396 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6397 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056398
6399 d.set_cancel_in_received_data(true);
6400
6401 r->Start();
6402 EXPECT_TRUE(r->is_pending());
6403
Wez2a31b222018-06-07 22:07:156404 d.RunUntilComplete();
mmenke94f1bd92016-12-07 21:13:056405
6406 EXPECT_EQ(1, d.response_started_count());
6407 EXPECT_NE(0, d.received_bytes_count());
6408 EXPECT_FALSE(d.received_data_before_response());
6409 EXPECT_EQ(ERR_ABORTED, d.request_status());
6410 }
6411}
6412
6413TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6414 ASSERT_TRUE(http_test_server()->Start());
6415
6416 TestDelegate d;
6417 {
6418 // This returns an empty response (With headers).
6419 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166420 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6421 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446422
6423 d.set_cancel_in_received_data(true);
6424
[email protected]f7022f32014-08-21 16:32:196425 r->Start();
6426 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446427
Wez2a31b222018-06-07 22:07:156428 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446429
6430 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056431 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446432 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506433 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446434 }
6435}
6436
mmenke94f1bd92016-12-07 21:13:056437TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556438 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446439
6440 TestDelegate d;
6441 {
danakj8522a25b2016-04-16 00:17:366442 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166443 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6444 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446445
[email protected]f7022f32014-08-21 16:32:196446 r->Start();
6447 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446448
6449 // The request will be implicitly canceled when it is destroyed. The
6450 // test delegate must not post a quit message when this happens because
6451 // this test doesn't actually have a message loop. The quit message would
6452 // get put on this thread's message queue and the next test would exit
6453 // early, causing problems.
6454 d.set_quit_on_complete(false);
6455 }
6456 // expect things to just cleanup properly.
6457
kimwjdalsl2bb4ff02015-12-16 22:06:026458 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446459 // message loop
6460 EXPECT_FALSE(d.received_data_before_response());
6461 EXPECT_EQ(0, d.bytes_received());
6462}
6463
mmenke94f1bd92016-12-07 21:13:056464TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556465 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446466
6467 // populate cache
6468 {
6469 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366470 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166471 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6472 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196473 r->Start();
Wez2a31b222018-06-07 22:07:156474 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:506475 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446476 }
6477
6478 // cancel read from cache (see bug 990242)
6479 {
6480 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366481 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166482 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6483 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196484 r->Start();
6485 r->Cancel();
Wez2a31b222018-06-07 22:07:156486 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446487
maksim.sisovb53724b52016-09-16 05:30:506488 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446489 EXPECT_EQ(1, d.response_started_count());
6490 EXPECT_EQ(0, d.bytes_received());
6491 EXPECT_FALSE(d.received_data_before_response());
6492 }
6493}
6494
6495TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556496 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446497 HTTPUploadDataOperationTest("POST");
6498}
6499
6500TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556501 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446502 HTTPUploadDataOperationTest("PUT");
6503}
6504
6505TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556506 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446507
6508 TestDelegate d;
6509 {
danakj8522a25b2016-04-16 00:17:366510 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166511 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6512 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196513 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446514
[email protected]f7022f32014-08-21 16:32:196515 r->Start();
6516 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446517
Wez2a31b222018-06-07 22:07:156518 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446519
maksim.sisovb53724b52016-09-16 05:30:506520 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6521 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446522
6523 EXPECT_FALSE(d.received_data_before_response());
6524 EXPECT_TRUE(d.data_received().empty());
6525 }
6526}
6527
6528TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556529 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446530
6531 TestDelegate d;
6532 {
danakj8522a25b2016-04-16 00:17:366533 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166534 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6535 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196536 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446537
[email protected]6cdfd7f2013-02-08 20:40:156538 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196539 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026540 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446541
danakj8522a25b2016-04-16 00:17:366542 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446543
[email protected]6cdfd7f2013-02-08 20:40:156544 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196545 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476546 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446547 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196548 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146549 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076550 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046551 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6552 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446553
[email protected]f7022f32014-08-21 16:32:196554 r->Start();
6555 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446556
Wez2a31b222018-06-07 22:07:156557 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446558
avibf0746c2015-12-09 19:53:146559 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296560 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6561 ASSERT_LE(size64, std::numeric_limits<int>::max());
6562 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366563 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446564
[email protected]7600d0b2013-12-08 21:43:306565 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446566
maksim.sisovb53724b52016-09-16 05:30:506567 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6568 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446569
6570 EXPECT_FALSE(d.received_data_before_response());
6571
[email protected]329b68b2012-11-14 17:54:276572 EXPECT_EQ(size, d.bytes_received());
6573 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446574 }
6575}
6576
[email protected]999dd8c2013-11-12 06:45:546577TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556578 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546579
6580 TestDelegate d;
6581 {
danakj8522a25b2016-04-16 00:17:366582 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166583 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6584 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196585 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546586
danakj8522a25b2016-04-16 00:17:366587 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546588
Jeremy Roman0579ed62017-08-29 15:56:196589 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456590 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546591 base::FilePath(FILE_PATH_LITERAL(
6592 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076593 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046594 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6595 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546596
[email protected]f7022f32014-08-21 16:32:196597 r->Start();
6598 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546599
Wez2a31b222018-06-07 22:07:156600 d.RunUntilComplete();
[email protected]999dd8c2013-11-12 06:45:546601
[email protected]999dd8c2013-11-12 06:45:546602 EXPECT_TRUE(d.request_failed());
6603 EXPECT_FALSE(d.received_data_before_response());
6604 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506605 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546606 }
6607}
6608
mmenke56b0cbb912016-03-28 21:34:536609namespace {
6610
6611// Adds a standard set of data to an upload for chunked upload integration
6612// tests.
6613void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6614 writer->AppendData("a", 1, false);
6615 writer->AppendData("bcd", 3, false);
6616 writer->AppendData("this is a longer chunk than before.", 35, false);
6617 writer->AppendData("\r\n\r\n", 4, false);
6618 writer->AppendData("0", 1, false);
6619 writer->AppendData("2323", 4, true);
6620}
6621
6622// Checks that the upload data added in AddChunksToUpload() was echoed back from
6623// the server.
6624void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6625 // This should match the chunks sent by AddChunksToUpload().
6626 const std::string expected_data =
6627 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6628
maksim.sisovb53724b52016-09-16 05:30:506629 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6630 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536631
6632 EXPECT_FALSE(d->received_data_before_response());
6633
6634 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6635 EXPECT_EQ(expected_data, d->data_received());
6636}
6637
6638} // namespace
6639
[email protected]316c1e5e2012-09-12 15:17:446640TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556641 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446642
6643 TestDelegate d;
6644 {
danakj8522a25b2016-04-16 00:17:366645 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166646 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6647 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366648 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536649 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366650 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536651 upload_data_stream->CreateWriter();
6652 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196653 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536654 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196655 r->Start();
6656 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446657
Wez2a31b222018-06-07 22:07:156658 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446659
[email protected]f7022f32014-08-21 16:32:196660 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446661 }
6662}
6663
[email protected]329b68b2012-11-14 17:54:276664TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556665 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276666
6667 TestDelegate d;
6668 {
danakj8522a25b2016-04-16 00:17:366669 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166670 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6671 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366672 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536673 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366674 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536675 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046676 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196677 r->set_method("POST");
6678 r->Start();
6679 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536680 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156681 d.RunUntilComplete();
[email protected]329b68b2012-11-14 17:54:276682
[email protected]f7022f32014-08-21 16:32:196683 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276684 }
6685}
6686
[email protected]316c1e5e2012-09-12 15:17:446687TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556688 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446689
6690 TestDelegate d;
6691 {
danakj8522a25b2016-04-16 00:17:366692 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166693 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6694 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366695 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536696 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366697 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536698 upload_data_stream->CreateWriter();
6699 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196700 r->set_method("POST");
6701 r->Start();
6702 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446703
[email protected]255620da2013-08-19 13:14:296704 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536705 AddDataToUpload(writer.get());
Wez2a31b222018-06-07 22:07:156706 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446707
[email protected]f7022f32014-08-21 16:32:196708 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446709 }
6710}
6711
6712TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556713 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446714
6715 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366716 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166717 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6718 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196719 req->Start();
Wez2a31b222018-06-07 22:07:156720 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:446721
[email protected]f7022f32014-08-21 16:32:196722 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446723
6724 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196725 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446726
6727 std::string header;
6728 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6729 EXPECT_EQ("private", header);
6730
6731 header.clear();
6732 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6733 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6734
6735 // The response has two "X-Multiple-Entries" headers.
6736 // This verfies our output has them concatenated together.
6737 header.clear();
6738 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6739 EXPECT_EQ("a, b", header);
6740}
6741
tommycli59a63432015-11-06 00:10:556742// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6743// security state. (see http://crbug.com/550977).
6744#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466745TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556746 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6747 https_test_server.SetSSLConfig(
6748 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6749 https_test_server.ServeFilesFromSourceDirectory(
6750 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466751 ASSERT_TRUE(https_test_server.Start());
6752
tommycli59a63432015-11-06 00:10:556753 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466754 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366755 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166756 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6757 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196758 request->Start();
Wez2a31b222018-06-07 22:07:156759 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:466760
6761 TransportSecurityState* security_state =
6762 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406763 TransportSecurityState::STSState sts_state;
6764 TransportSecurityState::PKPState pkp_state;
6765 EXPECT_TRUE(
6766 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6767 EXPECT_FALSE(
6768 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6769 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6770 sts_state.upgrade_mode);
6771 EXPECT_TRUE(sts_state.include_subdomains);
6772 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036773#if defined(OS_ANDROID)
6774 // Android's CertVerifyProc does not (yet) handle pins.
6775#else
martijnc0d6b622015-06-30 19:14:406776 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036777#endif
[email protected]37fd55fb2013-06-29 13:13:276778}
6779
estarka5da76702015-04-09 04:00:166780TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556781 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6782 https_test_server.ServeFilesFromSourceDirectory(
6783 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166784 ASSERT_TRUE(https_test_server.Start());
6785 // Make sure this test fails if the test server is changed to not
6786 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556787 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6788 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166789
6790 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366791 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166792 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6793 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166794 request->Start();
Wez2a31b222018-06-07 22:07:156795 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:166796 TransportSecurityState* security_state =
6797 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406798 TransportSecurityState::STSState sts_state;
6799 EXPECT_FALSE(
6800 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166801}
6802
estark06e0dac2015-08-07 21:56:016803namespace {
Martijn Croonenb1383da2017-10-11 11:56:356804const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
6805const char kExpectStapleStaticHostname[] = "expect-staple.preloaded.test";
6806const char kExpectStapleReportURI[] =
6807 "http://report-uri.preloaded.test/expect-staple";
estark06e0dac2015-08-07 21:56:016808const char kHPKPReportUri[] = "https://hpkp-report.test";
6809} // namespace
6810
[email protected]37fd55fb2013-06-29 13:13:276811// Tests that enabling HPKP on a domain does not affect the HSTS
6812// validity/expiration.
dadrian2faf2062016-07-16 00:03:176813TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016814 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556815 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6816 https_test_server.SetSSLConfig(
6817 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6818 https_test_server.ServeFilesFromSourceDirectory(
6819 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276820 ASSERT_TRUE(https_test_server.Start());
6821
tommycli59a63432015-11-06 00:10:556822 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166823
[email protected]37fd55fb2013-06-29 13:13:276824 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366825 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166826 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6827 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196828 request->Start();
Wez2a31b222018-06-07 22:07:156829 d.RunUntilComplete();
[email protected]37fd55fb2013-06-29 13:13:276830 TransportSecurityState* security_state =
6831 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406832 TransportSecurityState::STSState sts_state;
6833 TransportSecurityState::PKPState pkp_state;
6834 EXPECT_FALSE(
6835 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6836 EXPECT_TRUE(
6837 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6838 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6839 sts_state.upgrade_mode);
6840 EXPECT_FALSE(sts_state.include_subdomains);
6841 EXPECT_FALSE(pkp_state.include_subdomains);
6842 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016843 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406844 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466845}
6846
estark06e0dac2015-08-07 21:56:016847// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176848TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016849 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556850 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6851 https_test_server.SetSSLConfig(
6852 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6853 https_test_server.ServeFilesFromSourceDirectory(
6854 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016855 ASSERT_TRUE(https_test_server.Start());
6856
tommycli59a63432015-11-06 00:10:556857 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016858
6859 // Set up a pin for |test_server_hostname|.
6860 TransportSecurityState security_state;
6861 const base::Time current_time(base::Time::Now());
6862 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6863 HashValueVector hashes;
6864 HashValue hash1;
6865 HashValue hash2;
6866 // The values here don't matter, as long as they are different from
6867 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446868 ASSERT_TRUE(
6869 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6870 ASSERT_TRUE(
6871 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016872 hashes.push_back(hash1);
6873 hashes.push_back(hash2);
6874 security_state.AddHPKP(test_server_hostname, expiry,
6875 false, /* include subdomains */
6876 hashes, report_uri);
6877
6878 MockCertificateReportSender mock_report_sender;
6879 security_state.SetReportSender(&mock_report_sender);
6880
6881 // Set up a MockCertVerifier to trigger a violation of the previously
6882 // set pin.
6883 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6884 ASSERT_TRUE(cert);
6885
6886 MockCertVerifier cert_verifier;
6887 CertVerifyResult verify_result;
6888 verify_result.verified_cert = cert;
6889 verify_result.is_issued_by_known_root = true;
6890 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446891 ASSERT_TRUE(
6892 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016893 verify_result.public_key_hashes.push_back(hash3);
6894 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6895
6896 TestNetworkDelegate network_delegate;
6897 TestURLRequestContext context(true);
6898 context.set_transport_security_state(&security_state);
6899 context.set_network_delegate(&network_delegate);
6900 context.set_cert_verifier(&cert_verifier);
6901 context.Init();
6902
6903 // Now send a request to trigger the violation.
6904 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366905 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166906 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6907 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016908 violating_request->Start();
Wez2a31b222018-06-07 22:07:156909 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016910
6911 // Check that a report was sent.
6912 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6913 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446914 EXPECT_EQ("application/json; charset=utf-8",
6915 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366916 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016917 base::JSONReader::Read(mock_report_sender.latest_report()));
6918 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086919 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016920 base::DictionaryValue* report_dict;
6921 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6922 std::string report_hostname;
6923 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6924 EXPECT_EQ(test_server_hostname, report_hostname);
6925}
6926
6927// Tests that reports get sent on requests with
6928// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176929TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016930 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556931 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6932 https_test_server.SetSSLConfig(
6933 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6934 https_test_server.ServeFilesFromSourceDirectory(
6935 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016936 ASSERT_TRUE(https_test_server.Start());
6937
tommycli59a63432015-11-06 00:10:556938 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016939
6940 TransportSecurityState security_state;
6941 MockCertificateReportSender mock_report_sender;
6942 security_state.SetReportSender(&mock_report_sender);
6943
6944 // Set up a MockCertVerifier to violate the pin in the Report-Only
6945 // header.
6946 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6947 ASSERT_TRUE(cert);
6948
6949 MockCertVerifier cert_verifier;
6950 CertVerifyResult verify_result;
6951 verify_result.verified_cert = cert;
6952 verify_result.is_issued_by_known_root = true;
6953 HashValue hash;
6954 // This value doesn't matter, as long as it is different from the pins
6955 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446956 ASSERT_TRUE(
6957 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016958 verify_result.public_key_hashes.push_back(hash);
6959 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6960
6961 TestNetworkDelegate network_delegate;
6962 TestURLRequestContext context(true);
6963 context.set_transport_security_state(&security_state);
6964 context.set_network_delegate(&network_delegate);
6965 context.set_cert_verifier(&cert_verifier);
6966 context.Init();
6967
6968 // Now send a request to trigger the violation.
6969 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366970 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556971 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166972 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016973 violating_request->Start();
Wez2a31b222018-06-07 22:07:156974 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:016975
6976 // Check that a report was sent.
6977 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6978 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446979 EXPECT_EQ("application/json; charset=utf-8",
6980 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366981 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016982 base::JSONReader::Read(mock_report_sender.latest_report()));
6983 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086984 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016985 base::DictionaryValue* report_dict;
6986 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6987 std::string report_hostname;
6988 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6989 EXPECT_EQ(test_server_hostname, report_hostname);
6990}
6991
6992// Tests that reports do not get sent on requests with
6993// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176994TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016995 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556996 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6997 https_test_server.SetSSLConfig(
6998 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6999 https_test_server.ServeFilesFromSourceDirectory(
7000 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:017001 ASSERT_TRUE(https_test_server.Start());
7002
tommycli59a63432015-11-06 00:10:557003 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:017004
7005 TransportSecurityState security_state;
7006 MockCertificateReportSender mock_report_sender;
7007 security_state.SetReportSender(&mock_report_sender);
7008
7009 TestNetworkDelegate network_delegate;
7010 MockCertVerifier mock_cert_verifier;
7011 TestURLRequestContext context(true);
7012 context.set_transport_security_state(&security_state);
7013 context.set_network_delegate(&network_delegate);
7014 context.set_cert_verifier(&mock_cert_verifier);
7015 mock_cert_verifier.set_default_result(OK);
7016 context.Init();
7017
7018 // Now send a request that does not trigger the violation.
7019 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367020 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557021 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:167022 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:017023 request->Start();
Wez2a31b222018-06-07 22:07:157024 d.RunUntilComplete();
estark06e0dac2015-08-07 21:56:017025
7026 // Check that a report was not sent.
7027 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
7028 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
7029}
7030
estarka5da76702015-04-09 04:00:167031TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:557032 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7033 https_test_server.ServeFilesFromSourceDirectory(
7034 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:167035 ASSERT_TRUE(https_test_server.Start());
7036 // Make sure this test fails if the test server is changed to not
7037 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:557038 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
7039 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167040
7041 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367042 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167043 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7044 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:167045 request->Start();
Wez2a31b222018-06-07 22:07:157046 d.RunUntilComplete();
estarka5da76702015-04-09 04:00:167047
7048 TransportSecurityState* security_state =
7049 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407050 TransportSecurityState::PKPState pkp_state;
7051 EXPECT_FALSE(
7052 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:167053}
7054
dadriandf302c42016-06-10 18:48:597055TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7056 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7057 https_test_server.SetSSLConfig(
7058 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7059 https_test_server.ServeFilesFromSourceDirectory(
7060 base::FilePath(kTestFilePath));
7061 ASSERT_TRUE(https_test_server.Start());
7062
7063 // Set up a MockCertVerifier to be a local root that violates the pin
7064 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7065 ASSERT_TRUE(cert);
7066
7067 MockCertVerifier cert_verifier;
7068 CertVerifyResult verify_result;
7069 verify_result.verified_cert = cert;
7070 verify_result.is_issued_by_known_root = false;
7071 HashValue hash;
7072 ASSERT_TRUE(
7073 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7074 verify_result.public_key_hashes.push_back(hash);
7075 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7076 cert_verifier.set_default_result(OK);
7077
7078 std::string test_server_hostname = https_test_server.GetURL("/").host();
7079
7080 // Set up HPKP
7081 base::Time current_time = base::Time::Now();
7082 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
7083 HashValue pin;
7084 ASSERT_TRUE(
7085 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
7086 HashValueVector hashes;
7087 hashes.push_back(pin);
7088 GURL report_uri(kHPKPReportUri);
7089 TransportSecurityState security_state;
7090 security_state.AddHPKP(test_server_hostname, expiry,
7091 false, /* include subdomains */
7092 hashes, report_uri);
7093
7094 TestNetworkDelegate network_delegate;
7095 TestURLRequestContext context(true);
7096 context.set_transport_security_state(&security_state);
7097 context.set_network_delegate(&network_delegate);
7098 context.set_cert_verifier(&cert_verifier);
7099 context.Init();
7100
7101 TestDelegate d;
7102 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167103 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7104 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597105 request->Start();
Wez2a31b222018-06-07 22:07:157106 d.RunUntilComplete();
dadriandf302c42016-06-10 18:48:597107
7108 TransportSecurityState::PKPState pkp_state;
7109 EXPECT_TRUE(
7110 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
7111 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7112}
7113
[email protected]242d8562012-10-30 21:20:467114TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557115 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7116 https_test_server.SetSSLConfig(
7117 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7118 https_test_server.ServeFilesFromSourceDirectory(
7119 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467120 ASSERT_TRUE(https_test_server.Start());
7121
tommycli59a63432015-11-06 00:10:557122 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167123
[email protected]242d8562012-10-30 21:20:467124 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367125 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557126 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167127 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197128 request->Start();
Wez2a31b222018-06-07 22:07:157129 d.RunUntilComplete();
[email protected]242d8562012-10-30 21:20:467130
7131 // We should have set parameters from the first header, not the second.
7132 TransportSecurityState* security_state =
7133 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407134 TransportSecurityState::STSState sts_state;
7135 EXPECT_TRUE(
7136 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7137 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7138 sts_state.upgrade_mode);
7139 EXPECT_FALSE(sts_state.include_subdomains);
7140 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467141}
7142
[email protected]9f972ec2013-04-10 20:24:367143TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:557144 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7145 https_test_server.SetSSLConfig(
7146 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7147 https_test_server.ServeFilesFromSourceDirectory(
7148 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:367149 ASSERT_TRUE(https_test_server.Start());
7150
tommycli59a63432015-11-06 00:10:557151 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167152
[email protected]9f972ec2013-04-10 20:24:367153 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367154 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557155 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167156 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197157 request->Start();
Wez2a31b222018-06-07 22:07:157158 d.RunUntilComplete();
[email protected]9f972ec2013-04-10 20:24:367159
7160 // We should have set parameters from the first header, not the second.
7161 TransportSecurityState* security_state =
7162 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407163 TransportSecurityState::STSState sts_state;
7164 TransportSecurityState::PKPState pkp_state;
7165 EXPECT_TRUE(
7166 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7167 EXPECT_TRUE(
7168 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7169 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7170 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037171#if defined(OS_ANDROID)
7172 // Android's CertVerifyProc does not (yet) handle pins.
7173#else
martijnc0d6b622015-06-30 19:14:407174 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037175#endif
martijnc0d6b622015-06-30 19:14:407176 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:367177
[email protected]a165f092013-06-12 16:10:057178 // Even though there is an HSTS header asserting includeSubdomains, it is
7179 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:407180 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:057181 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:407182 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:367183}
7184
[email protected]37fd55fb2013-06-29 13:13:277185// Tests that when multiple HPKP headers are present, asserting different
7186// policies, that only the first such policy is processed.
7187TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:557188 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7189 https_test_server.SetSSLConfig(
7190 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7191 https_test_server.ServeFilesFromSourceDirectory(
7192 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:277193 ASSERT_TRUE(https_test_server.Start());
7194
tommycli59a63432015-11-06 00:10:557195 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167196
[email protected]37fd55fb2013-06-29 13:13:277197 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367198 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557199 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:167200 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197201 request->Start();
Wez2a31b222018-06-07 22:07:157202 d.RunUntilComplete();
[email protected]37fd55fb2013-06-29 13:13:277203
7204 TransportSecurityState* security_state =
7205 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407206 TransportSecurityState::STSState sts_state;
7207 TransportSecurityState::PKPState pkp_state;
7208 EXPECT_TRUE(
7209 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7210 EXPECT_TRUE(
7211 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7212 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7213 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037214#if defined(OS_ANDROID)
7215 // Android's CertVerifyProc does not (yet) handle pins.
7216#else
martijnc0d6b622015-06-30 19:14:407217 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037218#endif
martijnc0d6b622015-06-30 19:14:407219 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:277220
martijnc0d6b622015-06-30 19:14:407221 EXPECT_TRUE(sts_state.include_subdomains);
7222 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:277223}
7224
estark1614475f2016-03-10 03:46:477225// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7226// called.
7227class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7228 public:
7229 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277230 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477231
7232 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7233 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017234 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257235 const X509Certificate* validated_certificate_chain,
7236 const X509Certificate* served_certificate_chain,
7237 const SignedCertificateTimestampAndStatusList&
7238 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477239 num_failures_++;
7240 }
7241
7242 uint32_t num_failures() { return num_failures_; }
7243
7244 private:
7245 uint32_t num_failures_;
7246};
7247
Emily Stark627238f2017-11-29 03:29:547248// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477249// for every certificate.
7250class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7251 public:
7252 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547253 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277254 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477255
Emily Stark627238f2017-11-29 03:29:547256 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477257 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237258 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207259 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477260 return default_result_;
7261 }
7262
Emily Stark627238f2017-11-29 03:29:547263 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477264 default_result_ = default_result;
7265 }
7266
7267 private:
Emily Stark627238f2017-11-29 03:29:547268 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477269};
7270
Emily Stark4cfecf072017-08-08 01:05:517271// Tests that Expect CT headers for the preload list are processed correctly.
7272TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357273 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7274
estark1614475f2016-03-10 03:46:477275 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7276 https_test_server.SetSSLConfig(
7277 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7278 https_test_server.ServeFilesFromSourceDirectory(
7279 base::FilePath(kTestFilePath));
7280 ASSERT_TRUE(https_test_server.Start());
7281
7282 MockExpectCTReporter reporter;
7283 TransportSecurityState transport_security_state;
7284 transport_security_state.enable_static_expect_ct_ = true;
7285 transport_security_state.SetExpectCTReporter(&reporter);
7286
7287 // Set up a MockCertVerifier to accept the certificate that the server sends.
7288 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7289 ASSERT_TRUE(cert);
7290 MockCertVerifier cert_verifier;
7291 CertVerifyResult verify_result;
7292 verify_result.verified_cert = cert;
7293 verify_result.is_issued_by_known_root = true;
7294 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7295
rsleevi22cae1672016-12-28 01:53:367296 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7297 // CT violation.
7298 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477299 MockCTPolicyEnforcer ct_policy_enforcer;
7300 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547301 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477302
7303 TestNetworkDelegate network_delegate;
7304 // Use a MockHostResolver (which by default maps all hosts to
7305 // 127.0.0.1) so that the request can be sent to a site on the Expect
7306 // CT preload list.
7307 MockHostResolver host_resolver;
7308 TestURLRequestContext context(true);
7309 context.set_host_resolver(&host_resolver);
7310 context.set_transport_security_state(&transport_security_state);
7311 context.set_network_delegate(&network_delegate);
7312 context.set_cert_verifier(&cert_verifier);
7313 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467314 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477315 context.Init();
7316
7317 // Now send a request to trigger the violation.
7318 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517319 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477320 GURL::Replacements replace_host;
7321 replace_host.SetHostStr(kExpectCTStaticHostname);
7322 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167323 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7324 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477325 violating_request->Start();
Wez2a31b222018-06-07 22:07:157326 d.RunUntilComplete();
estark1614475f2016-03-10 03:46:477327
7328 EXPECT_EQ(1u, reporter.num_failures());
7329}
Emily Stark4cfecf072017-08-08 01:05:517330
7331// Tests that Expect CT HTTP headers are processed correctly.
7332TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7333 base::test::ScopedFeatureList feature_list;
7334 feature_list.InitAndEnableFeature(
7335 TransportSecurityState::kDynamicExpectCTFeature);
7336
7337 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7338 https_test_server.SetSSLConfig(
7339 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7340 https_test_server.ServeFilesFromSourceDirectory(
7341 base::FilePath(kTestFilePath));
7342 ASSERT_TRUE(https_test_server.Start());
7343
7344 MockExpectCTReporter reporter;
7345 TransportSecurityState transport_security_state;
7346 transport_security_state.SetExpectCTReporter(&reporter);
7347
7348 // Set up a MockCertVerifier to accept the certificate that the server sends.
7349 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7350 ASSERT_TRUE(cert);
7351 MockCertVerifier cert_verifier;
7352 CertVerifyResult verify_result;
7353 verify_result.verified_cert = cert;
7354 verify_result.is_issued_by_known_root = true;
7355 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7356
7357 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7358 // compliance.
7359 DoNothingCTVerifier ct_verifier;
7360 MockCTPolicyEnforcer ct_policy_enforcer;
7361 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547362 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517363
7364 TestNetworkDelegate network_delegate;
7365 // Use a MockHostResolver (which by default maps all hosts to
7366 // 127.0.0.1).
7367 MockHostResolver host_resolver;
7368 TestURLRequestContext context(true);
7369 context.set_host_resolver(&host_resolver);
7370 context.set_transport_security_state(&transport_security_state);
7371 context.set_network_delegate(&network_delegate);
7372 context.set_cert_verifier(&cert_verifier);
7373 context.set_cert_transparency_verifier(&ct_verifier);
7374 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7375 context.Init();
7376
7377 // Now send a request to trigger the header processing.
7378 TestDelegate d;
7379 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7380 std::unique_ptr<URLRequest> request(context.CreateRequest(
7381 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7382 request->Start();
Wez2a31b222018-06-07 22:07:157383 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517384
7385 TransportSecurityState::ExpectCTState state;
7386 ASSERT_TRUE(
7387 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7388 EXPECT_TRUE(state.enforce);
7389 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7390}
7391
7392// Tests that if multiple Expect CT HTTP headers are sent, they are all
7393// processed.
7394TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7395 base::test::ScopedFeatureList feature_list;
7396 feature_list.InitAndEnableFeature(
7397 TransportSecurityState::kDynamicExpectCTFeature);
7398
7399 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7400 https_test_server.SetSSLConfig(
7401 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7402 https_test_server.ServeFilesFromSourceDirectory(
7403 base::FilePath(kTestFilePath));
7404 ASSERT_TRUE(https_test_server.Start());
7405
7406 MockExpectCTReporter reporter;
7407 TransportSecurityState transport_security_state;
7408 transport_security_state.SetExpectCTReporter(&reporter);
7409
7410 // Set up a MockCertVerifier to accept the certificate that the server sends.
7411 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7412 ASSERT_TRUE(cert);
7413 MockCertVerifier cert_verifier;
7414 CertVerifyResult verify_result;
7415 verify_result.verified_cert = cert;
7416 verify_result.is_issued_by_known_root = true;
7417 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7418
7419 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7420 // compliance.
7421 DoNothingCTVerifier ct_verifier;
7422 MockCTPolicyEnforcer ct_policy_enforcer;
7423 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547424 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517425
7426 TestNetworkDelegate network_delegate;
7427 // Use a MockHostResolver (which by default maps all hosts to
7428 // 127.0.0.1).
7429 MockHostResolver host_resolver;
7430 TestURLRequestContext context(true);
7431 context.set_host_resolver(&host_resolver);
7432 context.set_transport_security_state(&transport_security_state);
7433 context.set_network_delegate(&network_delegate);
7434 context.set_cert_verifier(&cert_verifier);
7435 context.set_cert_transparency_verifier(&ct_verifier);
7436 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7437 context.Init();
7438
7439 // Now send a request to trigger the header processing.
7440 TestDelegate d;
7441 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7442 std::unique_ptr<URLRequest> request(context.CreateRequest(
7443 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7444 request->Start();
Wez2a31b222018-06-07 22:07:157445 d.RunUntilComplete();
Emily Stark4cfecf072017-08-08 01:05:517446
7447 TransportSecurityState::ExpectCTState state;
7448 ASSERT_TRUE(
7449 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7450 EXPECT_TRUE(state.enforce);
7451 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7452}
7453
mmenkefd9d15c2017-06-29 13:45:547454#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477455
mmenkefd9d15c2017-06-29 13:45:547456#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:417457namespace {
7458
7459class TestReportingService : public ReportingService {
7460 public:
7461 struct Header {
7462 GURL url;
7463 std::string header_value;
7464 };
7465
juliatuttle2b8dd2d12017-04-12 21:27:417466 const std::vector<Header>& headers() { return headers_; }
7467
juliatuttle1d92f0152017-04-28 17:19:217468 // ReportingService implementation:
7469
Chris Watkins7a41d3552017-12-01 02:13:277470 ~TestReportingService() override = default;
juliatuttle1d92f0152017-04-28 17:19:217471
juliatuttle2b8dd2d12017-04-12 21:27:417472 void QueueReport(const GURL& url,
7473 const std::string& group,
7474 const std::string& type,
Julia Tuttle107e30672018-03-29 18:48:427475 std::unique_ptr<const base::Value> body,
7476 int depth) override {
juliatuttle2b8dd2d12017-04-12 21:27:417477 NOTIMPLEMENTED();
7478 }
7479
7480 void ProcessHeader(const GURL& url,
7481 const std::string& header_value) override {
7482 headers_.push_back({url, header_value});
7483 }
7484
Julia Tuttle227a6ff2017-12-19 19:44:247485 void RemoveBrowsingData(int data_type_mask,
7486 const base::RepeatingCallback<bool(const GURL&)>&
7487 origin_filter) override {
juliatuttleaeb1abc2017-05-04 21:14:387488 NOTIMPLEMENTED();
7489 }
7490
Eric Orthb812a442018-05-04 20:26:487491 void RemoveAllBrowsingData(int data_type_mask) override { NOTIMPLEMENTED(); }
7492
Julia Tuttle107e30672018-03-29 18:48:427493 int GetUploadDepth(const URLRequest& request) override {
Julia Tuttle4667c1c2017-12-19 18:27:387494 NOTIMPLEMENTED();
Julia Tuttle107e30672018-03-29 18:48:427495 return 0;
Julia Tuttle4667c1c2017-12-19 18:27:387496 }
7497
Julia Tuttle91a655d2018-01-26 18:03:037498 const ReportingPolicy& GetPolicy() const override {
7499 static ReportingPolicy dummy_policy_;
7500 NOTIMPLEMENTED();
7501 return dummy_policy_;
7502 }
7503
juliatuttle2b8dd2d12017-04-12 21:27:417504 private:
7505 std::vector<Header> headers_;
7506};
7507
7508std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7509 const test_server::HttpRequest& request) {
7510 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7511 new test_server::BasicHttpResponse);
7512 http_response->set_code(HTTP_OK);
7513 http_response->AddCustomHeader("Report-To", "foo");
7514 http_response->AddCustomHeader("Report-To", "bar");
7515 return std::move(http_response);
7516}
7517
7518} // namespace
7519
7520TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
Julia Tuttle7005a2a2017-12-08 21:01:187521 http_test_server()->RegisterRequestHandler(
7522 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417523 ASSERT_TRUE(http_test_server()->Start());
7524 GURL request_url = http_test_server()->GetURL("/");
7525
7526 TestNetworkDelegate network_delegate;
7527 TestURLRequestContext context(true);
7528 context.set_network_delegate(&network_delegate);
7529 context.Init();
7530
7531 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167532 std::unique_ptr<URLRequest> request(context.CreateRequest(
7533 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417534 request->Start();
Wez2a31b222018-06-07 22:07:157535 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417536}
7537
7538TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
Julia Tuttle7005a2a2017-12-08 21:01:187539 http_test_server()->RegisterRequestHandler(
7540 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417541 ASSERT_TRUE(http_test_server()->Start());
7542 GURL request_url = http_test_server()->GetURL("/");
7543
7544 TestNetworkDelegate network_delegate;
7545 TestReportingService reporting_service;
7546 TestURLRequestContext context(true);
7547 context.set_network_delegate(&network_delegate);
7548 context.set_reporting_service(&reporting_service);
7549 context.Init();
7550
7551 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167552 std::unique_ptr<URLRequest> request(context.CreateRequest(
7553 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417554 request->Start();
Wez2a31b222018-06-07 22:07:157555 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417556
7557 EXPECT_TRUE(reporting_service.headers().empty());
7558}
7559
7560TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7561 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187562 https_test_server.RegisterRequestHandler(
7563 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417564 ASSERT_TRUE(https_test_server.Start());
7565 GURL request_url = https_test_server.GetURL("/");
7566
7567 TestNetworkDelegate network_delegate;
7568 TestReportingService reporting_service;
7569 TestURLRequestContext context(true);
7570 context.set_network_delegate(&network_delegate);
7571 context.set_reporting_service(&reporting_service);
7572 context.Init();
7573
7574 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167575 std::unique_ptr<URLRequest> request(context.CreateRequest(
7576 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417577 request->Start();
Wez2a31b222018-06-07 22:07:157578 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417579
7580 ASSERT_EQ(1u, reporting_service.headers().size());
7581 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7582 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7583}
7584
Julia Tuttlef9b74062017-07-27 14:44:057585TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417586 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7587 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187588 https_test_server.RegisterRequestHandler(
7589 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417590 ASSERT_TRUE(https_test_server.Start());
7591 GURL request_url = https_test_server.GetURL("/");
7592
7593 TestNetworkDelegate network_delegate;
7594 TestReportingService reporting_service;
7595 TestURLRequestContext context(true);
7596 context.set_network_delegate(&network_delegate);
7597 context.set_reporting_service(&reporting_service);
7598 context.Init();
7599
7600 TestDelegate d;
7601 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167602 std::unique_ptr<URLRequest> request(context.CreateRequest(
7603 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417604 request->Start();
Wez2a31b222018-06-07 22:07:157605 d.RunUntilComplete();
juliatuttle2b8dd2d12017-04-12 21:27:417606
7607 EXPECT_TRUE(d.have_certificate_errors());
7608 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7609 EXPECT_TRUE(reporting_service.headers().empty());
7610}
Julia Tuttlefadc26d2017-10-13 18:12:297611
7612// Network Error Logging is dependent on the Reporting API, so only run NEL
7613// tests if Reporting is enabled in the build.
tommycli59a63432015-11-06 00:10:557614
Julia Tuttlef9b74062017-07-27 14:44:057615namespace {
7616
Julia Tuttlecba7d222018-02-23 19:37:277617class TestNetworkErrorLoggingService : public NetworkErrorLoggingService {
Julia Tuttlef9b74062017-07-27 14:44:057618 public:
7619 struct Header {
Chris Watkins7a41d3552017-12-01 02:13:277620 Header() = default;
7621 ~Header() = default;
Julia Tuttlef9b74062017-07-27 14:44:057622
7623 url::Origin origin;
7624 std::string value;
7625 };
7626
Julia Tuttlef9b74062017-07-27 14:44:057627 const std::vector<Header>& headers() { return headers_; }
Douglas Creager1f56bbe2018-02-17 03:58:407628 const std::vector<RequestDetails>& errors() { return errors_; }
Julia Tuttlef9b74062017-07-27 14:44:057629
Julia Tuttlecba7d222018-02-23 19:37:277630 // NetworkErrorLoggingService implementation:
Julia Tuttlef9b74062017-07-27 14:44:057631
Julia Tuttlecba7d222018-02-23 19:37:277632 ~TestNetworkErrorLoggingService() override = default;
Julia Tuttlef9b74062017-07-27 14:44:057633
7634 void OnHeader(const url::Origin& origin, const std::string& value) override {
7635 Header header;
7636 header.origin = origin;
7637 header.value = value;
7638 headers_.push_back(header);
7639 }
7640
Douglas Creager1f56bbe2018-02-17 03:58:407641 void OnRequest(const RequestDetails& details) override {
Julia Tuttleb0d45472017-09-25 20:14:437642 errors_.push_back(details);
Julia Tuttlef9b74062017-07-27 14:44:057643 }
7644
Julia Tuttlea059db82018-01-04 18:46:437645 void RemoveBrowsingData(const base::RepeatingCallback<bool(const GURL&)>&
7646 origin_filter) override {
7647 NOTREACHED();
7648 }
7649
Eric Orth26a408f2018-05-09 15:43:407650 void RemoveAllBrowsingData() override { NOTREACHED(); }
7651
Julia Tuttlef9b74062017-07-27 14:44:057652 private:
7653 std::vector<Header> headers_;
Douglas Creager1f56bbe2018-02-17 03:58:407654 std::vector<RequestDetails> errors_;
Julia Tuttlef9b74062017-07-27 14:44:057655};
7656
7657std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7658 const test_server::HttpRequest& request) {
7659 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7660 new test_server::BasicHttpResponse);
7661 http_response->set_code(HTTP_OK);
Julia Tuttlecba7d222018-02-23 19:37:277662 http_response->AddCustomHeader(NetworkErrorLoggingService::kHeaderName,
Julia Tuttlef9b74062017-07-27 14:44:057663 "foo");
7664 return std::move(http_response);
7665}
7666
Julia Tuttle7005a2a2017-12-08 21:01:187667std::unique_ptr<test_server::HttpResponse> SendEmptyResponse(
7668 const test_server::HttpRequest& request) {
Gyuyoung Kimb480aba2018-01-27 07:00:047669 return std::make_unique<test_server::RawHttpResponse>("", "");
Julia Tuttle7005a2a2017-12-08 21:01:187670}
7671
Julia Tuttlef9b74062017-07-27 14:44:057672} // namespace
7673
7674TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
Julia Tuttle7005a2a2017-12-08 21:01:187675 http_test_server()->RegisterRequestHandler(
7676 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057677 ASSERT_TRUE(http_test_server()->Start());
7678 GURL request_url = http_test_server()->GetURL("/");
7679
7680 TestNetworkDelegate network_delegate;
7681 TestURLRequestContext context(true);
7682 context.set_network_delegate(&network_delegate);
7683 context.Init();
7684
7685 TestDelegate d;
7686 std::unique_ptr<URLRequest> request(context.CreateRequest(
7687 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7688 request->Start();
Wez2a31b222018-06-07 22:07:157689 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057690}
7691
7692TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
Julia Tuttle7005a2a2017-12-08 21:01:187693 http_test_server()->RegisterRequestHandler(
7694 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057695 ASSERT_TRUE(http_test_server()->Start());
7696 GURL request_url = http_test_server()->GetURL("/");
7697
7698 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277699 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057700 TestURLRequestContext context(true);
7701 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277702 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057703 context.Init();
7704
7705 TestDelegate d;
7706 std::unique_ptr<URLRequest> request(context.CreateRequest(
7707 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7708 request->Start();
Wez2a31b222018-06-07 22:07:157709 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057710
Julia Tuttlecba7d222018-02-23 19:37:277711 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057712}
7713
7714TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7715 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187716 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057717 ASSERT_TRUE(https_test_server.Start());
7718 GURL request_url = https_test_server.GetURL("/");
7719
7720 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277721 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057722 TestURLRequestContext context(true);
7723 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277724 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057725 context.Init();
7726
7727 TestDelegate d;
7728 std::unique_ptr<URLRequest> request(context.CreateRequest(
7729 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7730 request->Start();
Wez2a31b222018-06-07 22:07:157731 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057732
Julia Tuttlecba7d222018-02-23 19:37:277733 ASSERT_EQ(1u, nel_service.headers().size());
7734 EXPECT_EQ(url::Origin::Create(request_url), nel_service.headers()[0].origin);
7735 EXPECT_EQ("foo", nel_service.headers()[0].value);
Julia Tuttlef9b74062017-07-27 14:44:057736}
7737
7738TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7739 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7740 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187741 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057742 ASSERT_TRUE(https_test_server.Start());
7743 GURL request_url = https_test_server.GetURL("/");
7744
7745 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277746 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057747 TestURLRequestContext context(true);
7748 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277749 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057750 context.Init();
7751
7752 TestDelegate d;
7753 d.set_allow_certificate_errors(true);
7754 std::unique_ptr<URLRequest> request(context.CreateRequest(
7755 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7756 request->Start();
Wez2a31b222018-06-07 22:07:157757 d.RunUntilComplete();
Julia Tuttlef9b74062017-07-27 14:44:057758
7759 EXPECT_TRUE(d.have_certificate_errors());
7760 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
Julia Tuttlecba7d222018-02-23 19:37:277761 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057762}
7763
Julia Tuttlefadc26d2017-10-13 18:12:297764TEST_F(URLRequestTestHTTP, DontForwardErrorToNelNoDelegate) {
7765 URLRequestFailedJob::AddUrlHandler();
7766
7767 GURL request_url =
7768 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7769
7770 TestNetworkDelegate network_delegate;
7771 TestURLRequestContext context(true);
7772 context.set_network_delegate(&network_delegate);
7773 context.Init();
7774
7775 TestDelegate d;
7776 std::unique_ptr<URLRequest> request(context.CreateRequest(
7777 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7778 request->Start();
Wez2a31b222018-06-07 22:07:157779 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297780
7781 URLRequestFilter::GetInstance()->ClearHandlers();
7782}
7783
7784// TODO(juliatuttle): Figure out whether this restriction should be in place,
7785// and either implement it or remove this test.
7786TEST_F(URLRequestTestHTTP, DISABLED_DontForwardErrorToNelHttp) {
7787 URLRequestFailedJob::AddUrlHandler();
7788
7789 GURL request_url =
7790 URLRequestFailedJob::GetMockHttpUrl(ERR_CONNECTION_REFUSED);
7791
7792 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277793 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297794 TestURLRequestContext context(true);
7795 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277796 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297797 context.Init();
7798
7799 TestDelegate d;
7800 std::unique_ptr<URLRequest> request(context.CreateRequest(
7801 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7802 request->Start();
Wez2a31b222018-06-07 22:07:157803 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297804
Julia Tuttlecba7d222018-02-23 19:37:277805 EXPECT_TRUE(nel_service.errors().empty());
Julia Tuttlefadc26d2017-10-13 18:12:297806
7807 URLRequestFilter::GetInstance()->ClearHandlers();
7808}
7809
Julia Tuttle7005a2a2017-12-08 21:01:187810TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Mock) {
Julia Tuttlefadc26d2017-10-13 18:12:297811 URLRequestFailedJob::AddUrlHandler();
7812
7813 GURL request_url =
7814 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7815
7816 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277817 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297818 TestURLRequestContext context(true);
7819 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277820 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297821 context.Init();
7822
7823 TestDelegate d;
7824 std::unique_ptr<URLRequest> request(context.CreateRequest(
7825 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7826 request->Start();
Wez2a31b222018-06-07 22:07:157827 d.RunUntilComplete();
Julia Tuttlefadc26d2017-10-13 18:12:297828
Julia Tuttlecba7d222018-02-23 19:37:277829 ASSERT_EQ(1u, nel_service.errors().size());
7830 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7831 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7832 EXPECT_EQ(ERR_CONNECTION_REFUSED, nel_service.errors()[0].type);
Julia Tuttlefadc26d2017-10-13 18:12:297833
7834 URLRequestFilter::GetInstance()->ClearHandlers();
7835}
7836
Julia Tuttle7005a2a2017-12-08 21:01:187837// Also test with a real server, to exercise interactions with
7838// URLRequestHttpJob.
7839TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Real) {
7840 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7841 https_test_server.RegisterRequestHandler(
7842 base::BindRepeating(&SendEmptyResponse));
7843 ASSERT_TRUE(https_test_server.Start());
7844 GURL request_url = https_test_server.GetURL("/");
7845
7846 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277847 TestNetworkErrorLoggingService nel_service;
Julia Tuttle7005a2a2017-12-08 21:01:187848 TestURLRequestContext context(true);
7849 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277850 context.set_network_error_logging_service(&nel_service);
Julia Tuttle7005a2a2017-12-08 21:01:187851 context.Init();
7852
7853 TestDelegate d;
7854 std::unique_ptr<URLRequest> request(context.CreateRequest(
7855 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7856 request->Start();
Wez2a31b222018-06-07 22:07:157857 d.RunUntilComplete();
Julia Tuttle7005a2a2017-12-08 21:01:187858
Julia Tuttlecba7d222018-02-23 19:37:277859 ASSERT_EQ(1u, nel_service.errors().size());
7860 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7861 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7862 EXPECT_EQ(ERR_EMPTY_RESPONSE, nel_service.errors()[0].type);
Julia Tuttle7005a2a2017-12-08 21:01:187863}
7864
Julia Tuttlefadc26d2017-10-13 18:12:297865#endif // BUILDFLAG(ENABLE_REPORTING)
7866
[email protected]316c1e5e2012-09-12 15:17:447867TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557868 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447869
7870 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367871 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557872 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167873 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197874 req->Start();
Wez2a31b222018-06-07 22:07:157875 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447876
7877 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197878 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447879 EXPECT_EQ("text/html", mime_type);
7880
7881 std::string charset;
[email protected]f7022f32014-08-21 16:32:197882 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447883 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197884 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447885}
7886
[email protected]02494ec2014-05-07 15:05:297887TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347888 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347889 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347890 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027891 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347892
7893 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507894 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347895}
7896
brettwa1228ebb2016-10-28 03:51:347897#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297898TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7899 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7900 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457901 FileProtocolHandler file_protocol_handler(
7902 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297903 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7904
7905 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507906 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297907}
7908
[email protected]588614c22013-08-16 00:09:027909TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557910 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447911
7912 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367913 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557914 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167915 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197916 req->Start();
Wez2a31b222018-06-07 22:07:157917 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447918
maksim.sisovb53724b52016-09-16 05:30:507919 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307920
7921 // The redirect should have been rejected before reporting it to the caller.
7922 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447923}
brettwa1228ebb2016-10-28 03:51:347924#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447925
[email protected]588614c22013-08-16 00:09:027926TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557927 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027928
7929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367930 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557931 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167932 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197933 req->Start();
Wez2a31b222018-06-07 22:07:157934 d.RunUntilComplete();
[email protected]588614c22013-08-16 00:09:027935
maksim.sisovb53724b52016-09-16 05:30:507936 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307937
7938 // The redirect should have been rejected before reporting it to the
7939 // caller. See https://crbug.com/723796
7940 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027941}
7942
davidbend894710b2017-06-06 19:28:307943// Test that redirects to invalid URLs are rejected. See
7944// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447945TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557946 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447947
7948 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367949 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557950 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167951 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197952 req->Start();
Wez2a31b222018-06-07 22:07:157953 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:447954
davidbend894710b2017-06-06 19:28:307955 EXPECT_EQ(1, d.response_started_count());
7956 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7957
7958 // The redirect should have been rejected before reporting it to the caller.
7959 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447960}
7961
[email protected]e50efea2014-03-24 18:41:007962// Make sure redirects are cached, despite not reading their bodies.
7963TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557964 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007965 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557966 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007967
7968 {
7969 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167970 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7971 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197972 req->Start();
Wez2a31b222018-06-07 22:07:157973 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:507974 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007975 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557976 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007977 }
7978
7979 {
7980 TestDelegate d;
7981 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167982 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7983 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197984 req->Start();
Wez2a31b222018-06-07 22:07:157985 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007986
7987 EXPECT_EQ(1, d.received_redirect_count());
7988 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197989 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007990
Chong Zhang7607f1f2018-06-01 20:52:207991 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:157992 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:007993 EXPECT_EQ(1, d.received_redirect_count());
7994 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507995 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557996 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007997 }
7998}
7999
8000// Make sure a request isn't cached when a NetworkDelegate forces a redirect
8001// when the headers are read, since the body won't have been read.
8002TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:558003 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:008004 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:558005 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:008006
8007 {
8008 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:558009 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:008010 default_network_delegate_.set_redirect_on_headers_received_url(
8011 redirect_to_url);
8012
8013 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168014 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8015 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198016 req->Start();
Wez2a31b222018-06-07 22:07:158017 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508018 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:008019 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198020 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:008021 }
8022
8023 {
8024 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168025 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8026 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198027 req->Start();
Wez2a31b222018-06-07 22:07:158028 d.RunUntilComplete();
[email protected]e50efea2014-03-24 18:41:008029
maksim.sisovb53724b52016-09-16 05:30:508030 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198031 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:008032 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198033 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:008034 }
8035}
8036
[email protected]5f714132014-03-26 10:41:168037// Tests that redirection to an unsafe URL is allowed when it has been marked as
8038// safe.
8039TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:558040 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168041
8042 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
8043 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8044 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8045
8046 TestDelegate d;
8047 {
danakj8522a25b2016-04-16 00:17:368048 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168049 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8050 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168051
[email protected]f7022f32014-08-21 16:32:198052 r->Start();
Wez2a31b222018-06-07 22:07:158053 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168054
maksim.sisovb53724b52016-09-16 05:30:508055 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198056 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:198057 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:168058 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
8059 }
8060}
8061
8062// Tests that a redirect to a different unsafe URL is blocked, even after adding
8063// some other URL to the whitelist.
8064TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:558065 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168066
8067 GURL unsafe_url("data:text/html,something");
8068 GURL different_unsafe_url("data:text/html,something-else");
8069 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8070 default_network_delegate_.set_allowed_unsafe_redirect_url(
8071 different_unsafe_url);
8072
8073 TestDelegate d;
8074 {
danakj8522a25b2016-04-16 00:17:368075 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168076 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8077 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168078
[email protected]f7022f32014-08-21 16:32:198079 r->Start();
Wez2a31b222018-06-07 22:07:158080 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168081
maksim.sisovb53724b52016-09-16 05:30:508082 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:308083
8084 // The redirect should have been rejected before reporting it to the caller.
8085 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:168086 }
8087}
8088
[email protected]5f714132014-03-26 10:41:168089// Redirects from an URL with fragment to an unsafe URL with fragment should
8090// be allowed, and the reference fragment of the target URL should be preserved.
8091TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:558092 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168093
tommycli59a63432015-11-06 00:10:558094 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:168095 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8096 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8097
8098 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8099 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8100
8101 TestDelegate d;
8102 {
rhalavatib7bd7c792017-04-27 05:25:168103 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8104 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168105
[email protected]f7022f32014-08-21 16:32:198106 r->Start();
Wez2a31b222018-06-07 22:07:158107 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168108
[email protected]f7022f32014-08-21 16:32:198109 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508110 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198111 EXPECT_EQ(original_url, r->original_url());
8112 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:168113 }
8114}
8115
8116// When a delegate has specified a safe redirect URL, but it does not match the
8117// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:148118TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:558119 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168120
tommycli59a63432015-11-06 00:10:558121 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168122 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:558123 GURL redirect_url(http_test_server()->GetURL("/target"));
8124 GURL expected_redirect_url(
8125 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168126
8127 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8128 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8129
8130 TestDelegate d;
8131 {
rhalavatib7bd7c792017-04-27 05:25:168132 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8133 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168134
[email protected]f7022f32014-08-21 16:32:198135 r->Start();
Wez2a31b222018-06-07 22:07:158136 d.RunUntilComplete();
[email protected]5f714132014-03-26 10:41:168137
[email protected]f7022f32014-08-21 16:32:198138 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508139 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198140 EXPECT_EQ(original_url, r->original_url());
8141 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:168142 }
8143}
8144
[email protected]f878230e2014-04-03 15:36:148145// When a delegate has specified a safe redirect URL, assume that the redirect
8146// URL should not be changed. In particular, the reference fragment should not
8147// be modified.
8148TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558149 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148150
tommycli59a63432015-11-06 00:10:558151 GURL original_url(
8152 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:148153 GURL redirect_url("data:text/html,expect-no-reference-fragment");
8154
8155 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8156 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
8157
8158 TestDelegate d;
8159 {
rhalavatib7bd7c792017-04-27 05:25:168160 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8161 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148162
[email protected]f7022f32014-08-21 16:32:198163 r->Start();
Wez2a31b222018-06-07 22:07:158164 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148165
[email protected]f7022f32014-08-21 16:32:198166 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508167 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198168 EXPECT_EQ(original_url, r->original_url());
8169 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148170 }
8171}
8172
8173// When a URLRequestRedirectJob is created, the redirection must be followed and
8174// the reference fragment of the target URL must not be modified.
8175TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558176 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148177
tommycli59a63432015-11-06 00:10:558178 GURL original_url(
8179 http_test_server()->GetURL("/original#should-not-be-appended"));
8180 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:148181
8182 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168183 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8184 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148185
danakj8522a25b2016-04-16 00:17:368186 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:198187 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:428188 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8189 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:148190
[email protected]f7022f32014-08-21 16:32:198191 r->Start();
Wez2a31b222018-06-07 22:07:158192 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148193
maksim.sisovb53724b52016-09-16 05:30:508194 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198195 EXPECT_EQ(original_url, r->original_url());
8196 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148197}
8198
lizeb5120f6dc2016-02-19 09:29:448199TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
8200 ASSERT_TRUE(http_test_server()->Start());
8201
8202 const std::string referrer("foobar://totally.legit.referrer");
8203 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368204 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168205 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8206 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:448207 req->SetReferrer(referrer);
8208 req->Start();
Wez2a31b222018-06-07 22:07:158209 d.RunUntilComplete();
lizeb5120f6dc2016-02-19 09:29:448210
8211 EXPECT_EQ(std::string("None"), d.data_received());
8212}
8213
[email protected]316c1e5e2012-09-12 15:17:448214TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558215 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448216
8217 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368218 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168219 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8220 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198221 req->SetReferrer("http://user:[email protected]/");
8222 req->Start();
Wez2a31b222018-06-07 22:07:158223 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448224
8225 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8226}
8227
[email protected]99ecf6e2013-04-10 22:46:138228TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558229 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138230
8231 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368232 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168233 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8234 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198235 req->SetReferrer("http://foo.com/test#fragment");
8236 req->Start();
Wez2a31b222018-06-07 22:07:158237 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138238
8239 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8240}
8241
8242TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558243 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138244
8245 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368246 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168247 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8248 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198249 req->SetReferrer("http://foo.com/test#fragment");
8250 req->SetReferrer("");
8251 req->Start();
Wez2a31b222018-06-07 22:07:158252 d.RunUntilComplete();
[email protected]99ecf6e2013-04-10 22:46:138253
8254 EXPECT_EQ(std::string("None"), d.data_received());
8255}
8256
[email protected]316c1e5e2012-09-12 15:17:448257TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558258 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448259
8260 TestDelegate d;
8261 {
8262 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:368263 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168264 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8265 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198266 req->Start();
Wez2a31b222018-06-07 22:07:158267 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448268
8269 EXPECT_EQ(1, d.response_started_count());
8270 EXPECT_EQ(0, d.bytes_received());
8271 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508272 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448273 }
8274}
8275
8276TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558277 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448278
8279 TestDelegate d;
8280 {
8281 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558282 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168283 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8284 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048285
[email protected]f7022f32014-08-21 16:32:198286 req->Start();
Wez2a31b222018-06-07 22:07:158287 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448288
8289 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238290 EXPECT_TRUE(d.have_full_request_headers());
8291 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8292 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448293
Chong Zhang7607f1f2018-06-01 20:52:208294 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:158295 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448296
8297 EXPECT_EQ(1, d.response_started_count());
8298 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508299 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448300
[email protected]6cdfd7f2013-02-08 20:40:158301 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198302 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478303 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448304 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8305
8306 std::string contents;
[email protected]82f84b92013-08-30 18:23:508307 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448308 EXPECT_EQ(contents, d.data_received());
8309 }
8310}
8311
[email protected]79e1fd62013-06-20 06:50:048312TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558313 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048314
8315 TestDelegate d;
8316 {
8317 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558318 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168319 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8320 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048321
8322 EXPECT_FALSE(d.have_full_request_headers());
8323
[email protected]f7022f32014-08-21 16:32:198324 req->Start();
Wez2a31b222018-06-07 22:07:158325 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048326
8327 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048328
Chong Zhang7607f1f2018-06-01 20:52:208329 req->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:158330 d.RunUntilComplete();
[email protected]79e1fd62013-06-20 06:50:048331
tommycli59a63432015-11-06 00:10:558332 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048333 EXPECT_EQ(1, d.response_started_count());
8334 EXPECT_TRUE(d.have_full_request_headers());
8335 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8336 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508337 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048338
8339 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198340 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478341 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048342 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8343
8344 std::string contents;
[email protected]82f84b92013-08-30 18:23:508345 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048346 EXPECT_EQ(contents, d.data_received());
8347 }
8348}
8349
Chong Zhang7607f1f2018-06-01 20:52:208350TEST_F(URLRequestTestHTTP, DeferredRedirect_ModifiedRequestHeaders) {
8351 ASSERT_TRUE(http_test_server()->Start());
8352
8353 TestDelegate d;
8354 {
8355 d.set_quit_on_redirect(true);
8356 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
8357 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8358 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
8359
8360 // Set initial headers for the request.
8361 req->SetExtraRequestHeaderByName("Header1", "Value1", true /* overwrite */);
8362 req->SetExtraRequestHeaderByName("Header2", "Value2", true /* overwrite */);
8363
8364 req->Start();
Wez2a31b222018-06-07 22:07:158365 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208366
8367 // Initial request should only have initial headers.
8368 EXPECT_EQ(1, d.received_redirect_count());
8369 EXPECT_TRUE(d.have_full_request_headers());
8370 const HttpRequestHeaders& sent_headers1 = d.full_request_headers();
8371 std::string sent_value;
8372 EXPECT_TRUE(sent_headers1.GetHeader("Header1", &sent_value));
8373 EXPECT_EQ("Value1", sent_value);
8374 EXPECT_TRUE(sent_headers1.GetHeader("Header2", &sent_value));
8375 EXPECT_EQ("Value2", sent_value);
8376 EXPECT_FALSE(sent_headers1.GetHeader("Header3", &sent_value));
8377 d.ClearFullRequestHeaders();
8378
8379 // Overwrite Header2 and add Header3.
8380 net::HttpRequestHeaders modified_request_headers;
8381 modified_request_headers.SetHeader("Header2", "");
8382 modified_request_headers.SetHeader("Header3", "Value3");
8383
8384 req->FollowDeferredRedirect(modified_request_headers);
Wez2a31b222018-06-07 22:07:158385 d.RunUntilComplete();
Chong Zhang7607f1f2018-06-01 20:52:208386
8387 EXPECT_EQ(1, d.response_started_count());
8388 EXPECT_FALSE(d.received_data_before_response());
8389 EXPECT_EQ(OK, d.request_status());
8390
8391 // Redirected request should also have modified headers.
8392 EXPECT_TRUE(d.have_full_request_headers());
8393 const HttpRequestHeaders& sent_headers2 = d.full_request_headers();
8394 EXPECT_TRUE(sent_headers2.GetHeader("Header1", &sent_value));
8395 EXPECT_EQ("Value1", sent_value);
8396 EXPECT_TRUE(sent_headers2.GetHeader("Header2", &sent_value));
8397 EXPECT_EQ("", sent_value);
8398 EXPECT_TRUE(sent_headers2.GetHeader("Header3", &sent_value));
8399 EXPECT_EQ("Value3", sent_value);
8400 }
8401}
8402
[email protected]316c1e5e2012-09-12 15:17:448403TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558404 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448405
8406 TestDelegate d;
8407 {
8408 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:368409 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168410 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8411 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198412 req->Start();
Wez2a31b222018-06-07 22:07:158413 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448414
8415 EXPECT_EQ(1, d.received_redirect_count());
8416
[email protected]f7022f32014-08-21 16:32:198417 req->Cancel();
Wez2a31b222018-06-07 22:07:158418 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448419
8420 EXPECT_EQ(1, d.response_started_count());
8421 EXPECT_EQ(0, d.bytes_received());
8422 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508423 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448424 }
8425}
8426
8427TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558428 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448429
[email protected]3b23a222013-05-15 21:33:258430 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448431 {
8432 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368433 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558434 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168435 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448436 HttpRequestHeaders headers;
8437 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198438 req->SetExtraRequestHeaders(headers);
8439 req->Start();
Wez2a31b222018-06-07 22:07:158440 d.RunUntilComplete();
[email protected]3b23a222013-05-15 21:33:258441
8442 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198443 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258444 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448445 }
8446
[email protected]3b23a222013-05-15 21:33:258447 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448448 {
8449 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368450 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558451 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168452 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448453 HttpRequestHeaders headers;
8454 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198455 req->SetExtraRequestHeaders(headers);
8456 req->Start();
Wez2a31b222018-06-07 22:07:158457 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448458
[email protected]f7022f32014-08-21 16:32:198459 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258460
8461 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198462 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258463 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448464 }
8465
[email protected]3b23a222013-05-15 21:33:258466 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448467 {
8468 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368469 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558470 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168471 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448472 HttpRequestHeaders headers;
8473 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198474 req->SetExtraRequestHeaders(headers);
8475 req->Start();
Wez2a31b222018-06-07 22:07:158476 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448477
[email protected]f7022f32014-08-21 16:32:198478 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258479
8480 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198481 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258482 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448483 }
8484}
8485
8486TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558487 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448488
8489 // populate the cache
8490 {
8491 TestDelegate d;
8492 d.set_credentials(AuthCredentials(kUser, kSecret));
8493
danakj8522a25b2016-04-16 00:17:368494 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168495 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8496 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198497 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448498
Wez2a31b222018-06-07 22:07:158499 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448500
8501 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8502 }
8503
8504 // repeat request with end-to-end validation. since auth-basic results in a
8505 // cachable page, we expect this test to result in a 304. in which case, the
8506 // response should be fetched from the cache.
8507 {
8508 TestDelegate d;
8509 d.set_credentials(AuthCredentials(kUser, kSecret));
8510
danakj8522a25b2016-04-16 00:17:368511 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168512 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8513 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198514 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8515 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448516
Wez2a31b222018-06-07 22:07:158517 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448518
8519 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8520
8521 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198522 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448523 }
8524}
8525
8526// Check that Set-Cookie headers in 401 responses are respected.
8527// http://crbug.com/6450
8528TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558529 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448530
8531 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558532 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448533
8534 // Request a page that will give a 401 containing a Set-Cookie header.
8535 // Verify that when the transaction is restarted, it includes the new cookie.
8536 {
[email protected]ceefd7fd2012-11-29 00:36:248537 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448538 TestURLRequestContext context(true);
8539 context.set_network_delegate(&network_delegate);
8540 context.Init();
8541
8542 TestDelegate d;
8543 d.set_credentials(AuthCredentials(kUser, kSecret));
8544
danakj8522a25b2016-04-16 00:17:368545 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168546 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8547 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198548 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448549
Wez2a31b222018-06-07 22:07:158550 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448551
8552 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8553
8554 // Make sure we sent the cookie in the restarted transaction.
8555 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8556 != std::string::npos);
8557 }
8558
8559 // Same test as above, except this time the restart is initiated earlier
8560 // (without user intervention since identity is embedded in the URL).
8561 {
[email protected]ceefd7fd2012-11-29 00:36:248562 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448563 TestURLRequestContext context(true);
8564 context.set_network_delegate(&network_delegate);
8565 context.Init();
8566
8567 TestDelegate d;
8568
8569 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188570 replacements.SetUsernameStr("user2");
8571 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448572 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8573
rhalavatib7bd7c792017-04-27 05:25:168574 std::unique_ptr<URLRequest> r(context.CreateRequest(
8575 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198576 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448577
Wez2a31b222018-06-07 22:07:158578 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448579
8580 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8581
8582 // Make sure we sent the cookie in the restarted transaction.
8583 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8584 != std::string::npos);
8585 }
8586}
8587
[email protected]58e32bb2013-01-21 18:23:258588// Tests that load timing works as expected with auth and the cache.
8589TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558590 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258591
8592 // populate the cache
8593 {
8594 TestDelegate d;
8595 d.set_credentials(AuthCredentials(kUser, kSecret));
8596
danakj8522a25b2016-04-16 00:17:368597 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168598 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8599 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198600 r->Start();
[email protected]58e32bb2013-01-21 18:23:258601
Wez2a31b222018-06-07 22:07:158602 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258603
8604 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8605
8606 LoadTimingInfo load_timing_info_before_auth;
8607 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8608 &load_timing_info_before_auth));
8609 TestLoadTimingNotReused(load_timing_info_before_auth,
8610 CONNECT_TIMING_HAS_DNS_TIMES);
8611
8612 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198613 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258614 // The test server does not support keep alive sockets, so the second
8615 // request with auth should use a new socket.
8616 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8617 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8618 load_timing_info.socket_log_id);
8619 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8620 load_timing_info.connect_timing.connect_start);
8621 }
8622
[email protected]3b23a222013-05-15 21:33:258623 // Repeat request with end-to-end validation. Since auth-basic results in a
8624 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258625 // response should be fetched from the cache.
8626 {
8627 TestDelegate d;
8628 d.set_credentials(AuthCredentials(kUser, kSecret));
8629
danakj8522a25b2016-04-16 00:17:368630 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168631 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8632 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198633 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8634 r->Start();
[email protected]58e32bb2013-01-21 18:23:258635
Wez2a31b222018-06-07 22:07:158636 d.RunUntilComplete();
[email protected]58e32bb2013-01-21 18:23:258637
8638 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8639
8640 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198641 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258642
[email protected]3b23a222013-05-15 21:33:258643 // Since there was a request that went over the wire, the load timing
8644 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258645 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198646 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258647 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258648 }
8649}
8650
[email protected]316c1e5e2012-09-12 15:17:448651// In this test, we do a POST which the server will 302 redirect.
8652// The subsequent transaction should use GET, and should not send the
8653// Content-Type header.
8654// http://code.google.com/p/chromium/issues/detail?id=843
8655TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558656 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448657
8658 const char kData[] = "hello world";
8659
8660 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368661 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168662 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8663 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198664 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078665 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448666
8667 // Set headers (some of which are specific to the POST).
8668 HttpRequestHeaders headers;
8669 headers.AddHeadersFromString(
8670 "Content-Type: multipart/form-data; "
8671 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8672 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8673 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8674 "Accept-Language: en-US,en\r\n"
8675 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8676 "Content-Length: 11\r\n"
8677 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198678 req->SetExtraRequestHeaders(headers);
8679 req->Start();
Wez2a31b222018-06-07 22:07:158680 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448681
8682 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198683 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448684 EXPECT_EQ("text/html", mime_type);
8685
8686 const std::string& data = d.data_received();
8687
8688 // Check that the post-specific headers were stripped:
8689 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8690 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498691 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448692
8693 // These extra request headers should not have been stripped.
8694 EXPECT_TRUE(ContainsString(data, "Accept:"));
8695 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8696 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8697}
8698
jww5fe460ff2015-03-28 00:22:518699// The following tests check that we handle mutating the request for HTTP
8700// redirects as expected.
8701// See https://crbug.com/56373, https://crbug.com/102130, and
8702// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448703
8704TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558705 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448706
tommycli59a63432015-11-06 00:10:558707 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518708 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558709 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448710
8711 HTTPRedirectMethodTest(url, "POST", "GET", true);
8712 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8713 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518714
8715 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8716 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498717 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8718 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8719 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408720 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8721 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448722}
8723
8724TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558725 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448726
tommycli59a63432015-11-06 00:10:558727 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518728 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558729 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448730
8731 HTTPRedirectMethodTest(url, "POST", "GET", true);
8732 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8733 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518734
8735 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8736 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498737 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8738 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8739 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408740 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8741 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448742}
8743
8744TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558745 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448746
tommycli59a63432015-11-06 00:10:558747 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518748 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558749 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448750
8751 HTTPRedirectMethodTest(url, "POST", "GET", true);
8752 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8753 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518754
Alex Clarke1e08882b32017-10-06 14:22:408755 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8756 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8757 std::string());
8758 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8759 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8760 std::string());
jww5fe460ff2015-03-28 00:22:518761 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8762 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408763 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8764 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8765 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8766 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8767 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498768 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8769 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8770 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408771 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8772 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448773}
8774
8775TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558776 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448777
tommycli59a63432015-11-06 00:10:558778 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518779 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558780 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448781
8782 HTTPRedirectMethodTest(url, "POST", "POST", true);
8783 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8784 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518785
8786 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8787 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8788 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8789 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408790 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8791 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448792}
8793
[email protected]0a17aab32014-04-24 03:32:378794TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558795 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378796
tommycli59a63432015-11-06 00:10:558797 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518798 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558799 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378800
8801 HTTPRedirectMethodTest(url, "POST", "POST", true);
8802 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8803 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518804
8805 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8806 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8807 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8808 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408809 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8810 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378811}
8812
8813// Make sure that 308 responses without bodies are not treated as redirects.
8814// Certain legacy apis that pre-date the response code expect this behavior
8815// (Like Google Drive).
8816TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558817 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378818
8819 TestDelegate d;
tommycli59a63432015-11-06 00:10:558820 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378821
rhalavatib7bd7c792017-04-27 05:25:168822 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8823 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378824
[email protected]f7022f32014-08-21 16:32:198825 request->Start();
Wez2a31b222018-06-07 22:07:158826 d.RunUntilComplete();
maksim.sisovb53724b52016-09-16 05:30:508827 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378828 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198829 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378830 EXPECT_EQ("This is not a redirect.", d.data_received());
8831}
8832
[email protected]f878230e2014-04-03 15:36:148833TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558834 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148835
tommycli59a63432015-11-06 00:10:558836 GURL original_url(
8837 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8838 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148839
8840 TestDelegate d;
8841 {
rhalavatib7bd7c792017-04-27 05:25:168842 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8843 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148844
[email protected]f7022f32014-08-21 16:32:198845 r->Start();
Wez2a31b222018-06-07 22:07:158846 d.RunUntilComplete();
[email protected]f878230e2014-04-03 15:36:148847
[email protected]f7022f32014-08-21 16:32:198848 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508849 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198850 EXPECT_EQ(original_url, r->original_url());
8851 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148852 }
8853}
8854
[email protected]cba24642014-08-15 20:49:598855TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558856 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598857
tommycli59a63432015-11-06 00:10:558858 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598859 GURL first_party_url("http://example.com");
8860
8861 TestDelegate d;
8862 {
rhalavatib7bd7c792017-04-27 05:25:168863 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8864 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468865 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598866
[email protected]f7022f32014-08-21 16:32:198867 r->Start();
Wez2a31b222018-06-07 22:07:158868 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598869
[email protected]f7022f32014-08-21 16:32:198870 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508871 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468872 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598873 }
8874}
8875
8876TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558877 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598878
tommycli59a63432015-11-06 00:10:558879 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598880 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558881 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598882
8883 TestDelegate d;
8884 {
rhalavatib7bd7c792017-04-27 05:25:168885 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8886 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468887 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198888 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598889 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8890
[email protected]f7022f32014-08-21 16:32:198891 r->Start();
Wez2a31b222018-06-07 22:07:158892 d.RunUntilComplete();
[email protected]cba24642014-08-15 20:49:598893
[email protected]f7022f32014-08-21 16:32:198894 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508895 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468896 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598897 }
8898}
8899
[email protected]316c1e5e2012-09-12 15:17:448900TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558901 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448902
8903 const char kData[] = "hello world";
8904
8905 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368906 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168907 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8908 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198909 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078910 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448911 HttpRequestHeaders headers;
8912 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328913 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198914 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448915
danakj8522a25b2016-04-16 00:17:368916 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558917 req.get(), &default_network_delegate_,
8918 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428919 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8920 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448921
[email protected]f7022f32014-08-21 16:32:198922 req->Start();
Wez2a31b222018-06-07 22:07:158923 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198924 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448925}
8926
8927TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558928 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448929
8930 const char kData[] = "hello world";
8931
8932 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368933 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168934 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8935 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198936 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078937 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448938 HttpRequestHeaders headers;
8939 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328940 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198941 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448942
danakj8522a25b2016-04-16 00:17:368943 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558944 req.get(), &default_network_delegate_,
8945 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098946 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428947 "Very Good Reason"));
8948 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448949
[email protected]f7022f32014-08-21 16:32:198950 req->Start();
Wez2a31b222018-06-07 22:07:158951 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:198952 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448953 EXPECT_EQ(kData, d.data_received());
8954}
8955
8956// Check that default A-L header is sent.
8957TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558958 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448959
[email protected]8790210c2013-12-02 05:29:538960 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248961 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448962 TestURLRequestContext context(true);
8963 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438964 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448965 context.Init();
8966
8967 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368968 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558969 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168970 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198971 req->Start();
Wez2a31b222018-06-07 22:07:158972 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448973 EXPECT_EQ("en", d.data_received());
8974}
8975
8976// Check that an empty A-L header is not sent. http://crbug.com/77365.
8977TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558978 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448979
[email protected]8790210c2013-12-02 05:29:538980 std::string empty_string; // Avoid most vexing parse on line below.
8981 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248982 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448983 TestURLRequestContext context(true);
8984 context.set_network_delegate(&network_delegate);
8985 context.Init();
8986 // We override the language after initialization because empty entries
8987 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438988 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448989
8990 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368991 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558992 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168993 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198994 req->Start();
Wez2a31b222018-06-07 22:07:158995 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:448996 EXPECT_EQ("None", d.data_received());
8997}
8998
8999// Check that if request overrides the A-L header, the default is not appended.
9000// See http://crbug.com/20894
9001TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:559002 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449003
9004 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369005 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559006 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:169007 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449008 HttpRequestHeaders headers;
9009 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:199010 req->SetExtraRequestHeaders(headers);
9011 req->Start();
Wez2a31b222018-06-07 22:07:159012 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449013 EXPECT_EQ(std::string("ru"), d.data_received());
9014}
9015
9016// Check that default A-E header is sent.
9017TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559018 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449019
9020 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369021 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559022 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169023 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449024 HttpRequestHeaders headers;
[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_TRUE(ContainsString(d.data_received(), "gzip"));
9029}
9030
9031// Check that if request overrides the A-E header, the default is not appended.
9032// See http://crbug.com/47381
9033TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:559034 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449035
9036 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369037 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559038 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:169039 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449040 HttpRequestHeaders headers;
9041 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:199042 req->SetExtraRequestHeaders(headers);
9043 req->Start();
Wez2a31b222018-06-07 22:07:159044 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449045 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
9046 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
9047}
9048
[email protected]84f05432013-03-15 01:00:129049// Check that setting the A-C header sends the proper header.
9050TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:559051 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449052
9053 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369054 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559055 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:169056 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449057 HttpRequestHeaders headers;
9058 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:199059 req->SetExtraRequestHeaders(headers);
9060 req->Start();
Wez2a31b222018-06-07 22:07:159061 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449062 EXPECT_EQ(std::string("koi-8r"), d.data_received());
9063}
9064
9065// Check that default User-Agent header is sent.
9066TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:559067 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449068
9069 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369070 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559071 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169072 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199073 req->Start();
Wez2a31b222018-06-07 22:07:159074 d.RunUntilComplete();
[email protected]f7022f32014-08-21 16:32:199075 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:379076 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449077}
9078
9079// Check that if request overrides the User-Agent header,
9080// the default is not appended.
marqf14fff8d2015-12-02 15:52:299081// TODO(crbug.com/564656) This test is flaky on iOS.
9082#if defined(OS_IOS)
9083#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
9084#else
9085#define MAYBE_OverrideUserAgent OverrideUserAgent
9086#endif
9087TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:559088 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:449089
9090 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369091 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559092 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169093 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449094 HttpRequestHeaders headers;
9095 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199096 req->SetExtraRequestHeaders(headers);
9097 req->Start();
Wez2a31b222018-06-07 22:07:159098 d.RunUntilComplete();
[email protected]cd6f2522014-01-16 18:27:359099 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449100}
9101
[email protected]ee4c30d2012-11-07 15:08:439102// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9103// User-Agent header to be sent but does not send the Accept-Language and
9104// Accept-Charset headers.
9105TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559106 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439107
[email protected]ceefd7fd2012-11-29 00:36:249108 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439109 TestURLRequestContext context(true);
9110 context.set_network_delegate(&network_delegate);
9111 context.Init();
9112 // We override the HttpUserAgentSettings after initialization because empty
9113 // entries get overridden by Init().
9114 context.set_http_user_agent_settings(NULL);
9115
9116 struct {
9117 const char* request;
9118 const char* expected_response;
tommycli59a63432015-11-06 00:10:559119 } tests[] = {{"/echoheader?Accept-Language", "None"},
9120 {"/echoheader?Accept-Charset", "None"},
9121 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439122
viettrungluue4a8b882014-10-16 06:17:389123 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439124 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369125 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169126 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9127 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199128 req->Start();
Wez2a31b222018-06-07 22:07:159129 d.RunUntilComplete();
[email protected]ee4c30d2012-11-07 15:08:439130 EXPECT_EQ(tests[i].expected_response, d.data_received())
9131 << " Request = \"" << tests[i].request << "\"";
9132 }
9133}
9134
[email protected]5033ab82013-03-22 20:17:469135// Make sure that URLRequest passes on its priority updates to
9136// newly-created jobs after the first one.
9137TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559138 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469139
9140 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369141 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169142 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9143 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199144 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469145
danakj8522a25b2016-04-16 00:17:369146 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559147 req.get(), &default_network_delegate_,
9148 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429149 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9150 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469151
[email protected]f7022f32014-08-21 16:32:199152 req->SetPriority(LOW);
9153 req->Start();
9154 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469155
mmenkeed0498b2015-12-08 23:20:429156 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369157 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429158 req.get(), &default_network_delegate_, &job_priority));
9159 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469160
9161 // Should trigger |job| to be started.
Wez2a31b222018-06-07 22:07:159162 d.RunUntilComplete();
mmenkeed0498b2015-12-08 23:20:429163 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469164}
9165
[email protected]80abdad2014-03-15 00:20:549166// Check that creating a network request while entering/exiting suspend mode
9167// fails as it should. This is the only case where an HttpTransactionFactory
9168// does not return an HttpTransaction.
9169TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9170 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369171 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:179172 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549173 network_layer->OnSuspend();
9174
dchengc7eeda422015-12-26 03:56:489175 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039176 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279177 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549178
9179 TestURLRequestContext context(true);
9180 context.set_http_transaction_factory(&http_cache);
9181 context.Init();
9182
9183 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369184 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169185 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9186 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199187 req->Start();
Wez2a31b222018-06-07 22:07:159188 d.RunUntilComplete();
[email protected]80abdad2014-03-15 00:20:549189
9190 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509191 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549192}
9193
mmenke2281f3762015-11-02 20:38:179194namespace {
[email protected]80abdad2014-03-15 00:20:549195
mmenke2281f3762015-11-02 20:38:179196// HttpTransactionFactory that synchronously fails to create transactions.
9197class FailingHttpTransactionFactory : public HttpTransactionFactory {
9198 public:
9199 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9200 : network_session_(network_session) {}
9201
Chris Watkins7a41d3552017-12-01 02:13:279202 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179203
9204 // HttpTransactionFactory methods:
9205 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369206 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179207 return ERR_FAILED;
9208 }
9209
9210 HttpCache* GetCache() override { return nullptr; }
9211
9212 HttpNetworkSession* GetSession() override { return network_session_; }
9213
9214 private:
9215 HttpNetworkSession* network_session_;
9216
9217 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9218};
9219
9220} // namespace
9221
9222// Check that when a request that fails to create an HttpTransaction can be
9223// cancelled while the failure notification is pending, and doesn't send two
9224// failure notifications.
9225//
9226// This currently only happens when in suspend mode and there's no cache, but
9227// just use a special HttpTransactionFactory, to avoid depending on those
9228// behaviors.
9229TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9230 FailingHttpTransactionFactory http_transaction_factory(
9231 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549232 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179233 context.set_http_transaction_factory(&http_transaction_factory);
9234 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549235 context.Init();
9236
9237 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369238 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169239 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9240 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179241 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9242 // try to create an HttpNetworkTransaction synchronously on start).
9243 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199244 req->Start();
mmenke2281f3762015-11-02 20:38:179245 req->Cancel();
Wez2a31b222018-06-07 22:07:159246 d.RunUntilComplete();
mmenke2281f3762015-11-02 20:38:179247 // Run pending error task, if there is one.
9248 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549249
9250 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179251 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509252 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179253
9254 // NetworkDelegate should see the cancellation, but not the error.
9255 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9256 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549257}
9258
ttuttlec0c828492015-05-15 01:25:559259TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559260 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559261
9262 TestDelegate d;
tommycli59a63432015-11-06 00:10:559263 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169264 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9265 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559266
9267 req->Start();
Wez2a31b222018-06-07 22:07:159268 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559269
9270 EXPECT_TRUE(req->response_info().network_accessed);
9271}
9272
9273TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559274 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559275
9276 // Populate the cache.
9277 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369278 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169279 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9280 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559281 req->Start();
Wez2a31b222018-06-07 22:07:159282 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559283
maksim.sisovb53724b52016-09-16 05:30:509284 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559285 EXPECT_TRUE(req->response_info().network_accessed);
9286 EXPECT_FALSE(req->response_info().was_cached);
9287
tommycli59a63432015-11-06 00:10:559288 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:169289 DEFAULT_PRIORITY, &d,
9290 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559291 req->Start();
Wez2a31b222018-06-07 22:07:159292 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559293
maksim.sisovb53724b52016-09-16 05:30:509294 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559295 EXPECT_FALSE(req->response_info().network_accessed);
9296 EXPECT_TRUE(req->response_info().was_cached);
9297}
9298
9299TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559300 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559301
9302 TestDelegate d;
tommycli59a63432015-11-06 00:10:559303 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169304 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9305 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339306 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559307
9308 req->Start();
Wez2a31b222018-06-07 22:07:159309 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:559310
9311 EXPECT_FALSE(req->response_info().network_accessed);
9312}
9313
rdsmithbf8c3c12016-11-18 18:16:249314// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089315// correctly in the absence of contention.
9316TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9317 ASSERT_TRUE(http_test_server()->Start());
9318
9319 TestDelegate d;
9320 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169321 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9322 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089323 req->Start();
Wez2a31b222018-06-07 22:07:159324 d.RunUntilComplete();
rdsmith5eb6fbc2016-10-21 17:36:089325
9326 EXPECT_TRUE(req->status().is_success());
9327}
9328
ricea3a1c71f2016-06-17 10:05:269329TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9330 ASSERT_TRUE(http_test_server()->Start());
9331
9332 TestDelegate d;
9333 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169334 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9335 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269336 req->Start();
Wez2a31b222018-06-07 22:07:159337 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269338
9339 EXPECT_EQ(5, req->GetRawBodyBytes());
9340}
9341
9342TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9343 ASSERT_TRUE(http_test_server()->Start());
9344
9345 TestDelegate d;
9346 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169347 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9348 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269349 req->Start();
Wez2a31b222018-06-07 22:07:159350 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:269351
9352 EXPECT_EQ(30, req->GetRawBodyBytes());
9353}
9354
jamd3f5a3c2016-10-27 18:52:029355// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9356// the delegate isn't called back synchronously.
9357TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9358 ASSERT_TRUE(http_test_server()->Start());
9359 default_network_delegate_.set_before_start_transaction_fails();
9360
9361 TestDelegate d;
9362 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169363 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9364 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029365 req->Start();
9366 DCHECK(!d.response_completed());
Wez2a31b222018-06-07 22:07:159367 d.RunUntilComplete();
jamd3f5a3c2016-10-27 18:52:029368 DCHECK(d.response_completed());
9369 EXPECT_EQ(ERR_FAILED, d.request_status());
9370}
9371
bengr1bf8e942014-11-07 01:36:509372class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9373 public:
9374 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9375 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9376 // tests into the factory tests.
9377 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
9378 }
9379
9380 void SetUpFactory() override {
9381 interceptor_ = new MockURLRequestInterceptor();
9382 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369383 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509384 }
9385
9386 MockURLRequestInterceptor* interceptor() const {
9387 return interceptor_;
9388 }
9389
9390 private:
9391 MockURLRequestInterceptor* interceptor_;
9392};
9393
9394TEST_F(URLRequestInterceptorTestHTTP,
9395 NetworkDelegateNotificationOnRedirectIntercept) {
9396 interceptor()->set_intercept_redirect(true);
9397 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9398 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9399
tommycli59a63432015-11-06 00:10:559400 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509401
9402 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369403 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169404 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9405 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509406 req->Start();
Wez2a31b222018-06-07 22:07:159407 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509408
9409 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9410 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509411 int status = d.request_status();
9412 EXPECT_EQ(OK, status);
9413 if (status == OK)
bengr1bf8e942014-11-07 01:36:509414 EXPECT_EQ(200, req->response_headers()->response_code());
9415
9416 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9417 EXPECT_EQ(1, d.response_started_count());
9418 EXPECT_EQ(0, d.received_redirect_count());
9419
9420 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009421 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509422 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9423}
9424
9425TEST_F(URLRequestInterceptorTestHTTP,
9426 NetworkDelegateNotificationOnErrorIntercept) {
9427 // Intercept that error and respond with an OK response.
9428 interceptor()->set_intercept_final_response(true);
9429 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9430 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9431 default_network_delegate()->set_can_be_intercepted_on_error(true);
9432
tommycli59a63432015-11-06 00:10:559433 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509434
9435 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369436 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559437 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169438 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509439 req->set_method("GET");
9440 req->Start();
Wez2a31b222018-06-07 22:07:159441 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509442
9443 EXPECT_TRUE(interceptor()->did_intercept_final());
9444
9445 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509446 int status = d.request_status();
9447 EXPECT_EQ(OK, status);
9448 if (status == OK)
bengr1bf8e942014-11-07 01:36:509449 EXPECT_EQ(200, req->response_headers()->response_code());
9450 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9451 EXPECT_EQ(1, d.response_started_count());
9452 EXPECT_EQ(0, d.received_redirect_count());
9453
9454 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009455 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509456 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9457}
9458
9459TEST_F(URLRequestInterceptorTestHTTP,
9460 NetworkDelegateNotificationOnResponseIntercept) {
9461 // Intercept that error and respond with an OK response.
9462 interceptor()->set_intercept_final_response(true);
9463
9464 // Intercept with a real URLRequestHttpJob.
9465 interceptor()->set_use_url_request_http_job(true);
9466
tommycli59a63432015-11-06 00:10:559467 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509468
9469 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369470 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169471 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9472 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509473 req->set_method("GET");
9474 req->Start();
Wez2a31b222018-06-07 22:07:159475 d.RunUntilComplete();
bengr1bf8e942014-11-07 01:36:509476
9477 EXPECT_TRUE(interceptor()->did_intercept_final());
9478
9479 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509480 int status = d.request_status();
9481 EXPECT_EQ(OK, status);
9482 if (status == OK)
bengr1bf8e942014-11-07 01:36:509483 EXPECT_EQ(200, req->response_headers()->response_code());
9484 EXPECT_EQ("hello", d.data_received());
9485 EXPECT_EQ(1, d.response_started_count());
9486 EXPECT_EQ(0, d.received_redirect_count());
9487
9488 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009489 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509490 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9491}
9492
mkwst0c5eab872014-11-21 14:18:549493class URLRequestTestReferrerPolicy : public URLRequestTest {
9494 public:
Chris Watkins7a41d3552017-12-01 02:13:279495 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549496
tommycli59a63432015-11-06 00:10:559497 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9498 origin_server_.reset(new EmbeddedTestServer(type));
9499 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9500 origin_server_->AddDefaultHandlers(
9501 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9502 } else {
9503 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9504 }
mkwst0c5eab872014-11-21 14:18:549505 ASSERT_TRUE(origin_server_->Start());
9506 }
9507
tommycli59a63432015-11-06 00:10:559508 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9509 net::EmbeddedTestServer::Type dest_type) {
9510 origin_server_.reset(new EmbeddedTestServer(origin_type));
9511 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9512 origin_server_->AddDefaultHandlers(
9513 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9514 } else {
9515 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9516 }
mkwst0c5eab872014-11-21 14:18:549517 ASSERT_TRUE(origin_server_->Start());
9518
tommycli59a63432015-11-06 00:10:559519 destination_server_.reset(new EmbeddedTestServer(dest_type));
9520 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9521 destination_server_->AddDefaultHandlers(
9522 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9523 } else {
9524 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9525 }
mkwst0c5eab872014-11-21 14:18:549526 ASSERT_TRUE(destination_server_->Start());
9527 }
9528
9529 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9530 const GURL& referrer,
9531 const GURL& expected) {
9532 // Create and execute the request: we'll only have a |destination_server_|
9533 // if the origins are meant to be distinct. Otherwise, we'll use the
9534 // |origin_server_| for both endpoints.
9535 GURL destination_url =
tommycli59a63432015-11-06 00:10:559536 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9537 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549538 GURL origin_url =
tommycli59a63432015-11-06 00:10:559539 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549540
9541 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169542 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9543 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549544 req->set_referrer_policy(policy);
9545 req->SetReferrer(referrer.spec());
9546 req->Start();
Wez2a31b222018-06-07 22:07:159547 d.RunUntilComplete();
mkwst0c5eab872014-11-21 14:18:549548
9549 EXPECT_EQ(1, d.response_started_count());
9550 EXPECT_EQ(1, d.received_redirect_count());
9551 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509552 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549553 EXPECT_EQ(200, req->response_headers()->response_code());
9554
9555 EXPECT_EQ(expected.spec(), req->referrer());
9556 if (expected.is_empty())
9557 EXPECT_EQ("None", d.data_received());
9558 else
9559 EXPECT_EQ(expected.spec(), d.data_received());
9560 }
9561
tommycli59a63432015-11-06 00:10:559562 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549563
9564 private:
danakj8522a25b2016-04-16 00:17:369565 std::unique_ptr<EmbeddedTestServer> origin_server_;
9566 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549567};
9568
9569TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559570 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549571
estarkc8ccba82017-06-13 22:37:409572 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549573 VerifyReferrerAfterRedirect(
9574 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409575 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549576
9577 VerifyReferrerAfterRedirect(
9578 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409579 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549580
9581 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409582 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549583
estarkc8ccba82017-06-13 22:37:409584 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9585 referrer);
9586
9587 // The original referrer set on the request is expected to obey the referrer
9588 // policy and already be stripped to the origin; thus this test case just
9589 // checks that this policy doesn't cause the referrer to change when following
9590 // a redirect.
9591 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9592 referrer.GetOrigin());
9593
9594 VerifyReferrerAfterRedirect(
9595 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9596 referrer);
9597
9598 // The original referrer set on the request is expected to obey the referrer
9599 // policy and already be stripped to the origin; thus this test case just
9600 // checks that this policy doesn't cause the referrer to change when following
9601 // a redirect.
9602 VerifyReferrerAfterRedirect(
9603 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9604 referrer.GetOrigin(), referrer.GetOrigin());
9605
9606 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549607}
9608
tommycli59a63432015-11-06 00:10:559609TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9610 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9611 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409612 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549613
9614 VerifyReferrerAfterRedirect(
9615 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409616 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549617
9618 VerifyReferrerAfterRedirect(
9619 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409620 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549621
9622 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409623 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9624 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549625
estarkc8ccba82017-06-13 22:37:409626 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9627 referrer);
9628
9629 // The original referrer set on the request is expected to obey the referrer
9630 // policy and already be stripped to the origin; thus this test case just
9631 // checks that this policy doesn't cause the referrer to change when following
9632 // a redirect.
9633 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9634 referrer.GetOrigin());
9635
9636 VerifyReferrerAfterRedirect(
9637 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9638
9639 // The original referrer set on the request is expected to obey the referrer
9640 // policy and already be stripped to the origin; thus this test case just
9641 // checks that this policy doesn't cause the referrer to change when following
9642 // a redirect.
9643 VerifyReferrerAfterRedirect(
9644 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9645 referrer.GetOrigin(), referrer.GetOrigin());
9646
9647 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549648}
9649
9650TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559651 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409652 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549653
9654 VerifyReferrerAfterRedirect(
9655 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409656 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549657
9658 VerifyReferrerAfterRedirect(
9659 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409660 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549661
9662 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409663 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549664
estarkc8ccba82017-06-13 22:37:409665 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9666 referrer);
9667
9668 // The original referrer set on the request is expected to obey the referrer
9669 // policy and already be stripped to the origin; thus this test case just
9670 // checks that this policy doesn't cause the referrer to change when following
9671 // a redirect.
9672 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9673 referrer.GetOrigin());
9674
9675 VerifyReferrerAfterRedirect(
9676 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9677 referrer);
9678
9679 // The original referrer set on the request is expected to obey the referrer
9680 // policy and already be stripped to the origin; thus this test case just
9681 // checks that this policy doesn't cause the referrer to change when following
9682 // a redirect.
9683 VerifyReferrerAfterRedirect(
9684 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9685 referrer.GetOrigin(), referrer.GetOrigin());
9686
9687 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549688}
9689
tommycli59a63432015-11-06 00:10:559690TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9691 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9692 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409693 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549694
9695 VerifyReferrerAfterRedirect(
9696 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409697 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549698
9699 VerifyReferrerAfterRedirect(
9700 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409701 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549702
9703 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409704 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559705 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549706
estarkc8ccba82017-06-13 22:37:409707 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9708 referrer);
9709
9710 // The original referrer set on the request is expected to obey the referrer
9711 // policy and already be stripped to the origin; thus this test case just
9712 // checks that this policy doesn't cause the referrer to change when following
9713 // a redirect.
9714 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9715 referrer.GetOrigin());
9716
9717 VerifyReferrerAfterRedirect(
9718 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9719
9720 // The original referrer set on the request is expected to obey the referrer
9721 // policy and already be stripped to the origin; thus this test case just
9722 // checks that this policy doesn't cause the referrer to change when following
9723 // a redirect.
9724 VerifyReferrerAfterRedirect(
9725 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9726 referrer.GetOrigin(), referrer.GetOrigin());
9727
9728 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549729}
9730
tommycli59a63432015-11-06 00:10:559731TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9732 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9733 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409734 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549735
9736 VerifyReferrerAfterRedirect(
9737 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409738 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549739
9740 VerifyReferrerAfterRedirect(
9741 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409742 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549743
9744 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409745 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559746 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549747
estarkc8ccba82017-06-13 22:37:409748 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9749 referrer);
9750
9751 // The original referrer set on the request is expected to obey the referrer
9752 // policy and already be stripped to the origin; thus this test case just
9753 // checks that this policy doesn't cause the referrer to change when following
9754 // a redirect.
9755 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9756 referrer.GetOrigin());
9757
9758 VerifyReferrerAfterRedirect(
9759 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9760
9761 // The original referrer set on the request is expected to obey the referrer
9762 // policy and already be stripped to the origin; thus this test case just
9763 // checks that this policy doesn't cause the referrer to change when following
9764 // a redirect.
9765 VerifyReferrerAfterRedirect(
9766 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9767 referrer.GetOrigin(), referrer.GetOrigin());
9768
9769 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549770}
9771
tommycli59a63432015-11-06 00:10:559772TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9773 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9774 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409775 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549776
9777 VerifyReferrerAfterRedirect(
9778 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409779 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549780
9781 VerifyReferrerAfterRedirect(
9782 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409783 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549784
9785 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409786 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559787 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549788
estarkc8ccba82017-06-13 22:37:409789 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9790 referrer);
9791
9792 // The original referrer set on the request is expected to obey the referrer
9793 // policy and already be stripped to the origin; thus this test case just
9794 // checks that this policy doesn't cause the referrer to change when following
9795 // a redirect.
9796 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9797 referrer.GetOrigin());
9798
9799 VerifyReferrerAfterRedirect(
9800 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9801
9802 // The original referrer set on the request is expected to obey the referrer
9803 // policy and already be stripped to the origin, though it should be
9804 // subsequently cleared during the downgrading redirect.
9805 VerifyReferrerAfterRedirect(
9806 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9807 referrer.GetOrigin(), GURL());
9808
9809 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549810}
9811
Bence Béky98447b12018-05-08 03:14:019812class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509813 public:
fdorayf33fede2017-05-11 21:18:109814 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099815 default_context_.set_network_delegate(&default_network_delegate_);
9816 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509817 }
Martijn Croonenb1383da2017-10-11 11:56:359818 ~HTTPSRequestTest() override {
9819 SetTransportSecurityStateSourceForTesting(nullptr);
9820 }
[email protected]87a09a92011-07-14 15:50:509821
9822 protected:
[email protected]ceefd7fd2012-11-29 00:36:249823 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099824 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469825};
9826
[email protected]c044616e2013-02-20 02:01:269827TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559828 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9829 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229830 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119831 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469832
[email protected]ea224582008-12-07 20:25:469833 TestDelegate d;
9834 {
danakj8522a25b2016-04-16 00:17:369835 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169836 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9837 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199838 r->Start();
9839 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469840
Wez2a31b222018-06-07 22:07:159841 d.RunUntilComplete();
[email protected]ea224582008-12-07 20:25:469842
9843 EXPECT_EQ(1, d.response_started_count());
9844 EXPECT_FALSE(d.received_data_before_response());
9845 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199846 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199847 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199848 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199849 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199850 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469851 }
[email protected]ea224582008-12-07 20:25:469852}
9853
[email protected]5774ada2010-07-15 06:30:549854TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559855 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9856 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9857 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229858 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119859 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339860
9861 bool err_allowed = true;
9862 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9863 TestDelegate d;
9864 {
9865 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369866 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169867 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9868 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339869
[email protected]f7022f32014-08-21 16:32:199870 r->Start();
9871 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339872
Wez2a31b222018-06-07 22:07:159873 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339874
9875 EXPECT_EQ(1, d.response_started_count());
9876 EXPECT_FALSE(d.received_data_before_response());
9877 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179878 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339879 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199880 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179881 } else {
[email protected]bacff652009-03-31 17:50:339882 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179883 }
[email protected]bacff652009-03-31 17:50:339884 }
9885 }
9886}
9887
[email protected]5774ada2010-07-15 06:30:549888TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559889 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9890 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9891 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229892 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119893 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339894
9895 // Iterate from false to true, just so that we do the opposite of the
9896 // previous test in order to increase test coverage.
9897 bool err_allowed = false;
9898 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9899 TestDelegate d;
9900 {
9901 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369902 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169903 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9904 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339905
[email protected]f7022f32014-08-21 16:32:199906 r->Start();
9907 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339908
Wez2a31b222018-06-07 22:07:159909 d.RunUntilComplete();
[email protected]bacff652009-03-31 17:50:339910
9911 EXPECT_EQ(1, d.response_started_count());
9912 EXPECT_FALSE(d.received_data_before_response());
9913 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179914 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339915 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199916 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179917 } else {
[email protected]bacff652009-03-31 17:50:339918 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179919 }
[email protected]bacff652009-03-31 17:50:339920 }
9921 }
9922}
[email protected]73e0bba2009-02-19 22:57:099923
tommycli59a63432015-11-06 00:10:559924// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9925// security state. (see http://crbug.com/550977).
9926#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359927// This tests that a load of a domain with preloaded HSTS and HPKP with a
9928// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9929// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449930TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359931 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9932
tommycli59a63432015-11-06 00:10:559933 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9934 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9935 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449936 ASSERT_TRUE(test_server.Start());
9937
Martijn Croonenb1383da2017-10-11 11:56:359938 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9939 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9940 // means that we have to use a MockHostResolver in order to direct
9941 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9942 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449943
9944 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249945 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449946 TestURLRequestContext context(true);
9947 context.set_network_delegate(&network_delegate);
9948 context.set_host_resolver(&host_resolver);
9949 TransportSecurityState transport_security_state;
9950 context.set_transport_security_state(&transport_security_state);
9951 context.Init();
9952
9953 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369954 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359955 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369956 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169957 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449958
[email protected]f7022f32014-08-21 16:32:199959 r->Start();
9960 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449961
Wez2a31b222018-06-07 22:07:159962 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:449963
9964 EXPECT_EQ(1, d.response_started_count());
9965 EXPECT_FALSE(d.received_data_before_response());
9966 EXPECT_TRUE(d.have_certificate_errors());
9967 EXPECT_TRUE(d.certificate_errors_are_fatal());
9968}
9969
9970// This tests that cached HTTPS page loads do not cause any updates to the
9971// TransportSecurityState.
9972TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359973 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9974
[email protected]316c1e5e2012-09-12 15:17:449975 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9976 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559977 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9978 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9979 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449980 ASSERT_TRUE(test_server.Start());
9981
Martijn Croonenb1383da2017-10-11 11:56:359982 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9983 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9984 // means that we have to use a MockHostResolver in order to direct
9985 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9986 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449987
9988 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249989 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449990 TestURLRequestContext context(true);
9991 context.set_network_delegate(&network_delegate);
9992 context.set_host_resolver(&host_resolver);
9993 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269994
martijnc0d6b622015-06-30 19:14:409995 TransportSecurityState::STSState static_sts_state;
9996 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269997 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359998 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449999 context.set_transport_security_state(&transport_security_state);
10000 context.Init();
10001
martijnc0d6b622015-06-30 19:14:4010002 TransportSecurityState::STSState dynamic_sts_state;
10003 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:3510004 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
10005 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
10006 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
10007 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610008
[email protected]316c1e5e2012-09-12 15:17:4410009 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610010 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:3510011 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:3610012 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610013 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410014
[email protected]f7022f32014-08-21 16:32:1910015 r->Start();
10016 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410017
Wez2a31b222018-06-07 22:07:1510018 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410019
10020 EXPECT_EQ(1, d.response_started_count());
10021 EXPECT_FALSE(d.received_data_before_response());
10022 EXPECT_TRUE(d.have_certificate_errors());
10023 EXPECT_TRUE(d.certificate_errors_are_fatal());
10024
[email protected]9e6968d2014-05-07 21:46:2610025 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:4010026 TransportSecurityState::STSState new_static_sts_state;
10027 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:2610028 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:3510029 "hsts-hpkp-preloaded.test", &new_static_sts_state,
10030 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:4010031 TransportSecurityState::STSState new_dynamic_sts_state;
10032 TransportSecurityState::PKPState new_dynamic_pkp_state;
10033 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:3510034 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:4010035 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:3510036 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:2610037
martijnc0d6b622015-06-30 19:14:4010038 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
10039 EXPECT_EQ(new_static_sts_state.include_subdomains,
10040 static_sts_state.include_subdomains);
10041 EXPECT_EQ(new_static_pkp_state.include_subdomains,
10042 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:4810043 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
10044 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
10045 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:4410046}
10047
[email protected]8ccc69f2012-11-28 19:52:1410048// Make sure HSTS preserves a POST request's method and body.
10049TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
10050 static const char kData[] = "hello world";
10051
tommycli59a63432015-11-06 00:10:5510052 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10053 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210054 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:1410055 ASSERT_TRUE(test_server.Start());
10056
10057
10058 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10059 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:5510060 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:2210061 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:1410062 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:1410063
10064 // Force https for www.somewhere.com.
10065 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:2010066 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
10067 bool include_subdomains = false;
10068 transport_security_state.AddHSTS("www.somewhere.com", expiry,
10069 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:1410070
10071 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10072
10073 TestURLRequestContext context(true);
10074 context.set_host_resolver(&host_resolver);
10075 context.set_transport_security_state(&transport_security_state);
10076 context.set_network_delegate(&network_delegate);
10077 context.Init();
10078
10079 TestDelegate d;
10080 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
10081 // cause a certificate error. Ignore the error.
10082 d.set_allow_certificate_errors(true);
10083
danakj8522a25b2016-04-16 00:17:3610084 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:1910085 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:3610086 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:1610087 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910088 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:0710089 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:1410090
[email protected]f7022f32014-08-21 16:32:1910091 req->Start();
Wez2a31b222018-06-07 22:07:1510092 d.RunUntilComplete();
[email protected]8ccc69f2012-11-28 19:52:1410093
[email protected]f7022f32014-08-21 16:32:1910094 EXPECT_EQ("https", req->url().scheme());
10095 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410096 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010097
10098 LoadTimingInfo load_timing_info;
10099 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10100 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10101 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410102}
10103
rob4e0be1f2014-09-11 23:40:2210104// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10105TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10106 static const char kOriginHeaderValue[] = "http://www.example.com";
10107
tommycli59a63432015-11-06 00:10:5510108 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10109 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210110 ASSERT_TRUE(test_server.Start());
10111
10112 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10113 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510114 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10115 // default.
rob4e0be1f2014-09-11 23:40:2210116 MockHostResolver host_resolver;
10117
10118 TransportSecurityState transport_security_state;
10119 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10120 bool include_subdomains = false;
10121 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10122
10123 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10124
10125 MockCertVerifier cert_verifier;
10126 cert_verifier.set_default_result(OK);
10127
10128 TestURLRequestContext context(true);
10129 context.set_host_resolver(&host_resolver);
10130 context.set_transport_security_state(&transport_security_state);
10131 context.set_network_delegate(&network_delegate);
10132 context.set_cert_verifier(&cert_verifier);
10133 context.Init();
10134
10135 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10136 test_server.host_port_pair().port()));
10137 url::Replacements<char> replacements;
10138 const char kNewScheme[] = "https";
10139 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10140 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10141
10142 TestDelegate d;
10143 // Quit on redirect to allow response header inspection upon redirect.
10144 d.set_quit_on_redirect(true);
10145
rhalavatib7bd7c792017-04-27 05:25:1610146 std::unique_ptr<URLRequest> req(context.CreateRequest(
10147 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210148 // Set Origin header to simulate a cross-origin request.
10149 HttpRequestHeaders request_headers;
10150 request_headers.SetHeader("Origin", kOriginHeaderValue);
10151 req->SetExtraRequestHeaders(request_headers);
10152
10153 req->Start();
Wez2a31b222018-06-07 22:07:1510154 d.RunUntilComplete();
rob4e0be1f2014-09-11 23:40:2210155
10156 EXPECT_EQ(1, d.received_redirect_count());
10157
10158 const HttpResponseHeaders* headers = req->response_headers();
10159 std::string redirect_location;
10160 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
10161 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10162
10163 std::string received_cors_header;
10164 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
10165 &received_cors_header));
10166 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10167}
10168
[email protected]316c1e5e2012-09-12 15:17:4410169namespace {
10170
10171class SSLClientAuthTestDelegate : public TestDelegate {
10172 public:
10173 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
10174 }
dchengb03027d2014-10-21 12:00:2010175 void OnCertificateRequested(URLRequest* request,
10176 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410177 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:2310178 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:4410179 }
10180 int on_certificate_requested_count() {
10181 return on_certificate_requested_count_;
10182 }
10183 private:
10184 int on_certificate_requested_count_;
10185};
10186
David Benjamin76a40ad2018-02-24 22:22:0810187class TestSSLPrivateKey : public SSLPrivateKey {
10188 public:
10189 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10190 : key_(std::move(key)) {}
10191
10192 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10193 int sign_count() const { return sign_count_; }
10194
10195 std::vector<uint16_t> GetAlgorithmPreferences() override {
10196 return key_->GetAlgorithmPreferences();
10197 }
10198 void Sign(uint16_t algorithm,
10199 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610200 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810201 sign_count_++;
10202 if (fail_signing_) {
10203 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610204 FROM_HERE, base::BindOnce(std::move(callback),
10205 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10206 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810207 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610208 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810209 }
10210 }
10211
10212 private:
10213 ~TestSSLPrivateKey() override = default;
10214
10215 scoped_refptr<SSLPrivateKey> key_;
10216 bool fail_signing_ = false;
10217 int sign_count_ = 0;
10218};
10219
[email protected]316c1e5e2012-09-12 15:17:4410220} // namespace
10221
10222// TODO(davidben): Test the rest of the code. Specifically,
10223// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410224// - Getting a certificate request in an SSL renegotiation sending the
10225// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810226TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510227 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10228 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210229 ssl_config.client_cert_type =
10230 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810231 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510232 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210233 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410234 ASSERT_TRUE(test_server.Start());
10235
10236 SSLClientAuthTestDelegate d;
10237 {
danakj8522a25b2016-04-16 00:17:3610238 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610239 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10240 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410241
[email protected]f7022f32014-08-21 16:32:1910242 r->Start();
10243 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410244
Wez2a31b222018-06-07 22:07:1510245 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410246
10247 EXPECT_EQ(1, d.on_certificate_requested_count());
10248 EXPECT_FALSE(d.received_data_before_response());
10249 EXPECT_EQ(0, d.bytes_received());
10250
10251 // Send no certificate.
10252 // TODO(davidben): Get temporary client cert import (with keys) working on
10253 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410254 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410255
Wez2a31b222018-06-07 22:07:1510256 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410257
David Benjamin76a40ad2018-02-24 22:22:0810258 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410259 EXPECT_EQ(1, d.response_started_count());
10260 EXPECT_FALSE(d.received_data_before_response());
10261 EXPECT_NE(0, d.bytes_received());
10262 }
10263}
10264
David Benjamin76a40ad2018-02-24 22:22:0810265TEST_F(HTTPSRequestTest, ClientAuth) {
10266 std::unique_ptr<FakeClientCertIdentity> identity =
10267 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10268 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10269 ASSERT_TRUE(identity);
10270 scoped_refptr<TestSSLPrivateKey> private_key =
10271 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10272
10273 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10274 net::SSLServerConfig ssl_config;
10275 ssl_config.client_cert_type =
10276 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10277 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10278 test_server.AddDefaultHandlers(
10279 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10280 ASSERT_TRUE(test_server.Start());
10281
10282 {
10283 SSLClientAuthTestDelegate d;
10284 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10285 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10286 TRAFFIC_ANNOTATION_FOR_TESTS));
10287
10288 r->Start();
10289 EXPECT_TRUE(r->is_pending());
10290
Wez2a31b222018-06-07 22:07:1510291 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810292
10293 EXPECT_EQ(1, d.on_certificate_requested_count());
10294 EXPECT_FALSE(d.received_data_before_response());
10295 EXPECT_EQ(0, d.bytes_received());
10296
10297 // Send a certificate.
10298 r->ContinueWithCertificate(identity->certificate(), private_key);
10299
Wez2a31b222018-06-07 22:07:1510300 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810301
10302 EXPECT_EQ(OK, d.request_status());
10303 EXPECT_EQ(1, d.response_started_count());
10304 EXPECT_FALSE(d.received_data_before_response());
10305 EXPECT_NE(0, d.bytes_received());
10306
10307 // The private key should have been used.
10308 EXPECT_EQ(1, private_key->sign_count());
10309 }
10310
10311 // Close all connections and clear the session cache to force a new handshake.
10312 default_context_.http_transaction_factory()
10313 ->GetSession()
10314 ->CloseAllConnections();
10315 SSLClientSocket::ClearSessionCache();
10316
10317 // Connecting again should not call OnCertificateRequested. The identity is
10318 // taken from the client auth cache.
10319 {
10320 SSLClientAuthTestDelegate d;
10321 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10322 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10323 TRAFFIC_ANNOTATION_FOR_TESTS));
10324
10325 r->Start();
10326 EXPECT_TRUE(r->is_pending());
10327
Wez2a31b222018-06-07 22:07:1510328 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810329
10330 EXPECT_EQ(OK, d.request_status());
10331 EXPECT_EQ(0, d.on_certificate_requested_count());
10332 EXPECT_FALSE(d.received_data_before_response());
10333 EXPECT_EQ(1, d.response_started_count());
10334 EXPECT_FALSE(d.received_data_before_response());
10335 EXPECT_NE(0, d.bytes_received());
10336
10337 // The private key should have been used.
10338 EXPECT_EQ(2, private_key->sign_count());
10339 }
10340}
10341
10342// Test that private keys that fail to sign anything get evicted from the cache.
10343TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10344 std::unique_ptr<FakeClientCertIdentity> identity =
10345 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10346 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10347 ASSERT_TRUE(identity);
10348 scoped_refptr<TestSSLPrivateKey> private_key =
10349 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10350 private_key->set_fail_signing(true);
10351
10352 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10353 net::SSLServerConfig ssl_config;
10354 ssl_config.client_cert_type =
10355 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10356 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10357 test_server.AddDefaultHandlers(
10358 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10359 ASSERT_TRUE(test_server.Start());
10360
10361 {
10362 SSLClientAuthTestDelegate d;
10363 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10364 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10365 TRAFFIC_ANNOTATION_FOR_TESTS));
10366
10367 r->Start();
10368 EXPECT_TRUE(r->is_pending());
Wez2a31b222018-06-07 22:07:1510369 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810370
10371 EXPECT_EQ(1, d.on_certificate_requested_count());
10372 EXPECT_FALSE(d.received_data_before_response());
10373 EXPECT_EQ(0, d.bytes_received());
10374
10375 // Send a certificate.
10376 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510377 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810378
10379 // The private key cannot sign anything, so we report an error.
10380 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10381 EXPECT_EQ(1, d.response_started_count());
10382 EXPECT_FALSE(d.received_data_before_response());
10383 EXPECT_EQ(0, d.bytes_received());
10384
10385 // The private key should have been used.
10386 EXPECT_EQ(1, private_key->sign_count());
10387 }
10388
10389 // Close all connections and clear the session cache to force a new handshake.
10390 default_context_.http_transaction_factory()
10391 ->GetSession()
10392 ->CloseAllConnections();
10393 SSLClientSocket::ClearSessionCache();
10394
10395 // The bad identity should have been evicted from the cache, so connecting
10396 // again should call OnCertificateRequested again.
10397 {
10398 SSLClientAuthTestDelegate d;
10399 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10400 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10401 TRAFFIC_ANNOTATION_FOR_TESTS));
10402
10403 r->Start();
10404 EXPECT_TRUE(r->is_pending());
10405
Wez2a31b222018-06-07 22:07:1510406 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810407
10408 EXPECT_EQ(1, d.on_certificate_requested_count());
10409 EXPECT_FALSE(d.received_data_before_response());
10410 EXPECT_EQ(0, d.bytes_received());
10411
10412 // There should have been no additional uses of the private key.
10413 EXPECT_EQ(1, private_key->sign_count());
10414 }
10415}
10416
10417// Test that cached private keys that fail to sign anything trigger a
10418// retry. This is so we handle unplugged smartcards
10419// gracefully. https://crbug.com/813022.
10420TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10421 std::unique_ptr<FakeClientCertIdentity> identity =
10422 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10423 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10424 ASSERT_TRUE(identity);
10425 scoped_refptr<TestSSLPrivateKey> private_key =
10426 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10427
10428 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10429 net::SSLServerConfig ssl_config;
10430 ssl_config.client_cert_type =
10431 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10432 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10433 test_server.AddDefaultHandlers(
10434 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10435 ASSERT_TRUE(test_server.Start());
10436
10437 // Connect with a client certificate to put it in the client auth cache.
10438 {
10439 SSLClientAuthTestDelegate d;
10440 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10441 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10442 TRAFFIC_ANNOTATION_FOR_TESTS));
10443
10444 r->Start();
10445 EXPECT_TRUE(r->is_pending());
10446
Wez2a31b222018-06-07 22:07:1510447 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810448
10449 EXPECT_EQ(1, d.on_certificate_requested_count());
10450 EXPECT_FALSE(d.received_data_before_response());
10451 EXPECT_EQ(0, d.bytes_received());
10452
10453 r->ContinueWithCertificate(identity->certificate(), private_key);
Wez2a31b222018-06-07 22:07:1510454 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810455
10456 EXPECT_EQ(OK, d.request_status());
10457 EXPECT_EQ(1, d.response_started_count());
10458 EXPECT_FALSE(d.received_data_before_response());
10459 EXPECT_NE(0, d.bytes_received());
10460
10461 // The private key should have been used.
10462 EXPECT_EQ(1, private_key->sign_count());
10463 }
10464
10465 // Close all connections and clear the session cache to force a new handshake.
10466 default_context_.http_transaction_factory()
10467 ->GetSession()
10468 ->CloseAllConnections();
10469 SSLClientSocket::ClearSessionCache();
10470
10471 // Cause the private key to fail. Connecting again should attempt to use it,
10472 // notice the failure, and then request a new identity via
10473 // OnCertificateRequested.
10474 private_key->set_fail_signing(true);
10475
10476 {
10477 SSLClientAuthTestDelegate d;
10478 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10479 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10480 TRAFFIC_ANNOTATION_FOR_TESTS));
10481
10482 r->Start();
10483 EXPECT_TRUE(r->is_pending());
10484
Wez2a31b222018-06-07 22:07:1510485 d.RunUntilComplete();
David Benjamin76a40ad2018-02-24 22:22:0810486
10487 // There was an additional signing call on the private key (the one which
10488 // failed).
10489 EXPECT_EQ(2, private_key->sign_count());
10490
10491 // That caused another OnCertificateRequested call.
10492 EXPECT_EQ(1, d.on_certificate_requested_count());
10493 EXPECT_FALSE(d.received_data_before_response());
10494 EXPECT_EQ(0, d.bytes_received());
10495 }
10496}
10497
[email protected]316c1e5e2012-09-12 15:17:4410498TEST_F(HTTPSRequestTest, ResumeTest) {
10499 // Test that we attempt a session resume when making two connections to the
10500 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210501 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410502 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210503 SpawnedTestServer test_server(
10504 SpawnedTestServer::TYPE_HTTPS,
10505 ssl_options,
10506 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410507 ASSERT_TRUE(test_server.Start());
10508
10509 SSLClientSocket::ClearSessionCache();
10510
10511 {
10512 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610513 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610514 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10515 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410516
[email protected]f7022f32014-08-21 16:32:1910517 r->Start();
10518 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410519
Wez2a31b222018-06-07 22:07:1510520 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410521
10522 EXPECT_EQ(1, d.response_started_count());
10523 }
10524
10525 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10526 CloseAllConnections();
10527
10528 {
10529 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610530 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610531 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10532 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410533
[email protected]f7022f32014-08-21 16:32:1910534 r->Start();
10535 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410536
Wez2a31b222018-06-07 22:07:1510537 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410538
10539 // The response will look like;
10540 // insert abc
10541 // lookup abc
10542 // insert xyz
10543 //
10544 // With a newline at the end which makes the split think that there are
10545 // four lines.
10546
10547 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910548 std::vector<std::string> lines = base::SplitString(
10549 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410550 ASSERT_EQ(4u, lines.size()) << d.data_received();
10551
10552 std::string session_id;
10553
10554 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910555 std::vector<std::string> parts = base::SplitString(
10556 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410557 ASSERT_EQ(2u, parts.size());
10558 if (i == 0) {
10559 EXPECT_EQ("insert", parts[0]);
10560 session_id = parts[1];
10561 } else {
10562 EXPECT_EQ("lookup", parts[0]);
10563 EXPECT_EQ(session_id, parts[1]);
10564 }
10565 }
10566 }
10567}
10568
Adam Langley32352ad2014-10-14 22:31:0010569// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
10570// the result of fetching "ssl-session-cache" from the test server, indicates
10571// that exactly two different sessions were inserted, with no lookups etc.
10572static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:2910573 std::vector<std::string> lines = base::SplitString(
10574 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010575 ASSERT_EQ(3u, lines.size()) << session_info;
10576
10577 std::string session_id;
10578 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910579 std::vector<std::string> parts = base::SplitString(
10580 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010581 ASSERT_EQ(2u, parts.size());
10582 EXPECT_EQ("insert", parts[0]);
10583 if (i == 0) {
10584 session_id = parts[1];
10585 } else {
10586 EXPECT_NE(session_id, parts[1]);
10587 }
10588 }
10589}
10590
[email protected]316c1e5e2012-09-12 15:17:4410591TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10592 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10593 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210594 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410595 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210596 SpawnedTestServer test_server(
10597 SpawnedTestServer::TYPE_HTTPS,
10598 ssl_options,
10599 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410600 ASSERT_TRUE(test_server.Start());
10601
10602 SSLClientSocket::ClearSessionCache();
10603
10604 {
10605 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610606 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610607 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10608 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410609
[email protected]f7022f32014-08-21 16:32:1910610 r->Start();
10611 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410612
Wez2a31b222018-06-07 22:07:1510613 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410614
10615 EXPECT_EQ(1, d.response_started_count());
10616 }
10617
10618 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110619 HttpNetworkSession::Context session_context;
10620 session_context.host_resolver = default_context_.host_resolver();
10621 session_context.cert_verifier = default_context_.cert_verifier();
10622 session_context.transport_security_state =
10623 default_context_.transport_security_state();
10624 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010625 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110626 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910627 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110628 session_context.ssl_config_service = default_context_.ssl_config_service();
10629 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410630 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110631 session_context.http_server_properties =
10632 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410633
mmenke6ddfbea2017-05-31 21:48:4110634 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10635 session_context);
zhongyi4928bd52017-02-08 02:16:2710636 std::unique_ptr<HttpCache> cache(
10637 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10638 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410639
10640 default_context_.set_http_transaction_factory(cache.get());
10641
10642 {
10643 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610644 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610645 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10646 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410647
[email protected]f7022f32014-08-21 16:32:1910648 r->Start();
10649 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410650
Wez2a31b222018-06-07 22:07:1510651 d.RunUntilComplete();
[email protected]316c1e5e2012-09-12 15:17:4410652
10653 // The response will look like;
10654 // insert abc
10655 // insert xyz
10656 //
10657 // With a newline at the end which makes the split think that there are
10658 // three lines.
10659
10660 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010661 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410662 }
10663}
10664
Bence Béky98447b12018-05-08 03:14:0110665class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510666 public:
fdorayf33fede2017-05-11 21:18:1010667 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410668 ssl_config_service_ = new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5610669 false /* online revocation checking */,
davidben095ebb52017-04-12 22:23:3410670 false /* require rev. checking for local anchors */,
10671 false /* token binding enabled */);
10672 context_.set_ssl_config_service(ssl_config_service_.get());
10673 }
Chris Watkins7a41d3552017-12-01 02:13:2710674 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510675
10676 protected:
davidben095ebb52017-04-12 22:23:3410677 TestSSLConfigService* ssl_config_service() {
10678 return ssl_config_service_.get();
10679 }
10680
[email protected]48d2b7c52014-06-27 01:16:5510681 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10682 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010683 context_.Init();
10684 delegate_.set_allow_certificate_errors(true);
10685
[email protected]48d2b7c52014-06-27 01:16:5510686 SpawnedTestServer test_server(
10687 SpawnedTestServer::TYPE_HTTPS,
10688 ssl_options,
10689 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10690 ASSERT_TRUE(test_server.Start());
10691
tommycli59a63432015-11-06 00:10:5510692 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610693 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510694 request_->Start();
10695
Wez2a31b222018-06-07 22:07:1510696 delegate_.RunUntilComplete();
[email protected]48d2b7c52014-06-27 01:16:5510697 }
10698
davidben095ebb52017-04-12 22:23:3410699 void ExpectConnection(int version) {
10700 EXPECT_EQ(1, delegate_.response_started_count());
10701 EXPECT_NE(0, delegate_.bytes_received());
10702 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10703 request_->ssl_info().connection_status));
10704 }
10705
[email protected]48d2b7c52014-06-27 01:16:5510706 void ExpectFailure(int error) {
10707 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010708 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510709 }
10710
10711 private:
10712 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710713 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610714 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410715 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510716};
10717
davidbenb127ca82015-06-15 19:05:4210718// Tests the TLS 1.0 fallback doesn't happen.
10719TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510720 SpawnedTestServer::SSLOptions ssl_options(
10721 SpawnedTestServer::SSLOptions::CERT_OK);
10722 ssl_options.tls_intolerant =
10723 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10724
10725 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510726 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210727}
10728
davidben5a312152016-06-27 22:11:4710729// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510730TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210731 SpawnedTestServer::SSLOptions ssl_options(
10732 SpawnedTestServer::SSLOptions::CERT_OK);
10733 ssl_options.tls_intolerant =
10734 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10735
10736 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510737 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10738}
10739
davidben095ebb52017-04-12 22:23:3410740// Tests that TLS 1.3 interference results in a dedicated error code.
10741TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10742 SpawnedTestServer::SSLOptions ssl_options(
10743 SpawnedTestServer::SSLOptions::CERT_OK);
10744 ssl_options.tls_intolerant =
10745 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10746 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10747
10748 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10749 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10750}
10751
10752// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10753TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10754 SpawnedTestServer::SSLOptions ssl_options(
10755 SpawnedTestServer::SSLOptions::CERT_OK);
10756 ssl_options.tls_intolerant =
10757 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10758 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10759
10760 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10761 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10762}
10763
Bence Béky98447b12018-05-08 03:14:0110764class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410765 public:
fdorayf33fede2017-05-11 21:18:1010766 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910767 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410768
10769 default_context_.set_network_delegate(&default_network_delegate_);
10770 default_context_.set_cert_verifier(&cert_verifier_);
10771 default_context_.Init();
10772 }
Chris Watkins7a41d3552017-12-01 02:13:2710773 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410774
10775 protected:
10776 MockCertVerifier cert_verifier_;
10777 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10778 TestURLRequestContext default_context_;
10779};
10780
10781// Tests that session resumption is not attempted if an invalid certificate
10782// is presented.
10783TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10784 SpawnedTestServer::SSLOptions ssl_options;
10785 ssl_options.record_resume = true;
10786 SpawnedTestServer test_server(
10787 SpawnedTestServer::TYPE_HTTPS,
10788 ssl_options,
10789 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10790 ASSERT_TRUE(test_server.Start());
10791
10792 SSLClientSocket::ClearSessionCache();
10793
10794 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910795 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410796 {
10797 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610798 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610799 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10800 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410801
[email protected]f7022f32014-08-21 16:32:1910802 r->Start();
10803 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410804
Wez2a31b222018-06-07 22:07:1510805 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410806
10807 EXPECT_EQ(1, d.response_started_count());
10808 }
10809
10810 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10811 CloseAllConnections();
10812
10813 // Now change the certificate to be acceptable (so that the response is
10814 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910815 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410816 {
10817 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610818 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610819 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10820 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410821
[email protected]f7022f32014-08-21 16:32:1910822 r->Start();
10823 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410824
Wez2a31b222018-06-07 22:07:1510825 d.RunUntilComplete();
[email protected]a8fed1742013-12-27 02:14:2410826
10827 // The response will look like;
10828 // insert abc
10829 // insert xyz
10830 //
10831 // With a newline at the end which makes the split think that there are
10832 // three lines.
10833 //
10834 // If a session was presented (eg: a bug), then the response would look
10835 // like;
10836 // insert abc
10837 // lookup abc
10838 // insert xyz
10839
10840 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010841 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410842 }
10843}
10844
[email protected]dffe8242012-03-20 15:14:2710845// This the fingerprint of the "Testing CA" certificate used by the testserver.
10846// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810847static const SHA256HashValue kOCSPTestCertFingerprint = {{
10848 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10849 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10850 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510851}};
[email protected]dffe8242012-03-20 15:14:2710852
[email protected]51523f52013-07-31 21:57:2810853// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10854// testserver.
mattm0b12a6f2016-11-29 19:57:1610855static const SHA256HashValue kOCSPTestCertSPKI = {{
10856 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10857 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10858 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10859}};
[email protected]51523f52013-07-31 21:57:2810860
[email protected]dffe8242012-03-20 15:14:2710861// This is the policy OID contained in the certificates that testserver
10862// generates.
10863static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10864
10865class HTTPSOCSPTest : public HTTPSRequestTest {
10866 public:
10867 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910868 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810869 ev_test_policy_(
10870 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10871 kOCSPTestCertFingerprint,
10872 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210873 }
10874
dcheng67be2b1f2014-10-27 21:47:2910875 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310876 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010877 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910878 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710879
[email protected]cba24642014-08-15 20:49:5910880 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010881 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210882 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010883 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710884
Matt Muellerfb271992018-01-30 18:10:4810885#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510886 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10887#endif
10888
svaldez2135be52016-04-20 16:34:5310889#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910890 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710891#endif
10892 }
10893
dadrian612337a2016-07-20 22:36:5810894 void DoConnectionWithDelegate(
10895 const SpawnedTestServer::SSLOptions& ssl_options,
10896 TestDelegate* delegate,
10897 SSLInfo* out_ssl_info) {
10898 // Always overwrite |out_ssl_info|.
10899 out_ssl_info->Reset();
10900
[email protected]ce7d0cbc2013-05-03 18:57:2210901 SpawnedTestServer test_server(
10902 SpawnedTestServer::TYPE_HTTPS,
10903 ssl_options,
10904 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710905 ASSERT_TRUE(test_server.Start());
10906
dadrian612337a2016-07-20 22:36:5810907 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610908 std::unique_ptr<URLRequest> r(
10909 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10910 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910911 r->Start();
[email protected]dffe8242012-03-20 15:14:2710912
Wez2a31b222018-06-07 22:07:1510913 delegate->RunUntilComplete();
dadrian612337a2016-07-20 22:36:5810914 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710915
dadrian612337a2016-07-20 22:36:5810916 *out_ssl_info = r->ssl_info();
10917 }
10918
10919 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10920 CertStatus* out_cert_status) {
10921 // Always overwrite |out_cert_status|.
10922 *out_cert_status = 0;
10923
10924 TestDelegate d;
10925 SSLInfo ssl_info;
10926 ASSERT_NO_FATAL_FAILURE(
10927 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10928
10929 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710930 }
10931
dcheng67be2b1f2014-10-27 21:47:2910932 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810933#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510934 ShutdownGlobalCertNetFetcher();
10935#endif
10936
svaldez2135be52016-04-20 16:34:5310937#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810938 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710939#endif
10940 }
10941
[email protected]a13234c2012-03-20 21:45:0210942 protected:
10943 // SetupContext configures the URLRequestContext that will be used for making
10944 // connetions to testserver. This can be overridden in test subclasses for
10945 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010946 virtual void SetupContext() {
Ryan Sleevi5b4702a2018-04-06 22:23:5610947 context_.set_ssl_config_service(
10948 new TestSSLConfigService(true /* online revocation checking */,
10949 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1410950 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5610951 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210952 }
10953
danakj8522a25b2016-04-16 00:17:3610954 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910955 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610956 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710957};
10958
[email protected]a13234c2012-03-20 21:45:0210959static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010960#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210961 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10962 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410963 // TODO(eroman): Should this also be the return value for
10964 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210965 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10966#else
10967 return 0;
10968#endif
10969}
10970
[email protected]3a86a712013-07-30 07:16:2010971// SystemSupportsHardFailRevocationChecking returns true iff the current
10972// operating system supports revocation checking and can distinguish between
10973// situations where a given certificate lacks any revocation information (eg:
10974// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10975// revocation information cannot be obtained (eg: the CRL was unreachable).
10976// If it does not, then tests which rely on 'hard fail' behaviour should be
10977// skipped.
10978static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410979#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10980 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010981 return true;
10982#else
10983 return false;
10984#endif
10985}
10986
[email protected]a13234c2012-03-20 21:45:0210987// SystemUsesChromiumEVMetadata returns true iff the current operating system
10988// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10989// several tests are effected because our testing EV certificate won't be
10990// recognised as EV.
10991static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210992#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110993 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210994#else
10995 return false;
[email protected]05454a432012-03-20 20:04:0110996#endif
10997}
10998
mattmaf868e72016-09-23 23:25:2010999// Returns the expected CertStatus for tests that expect an online revocation
11000// check failure as a result of checking a test EV cert, which will not
11001// actually trigger an online revocation check on some platforms.
11002static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
11003 if (SystemUsesChromiumEVMetadata()) {
11004 return ExpectedCertStatusForFailedOnlineRevocationCheck();
11005 } else {
11006 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
11007 // be enabled, and thus there will not be a revocation check to fail.
11008 return 0u;
11009 }
11010}
11011
[email protected]b6f2de32012-08-17 04:35:0811012static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3911013#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0211014 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
11015 return false;
11016#else
11017 return true;
11018#endif
11019}
11020
davidbend1fb2f12014-11-08 02:51:0011021static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0411022#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
11023 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0311024 return true;
mathpc992e602015-10-21 20:34:0311025#else
11026 return false;
11027#endif
davidbend1fb2f12014-11-08 02:51:0011028}
11029
[email protected]dffe8242012-03-20 15:14:2711030TEST_F(HTTPSOCSPTest, Valid) {
11031 if (!SystemSupportsOCSP()) {
11032 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11033 return;
11034 }
11035
[email protected]ce7d0cbc2013-05-03 18:57:2211036 SpawnedTestServer::SSLOptions ssl_options(
11037 SpawnedTestServer::SSLOptions::CERT_AUTO);
11038 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2711039
[email protected]924e9f92012-12-16 22:00:5311040 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211041 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711042
11043 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11044
[email protected]a13234c2012-03-20 21:45:0211045 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11046 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2711047
11048 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11049}
11050
11051TEST_F(HTTPSOCSPTest, Revoked) {
11052 if (!SystemSupportsOCSP()) {
11053 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11054 return;
11055 }
11056
[email protected]ce7d0cbc2013-05-03 18:57:2211057 SpawnedTestServer::SSLOptions ssl_options(
11058 SpawnedTestServer::SSLOptions::CERT_AUTO);
11059 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2711060
11061 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211062 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711063
[email protected]dffe8242012-03-20 15:14:2711064 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2711065 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11066 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11067}
11068
11069TEST_F(HTTPSOCSPTest, Invalid) {
11070 if (!SystemSupportsOCSP()) {
11071 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11072 return;
11073 }
11074
[email protected]ce7d0cbc2013-05-03 18:57:2211075 SpawnedTestServer::SSLOptions ssl_options(
11076 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811077 ssl_options.ocsp_status =
11078 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2711079
[email protected]924e9f92012-12-16 22:00:5311080 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211081 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2711082
Eric Roman1b628daa2017-10-19 19:52:0411083#if defined(USE_BUILTIN_CERT_VERIFIER)
11084 // TODO(649017): This test uses soft-fail revocation checking, but returns an
11085 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
11086 // doesn't consider this a candidate for soft-fail (only considers
11087 // network-level failures as skippable).
11088 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11089 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11090#else
[email protected]a13234c2012-03-20 21:45:0211091 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2711092 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0411093#endif
[email protected]dffe8242012-03-20 15:14:2711094
11095 // Without a positive OCSP response, we shouldn't show the EV status.
11096 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11097 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11098}
[email protected]a13234c2012-03-20 21:45:0211099
Matt Mueller5339d862018-05-02 18:53:5711100TEST_F(HTTPSOCSPTest, IntermediateValid) {
11101 if (!SystemSupportsOCSP()) {
11102 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11103 return;
11104 }
11105
11106 SpawnedTestServer::SSLOptions ssl_options(
11107 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11108 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11109 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11110
11111 CertStatus cert_status;
11112 DoConnection(ssl_options, &cert_status);
11113
11114 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11115
11116 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11117 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11118
11119 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11120}
11121
11122TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11123 if (!SystemSupportsOCSP()) {
11124 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11125 return;
11126 }
11127
11128 SpawnedTestServer::SSLOptions ssl_options(
11129 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11130 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11131 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11132 // Use an OCSP response for the intermediate that would be too old for a leaf
11133 // cert, but is still valid for an intermediate.
11134 ssl_options.ocsp_intermediate_date =
11135 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11136
11137 CertStatus cert_status;
11138 DoConnection(ssl_options, &cert_status);
11139
11140 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11141
11142 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11143 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11144
11145 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11146}
11147
11148TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11149 if (!SystemSupportsOCSP()) {
11150 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11151 return;
11152 }
11153
11154 SpawnedTestServer::SSLOptions ssl_options(
11155 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11156 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11157 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11158 ssl_options.ocsp_intermediate_date =
11159 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11160
11161 CertStatus cert_status;
11162 DoConnection(ssl_options, &cert_status);
11163
11164#if defined(USE_BUILTIN_CERT_VERIFIER)
11165 // The builtin verifier enforces the baseline requirements for max age of an
11166 // intermediate's OCSP response.
11167 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11168 cert_status & CERT_STATUS_ALL_ERRORS);
11169 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11170#else
11171 // The platform verifiers are more lenient.
11172 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11173 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11174 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11175#endif
11176 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11177}
11178
11179TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11180 if (!SystemSupportsOCSP()) {
11181 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11182 return;
11183 }
11184
11185 SpawnedTestServer::SSLOptions ssl_options(
11186 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11187 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11188 ssl_options.ocsp_intermediate_status =
11189 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11190
11191 CertStatus cert_status;
11192 DoConnection(ssl_options, &cert_status);
11193
11194#if defined(OS_WIN)
11195 // TODO(mattm): why does CertVerifyProcWin accept this?
11196 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11197#else
11198 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11199#endif
11200 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11201 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11202}
11203
davidbend1fb2f12014-11-08 02:51:0011204TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311205 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011206 LOG(WARNING)
11207 << "Skipping test because system doesn't support OCSP stapling";
11208 return;
11209 }
11210
11211 SpawnedTestServer::SSLOptions ssl_options(
11212 SpawnedTestServer::SSLOptions::CERT_AUTO);
11213 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11214 ssl_options.staple_ocsp_response = true;
11215 ssl_options.ocsp_server_unavailable = true;
11216
11217 CertStatus cert_status;
11218 DoConnection(ssl_options, &cert_status);
11219
11220 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11221
11222 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11223 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11224
11225 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11226}
11227
davidben6c3191b2014-11-21 22:38:0411228// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811229#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411230#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11231#else
11232#define MAYBE_RevokedStapled RevokedStapled
11233#endif
11234TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311235 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011236 LOG(WARNING)
11237 << "Skipping test because system doesn't support OCSP stapling";
11238 return;
11239 }
11240
11241 SpawnedTestServer::SSLOptions ssl_options(
11242 SpawnedTestServer::SSLOptions::CERT_AUTO);
11243 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11244 ssl_options.staple_ocsp_response = true;
11245 ssl_options.ocsp_server_unavailable = true;
11246
11247 CertStatus cert_status;
11248 DoConnection(ssl_options, &cert_status);
11249
11250 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11251 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11252 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11253}
11254
dadriand476e652016-07-26 21:33:2411255TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
Martijn Croonenb1383da2017-10-11 11:56:3511256 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
11257
dadriand476e652016-07-26 21:33:2411258 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11259 https_test_server.SetSSLConfig(
11260 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11261 https_test_server.ServeFilesFromSourceDirectory(
11262 base::FilePath(kTestFilePath));
11263 ASSERT_TRUE(https_test_server.Start());
11264
11265 // Set up a MockCertVerifier to accept the certificate that the server sends,
11266 // but not provide any OCSP information.
11267 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11268 ASSERT_TRUE(cert);
11269 MockCertVerifier cert_verifier;
11270 CertVerifyResult verify_result;
11271 verify_result.verified_cert = cert;
11272 verify_result.is_issued_by_known_root = true;
11273 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11274 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11275
11276 // Catch the Expect-Staple report.
11277 TransportSecurityState transport_security_state;
11278 MockCertificateReportSender mock_report_sender;
11279 transport_security_state.SetReportSender(&mock_report_sender);
11280
11281 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11282 // that the request can be sent to a site on the Expect-Staple preload list.
11283 MockHostResolver host_resolver;
11284 TestNetworkDelegate network_delegate;
11285 TestURLRequestContext context(true);
11286 context.set_host_resolver(&host_resolver);
11287 context.set_transport_security_state(&transport_security_state);
11288 context.set_network_delegate(&network_delegate);
11289 context.set_cert_verifier(&cert_verifier);
11290 context.Init();
11291
11292 // Now send a request to trigger the violation.
11293 TestDelegate d;
11294 GURL url = https_test_server.GetURL("/");
11295 GURL::Replacements replace_host;
11296 replace_host.SetHostStr(kExpectStapleStaticHostname);
11297 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611298 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11299 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411300 violating_request->Start();
Wez2a31b222018-06-07 22:07:1511301 d.RunUntilComplete();
dadriand476e652016-07-26 21:33:2411302
11303 // Confirm a report was sent.
11304 EXPECT_FALSE(mock_report_sender.latest_report().empty());
11305 EXPECT_EQ(GURL(kExpectStapleReportURI),
11306 mock_report_sender.latest_report_uri());
11307}
11308
estark13e0b312016-12-22 23:52:3211309// Tests that Expect-Staple reports are not sent for connections on which there
11310// is a certificate error.
11311TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
11312 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11313 https_test_server.SetSSLConfig(
11314 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11315 https_test_server.ServeFilesFromSourceDirectory(
11316 base::FilePath(kTestFilePath));
11317 ASSERT_TRUE(https_test_server.Start());
11318
11319 // Set up a MockCertVerifier to report an error for the certificate
11320 // and indicate that there was no stapled OCSP response.
11321 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11322 ASSERT_TRUE(cert);
11323 MockCertVerifier cert_verifier;
11324 CertVerifyResult verify_result;
11325 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
11326 verify_result.verified_cert = cert;
11327 verify_result.is_issued_by_known_root = true;
11328 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11329 cert_verifier.AddResultForCert(cert.get(), verify_result,
11330 ERR_CERT_DATE_INVALID);
11331
11332 // Set up a mock report sender so that the test can check that an
11333 // Expect-Staple report is not sent.
11334 TransportSecurityState transport_security_state;
11335 MockCertificateReportSender mock_report_sender;
11336 transport_security_state.SetReportSender(&mock_report_sender);
11337
11338 TestNetworkDelegate network_delegate;
11339 TestURLRequestContext context(true);
11340
11341 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11342 MockHostResolver host_resolver;
11343 context.set_host_resolver(&host_resolver);
11344
11345 context.set_transport_security_state(&transport_security_state);
11346 context.set_network_delegate(&network_delegate);
11347 context.set_cert_verifier(&cert_verifier);
11348 context.Init();
11349
11350 // Make a connection to |kExpectStapleStaticHostname|. Because the
11351 // |verify_result| used with the |cert_verifier| will indicate a certificate
11352 // error, an Expect-Staple report should not be sent.
11353 TestDelegate d;
11354 GURL url = https_test_server.GetURL("/");
11355 GURL::Replacements replace_host;
11356 replace_host.SetHostStr(kExpectStapleStaticHostname);
11357 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611358 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11359 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211360 violating_request->Start();
Wez2a31b222018-06-07 22:07:1511361 d.RunUntilComplete();
estark13e0b312016-12-22 23:52:3211362
11363 // Confirm a report was not sent.
11364 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11365 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11366}
11367
dadriand476e652016-07-26 21:33:2411368TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
11369 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11370 https_test_server.SetSSLConfig(
11371 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11372 https_test_server.ServeFilesFromSourceDirectory(
11373 base::FilePath(kTestFilePath));
11374 ASSERT_TRUE(https_test_server.Start());
11375
11376 // Set up a MockCertVerifier to accept the certificate that the server sends,
11377 // and provide GOOD revocation status.
11378 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11379 ASSERT_TRUE(cert);
11380 MockCertVerifier cert_verifier;
11381 CertVerifyResult verify_result;
11382 verify_result.verified_cert = cert;
11383 verify_result.is_issued_by_known_root = true;
11384 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
11385 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
11386 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11387
11388 // Catch the Expect-Staple report.
11389 TransportSecurityState transport_security_state;
11390 MockCertificateReportSender mock_report_sender;
11391 transport_security_state.SetReportSender(&mock_report_sender);
11392
11393 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11394 // that the request can be sent to a site on the Expect-Staple preload list.
11395 MockHostResolver host_resolver;
11396 TestNetworkDelegate network_delegate;
11397 TestURLRequestContext context(true);
11398 context.set_host_resolver(&host_resolver);
11399 context.set_transport_security_state(&transport_security_state);
11400 context.set_network_delegate(&network_delegate);
11401 context.set_cert_verifier(&cert_verifier);
11402 context.Init();
11403
11404 // This request should not not trigger an Expect-Staple violation.
11405 TestDelegate d;
11406 GURL url = https_test_server.GetURL("/");
11407 GURL::Replacements replace_host;
11408 replace_host.SetHostStr(kExpectStapleStaticHostname);
11409 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611410 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11411 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411412 ok_request->Start();
Wez2a31b222018-06-07 22:07:1511413 d.RunUntilComplete();
dadriand476e652016-07-26 21:33:2411414
11415 // Check that no report was sent.
11416 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11417 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11418}
11419
estark13e0b312016-12-22 23:52:3211420// Tests that an Expect-Staple report is not sent when OCSP details are not
11421// checked on the connection.
11422TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
11423 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11424 https_test_server.SetSSLConfig(
11425 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11426 https_test_server.ServeFilesFromSourceDirectory(
11427 base::FilePath(kTestFilePath));
11428 ASSERT_TRUE(https_test_server.Start());
11429
11430 // Set up a MockCertVerifier to accept the certificate that the server sends,
11431 // and set |ocsp_result| to indicate that OCSP stapling details were not
11432 // checked on the connection.
11433 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11434 ASSERT_TRUE(cert);
11435 MockCertVerifier cert_verifier;
11436 CertVerifyResult verify_result;
11437 verify_result.verified_cert = cert;
11438 verify_result.is_issued_by_known_root = true;
11439 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
11440 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11441
11442 // Set up a mock report sender so that the test can check that an
11443 // Expect-Staple report is not sent.
11444 TransportSecurityState transport_security_state;
11445 MockCertificateReportSender mock_report_sender;
11446 transport_security_state.SetReportSender(&mock_report_sender);
11447
11448 TestNetworkDelegate network_delegate;
11449 TestURLRequestContext context(true);
11450
11451 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11452 MockHostResolver host_resolver;
11453 context.set_host_resolver(&host_resolver);
11454
11455 context.set_transport_security_state(&transport_security_state);
11456 context.set_network_delegate(&network_delegate);
11457 context.set_cert_verifier(&cert_verifier);
11458 context.Init();
11459
11460 // Make a connection to |kExpectStapleStaticHostname|. Because the
11461 // |verify_result| used with the |cert_verifier| will indicate that OCSP
11462 // stapling details were not checked on the connection, an Expect-Staple
11463 // report should not be sent.
11464 TestDelegate d;
11465 GURL url = https_test_server.GetURL("/");
11466 GURL::Replacements replace_host;
11467 replace_host.SetHostStr(kExpectStapleStaticHostname);
11468 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611469 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11470 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211471 ok_request->Start();
Wez2a31b222018-06-07 22:07:1511472 d.RunUntilComplete();
estark13e0b312016-12-22 23:52:3211473
11474 // Check that no report was sent.
11475 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11476 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11477}
11478
dadrian612337a2016-07-20 22:36:5811479static const struct OCSPVerifyTestData {
11480 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11481 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11482 OCSPVerifyResult::ResponseStatus response_status;
11483 bool has_revocation_status;
11484 OCSPRevocationStatus cert_status;
11485} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111486 // 0
dadrian612337a2016-07-20 22:36:5811487 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11488 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11489 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11490 OCSPVerifyResult::PROVIDED,
11491 true,
11492 OCSPRevocationStatus::GOOD},
11493
Eric Roman8673b812017-09-20 18:57:3111494 // 1
dadrian612337a2016-07-20 22:36:5811495 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11496 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11497 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11498 OCSPVerifyResult::INVALID_DATE,
11499 false,
11500 OCSPRevocationStatus::UNKNOWN},
11501
Eric Roman8673b812017-09-20 18:57:3111502 // 2
dadrian612337a2016-07-20 22:36:5811503 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11504 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11505 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11506 OCSPVerifyResult::INVALID_DATE,
11507 false,
11508 OCSPRevocationStatus::UNKNOWN},
11509
Eric Roman8673b812017-09-20 18:57:3111510 // 3
dadrian612337a2016-07-20 22:36:5811511 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11512 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11513 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11514 OCSPVerifyResult::INVALID_DATE,
11515 false,
11516 OCSPRevocationStatus::UNKNOWN},
11517
Eric Roman8673b812017-09-20 18:57:3111518 // 4
dadrian612337a2016-07-20 22:36:5811519 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11520 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11521 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11522 OCSPVerifyResult::INVALID_DATE,
11523 false,
11524 OCSPRevocationStatus::UNKNOWN},
11525
Eric Roman8673b812017-09-20 18:57:3111526 // 5
dadrian612337a2016-07-20 22:36:5811527 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11528 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11529 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11530 OCSPVerifyResult::ERROR_RESPONSE,
11531 false,
11532 OCSPRevocationStatus::UNKNOWN},
11533
Eric Roman8673b812017-09-20 18:57:3111534 // 6
dadrian612337a2016-07-20 22:36:5811535 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11536 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11537 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11538 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11539 false,
11540 OCSPRevocationStatus::UNKNOWN},
11541
Eric Roman8673b812017-09-20 18:57:3111542 // 7
dadrian612337a2016-07-20 22:36:5811543 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11544 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11545 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11546 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11547 false,
11548 OCSPRevocationStatus::UNKNOWN},
11549
Eric Roman8673b812017-09-20 18:57:3111550 // 8
dadrian612337a2016-07-20 22:36:5811551 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11552 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11553 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11554 OCSPVerifyResult::INVALID_DATE,
11555 false,
11556 OCSPRevocationStatus::UNKNOWN},
11557
Eric Roman8673b812017-09-20 18:57:3111558 // 9
dadrian612337a2016-07-20 22:36:5811559 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11560 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11561 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11562 OCSPVerifyResult::PROVIDED,
11563 true,
11564 OCSPRevocationStatus::UNKNOWN},
11565
Eric Roman8673b812017-09-20 18:57:3111566 // 10
dadrian612337a2016-07-20 22:36:5811567 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11568 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11569 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11570 OCSPVerifyResult::INVALID_DATE,
11571 false,
11572 OCSPRevocationStatus::UNKNOWN},
11573
Eric Roman8673b812017-09-20 18:57:3111574 // 11
dadrian612337a2016-07-20 22:36:5811575 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11576 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11577 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11578 OCSPVerifyResult::INVALID_DATE,
11579 false,
11580 OCSPRevocationStatus::UNKNOWN},
11581
Eric Roman8673b812017-09-20 18:57:3111582 // 12
dadrian612337a2016-07-20 22:36:5811583 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11584 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11585 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11586 OCSPVerifyResult::BAD_PRODUCED_AT,
11587 false,
11588 OCSPRevocationStatus::UNKNOWN},
11589
Eric Roman8673b812017-09-20 18:57:3111590 // 13
dadrian612337a2016-07-20 22:36:5811591 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11592 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11593 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11594 OCSPVerifyResult::BAD_PRODUCED_AT,
11595 false,
11596 OCSPRevocationStatus::UNKNOWN},
11597
Eric Roman8673b812017-09-20 18:57:3111598 // 14
dadrian612337a2016-07-20 22:36:5811599 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11600 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11601 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11602 OCSPVerifyResult::BAD_PRODUCED_AT,
11603 false,
11604 OCSPRevocationStatus::UNKNOWN},
11605
Eric Roman8673b812017-09-20 18:57:3111606 // 15
dadrian612337a2016-07-20 22:36:5811607 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11608 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11609 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11610 OCSPVerifyResult::PROVIDED,
11611 true,
11612 OCSPRevocationStatus::GOOD},
11613
Eric Roman8673b812017-09-20 18:57:3111614 // 16
dadrian612337a2016-07-20 22:36:5811615 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11616 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11617 {SpawnedTestServer::SSLOptions::OCSP_OK,
11618 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11619 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11620 OCSPVerifyResult::PROVIDED,
11621 true,
11622 OCSPRevocationStatus::GOOD},
11623
Eric Roman8673b812017-09-20 18:57:3111624 // 17
dadrian612337a2016-07-20 22:36:5811625 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11626 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11627 {SpawnedTestServer::SSLOptions::OCSP_OK,
11628 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11629 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11630 OCSPVerifyResult::PROVIDED,
11631 true,
11632 OCSPRevocationStatus::GOOD},
11633
Eric Roman8673b812017-09-20 18:57:3111634 // 18
dadrian612337a2016-07-20 22:36:5811635 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11636 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11637 {SpawnedTestServer::SSLOptions::OCSP_OK,
11638 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11639 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11640 OCSPVerifyResult::PROVIDED,
11641 true,
11642 OCSPRevocationStatus::GOOD},
11643
Eric Roman8673b812017-09-20 18:57:3111644 // 19
dadrian612337a2016-07-20 22:36:5811645 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11646 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11647 {SpawnedTestServer::SSLOptions::OCSP_OK,
11648 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11649 {SpawnedTestServer::SSLOptions::OCSP_OK,
11650 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11651 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11652 OCSPVerifyResult::INVALID_DATE,
11653 false,
11654 OCSPRevocationStatus::UNKNOWN},
11655
Eric Roman8673b812017-09-20 18:57:3111656 // 20
dadrian612337a2016-07-20 22:36:5811657 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11658 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11659 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11660 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11661 {SpawnedTestServer::SSLOptions::OCSP_OK,
11662 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11663 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11664 OCSPVerifyResult::PROVIDED,
11665 true,
11666 OCSPRevocationStatus::REVOKED},
11667
Eric Roman8673b812017-09-20 18:57:3111668 // 21
dadrian612337a2016-07-20 22:36:5811669 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11670 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11671 {SpawnedTestServer::SSLOptions::OCSP_OK,
11672 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11673 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11674 OCSPVerifyResult::PROVIDED,
11675 true,
11676 OCSPRevocationStatus::UNKNOWN},
11677
Eric Roman8673b812017-09-20 18:57:3111678 // 22
dadrian612337a2016-07-20 22:36:5811679 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11680 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11681 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11682 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11683 {SpawnedTestServer::SSLOptions::OCSP_OK,
11684 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11685 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11686 OCSPVerifyResult::PROVIDED,
11687 true,
11688 OCSPRevocationStatus::UNKNOWN},
11689
Eric Roman8673b812017-09-20 18:57:3111690 // 23
dadrian612337a2016-07-20 22:36:5811691 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11692 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11693 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11694 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11695 false,
11696 OCSPRevocationStatus::UNKNOWN},
11697
Eric Roman8673b812017-09-20 18:57:3111698 // 24
dadrian612337a2016-07-20 22:36:5811699 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11700 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11701 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11702 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11703 false,
11704 OCSPRevocationStatus::UNKNOWN},
11705
Eric Roman8673b812017-09-20 18:57:3111706// These tests fail when using NSS for certificate verification, as NSS fails
11707// and doesn't return the partial path. As a result the OCSP checks being done
11708// at the CertVerifyProc layer cannot access the issuer certificate.
11709#if !defined(USE_NSS_CERTS)
11710 // 25
11711 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11712 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11713 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11714 OCSPVerifyResult::PROVIDED,
11715 true,
11716 OCSPRevocationStatus::REVOKED},
11717
11718 // 26
11719 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11720 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11721 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11722 OCSPVerifyResult::INVALID_DATE,
11723 false,
11724 OCSPRevocationStatus::UNKNOWN},
11725
11726 // 27
11727 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11728 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11729 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11730 OCSPVerifyResult::INVALID_DATE,
11731 false,
11732 OCSPRevocationStatus::UNKNOWN},
11733#endif
dadrian612337a2016-07-20 22:36:5811734};
11735
11736class HTTPSOCSPVerifyTest
11737 : public HTTPSOCSPTest,
11738 public testing::WithParamInterface<OCSPVerifyTestData> {};
11739
11740TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11741 SpawnedTestServer::SSLOptions ssl_options(
11742 SpawnedTestServer::SSLOptions::CERT_AUTO);
11743 OCSPVerifyTestData test = GetParam();
11744
11745 ssl_options.ocsp_responses = test.ocsp_responses;
11746 ssl_options.ocsp_produced = test.ocsp_produced;
11747 ssl_options.staple_ocsp_response = true;
11748
11749 SSLInfo ssl_info;
11750 OCSPErrorTestDelegate delegate;
11751 ASSERT_NO_FATAL_FAILURE(
11752 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11753
11754 // The SSLInfo must be extracted from |delegate| on error, due to how
11755 // URLRequest caches certificate errors.
11756 if (delegate.have_certificate_errors()) {
11757 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11758 ssl_info = delegate.ssl_info();
11759 }
11760
11761 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11762
11763 if (test.has_revocation_status)
11764 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11765}
11766
11767INSTANTIATE_TEST_CASE_P(OCSPVerify,
11768 HTTPSOCSPVerifyTest,
11769 testing::ValuesIn(kOCSPVerifyData));
11770
mattm0b12a6f2016-11-29 19:57:1611771class HTTPSAIATest : public HTTPSOCSPTest {
11772 public:
11773 void SetupContext() override {
11774 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611775 false /* online revocation checking */,
mattm0b12a6f2016-11-29 19:57:1611776 false /* require rev. checking for local anchors */,
11777 false /* token binding enabled */));
11778 }
11779};
11780
11781TEST_F(HTTPSAIATest, AIAFetching) {
11782 SpawnedTestServer::SSLOptions ssl_options(
11783 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11784 SpawnedTestServer test_server(
11785 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11786 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11787 ASSERT_TRUE(test_server.Start());
11788
Ryan Sleevi5b4702a2018-04-06 22:23:5611789 // Unmark the certificate's OID as EV, which will disable revocation
11790 // checking.
11791 ev_test_policy_.reset();
11792
mattm0b12a6f2016-11-29 19:57:1611793 TestDelegate d;
11794 d.set_allow_certificate_errors(true);
11795 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611796 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11797 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611798
11799 r->Start();
11800 EXPECT_TRUE(r->is_pending());
11801
Wez2a31b222018-06-07 22:07:1511802 d.RunUntilComplete();
mattm0b12a6f2016-11-29 19:57:1611803
11804 EXPECT_EQ(1, d.response_started_count());
11805
11806 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811807 EXPECT_EQ(OK, d.request_status());
11808 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11809 ASSERT_TRUE(r->ssl_info().cert);
11810 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611811 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411812 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611813}
11814
[email protected]3a86a712013-07-30 07:16:2011815class HTTPSHardFailTest : public HTTPSOCSPTest {
11816 protected:
rsleevid6de8302016-06-21 01:33:2011817 void SetupContext() override {
11818 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611819 false /* online revocation checking */,
11820 true /* require rev. checking for local anchors */,
nharperb7441ef2016-01-25 23:54:1411821 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011822 }
11823};
11824
[email protected]3a86a712013-07-30 07:16:2011825TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11826 if (!SystemSupportsOCSP()) {
11827 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11828 return;
11829 }
11830
11831 if (!SystemSupportsHardFailRevocationChecking()) {
11832 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11833 << "revocation checking";
11834 return;
11835 }
11836
11837 SpawnedTestServer::SSLOptions ssl_options(
11838 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811839 ssl_options.ocsp_status =
11840 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011841
11842 CertStatus cert_status;
11843 DoConnection(ssl_options, &cert_status);
11844
Eric Roman1b628daa2017-10-19 19:52:0411845#if defined(USE_BUILTIN_CERT_VERIFIER)
11846 // TODO(crbug.com/649017): Should we consider invalid response as
11847 // affirmatively revoked?
11848 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11849 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11850#else
11851 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11852#endif
[email protected]3a86a712013-07-30 07:16:2011853
11854 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411855 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011856 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11857}
11858
[email protected]a13234c2012-03-20 21:45:0211859class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11860 protected:
rsleevid6de8302016-06-21 01:33:2011861 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611862 context_.set_ssl_config_service(
11863 new TestSSLConfigService(false /* online revocation checking */,
11864 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411865 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611866 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211867 }
11868};
11869
Eric Romane2243cc62017-10-17 03:59:1311870// Helper class to set the global CRLSet, and on destruction restore the
11871// previously set one.
11872class ScopedSetCRLSet {
11873 public:
11874 ScopedSetCRLSet(scoped_refptr<CRLSet> crl_set) {
11875 prev_crl_set_ = SSLConfigService::GetCRLSet();
11876 SSLConfigService::SetCRLSetForTesting(std::move(crl_set));
11877 }
11878
11879 ~ScopedSetCRLSet() {
11880 SSLConfigService::SetCRLSetForTesting(std::move(prev_crl_set_));
11881 }
11882
11883 private:
11884 scoped_refptr<CRLSet> prev_crl_set_;
11885};
11886
[email protected]a13234c2012-03-20 21:45:0211887TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11888 if (!SystemSupportsOCSP()) {
11889 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11890 return;
11891 }
11892
[email protected]ce7d0cbc2013-05-03 18:57:2211893 SpawnedTestServer::SSLOptions ssl_options(
11894 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811895 ssl_options.ocsp_status =
11896 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311897 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211898
[email protected]924e9f92012-12-16 22:00:5311899 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211900 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211901
mattmaf868e72016-09-23 23:25:2011902 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211903 cert_status & CERT_STATUS_ALL_ERRORS);
11904
11905 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811906 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11907 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211908}
11909
[email protected]be0fff62013-08-29 23:37:4811910TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11911 if (!SystemSupportsOCSP()) {
11912 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11913 return;
11914 }
11915
11916 SpawnedTestServer::SSLOptions ssl_options(
11917 SpawnedTestServer::SSLOptions::CERT_AUTO);
11918 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Eric Romane2243cc62017-10-17 03:59:1311919 ScopedSetCRLSet set_crlset(nullptr);
[email protected]be0fff62013-08-29 23:37:4811920
11921 CertStatus cert_status;
11922 DoConnection(ssl_options, &cert_status);
11923
mattm1a282f52016-11-10 21:49:4211924// Currently only works for Windows and OS X. When using NSS, it's not
11925// possible to determine whether the check failed because of actual
11926// revocation or because there was an OCSP failure.
11927#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811928 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11929#else
11930 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11931#endif
11932
11933 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11934 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11935 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11936}
11937
[email protected]a13234c2012-03-20 21:45:0211938TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11939 if (!SystemSupportsOCSP()) {
11940 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11941 return;
11942 }
11943
[email protected]ce7d0cbc2013-05-03 18:57:2211944 SpawnedTestServer::SSLOptions ssl_options(
11945 SpawnedTestServer::SSLOptions::CERT_AUTO);
11946 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
Eric Romane2243cc62017-10-17 03:59:1311947 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211948
11949 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211950 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211951
11952 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11953
11954 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11955 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811956 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11957 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211958}
11959
11960TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11961 if (!SystemSupportsOCSP()) {
11962 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11963 return;
11964 }
11965
[email protected]ce7d0cbc2013-05-03 18:57:2211966 SpawnedTestServer::SSLOptions ssl_options(
11967 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811968 ssl_options.ocsp_status =
11969 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311970 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211971
11972 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211973 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211974
mattmaf868e72016-09-23 23:25:2011975 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211976 cert_status & CERT_STATUS_ALL_ERRORS);
11977
11978 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811979 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11980 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211981}
11982
[email protected]51523f52013-07-31 21:57:2811983TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11984 if (!SystemSupportsOCSP()) {
11985 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11986 return;
11987 }
11988
11989 SpawnedTestServer::SSLOptions ssl_options(
11990 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811991 ssl_options.ocsp_status =
11992 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Adam Langleyea6d6782017-12-05 23:57:3311993 ScopedSetCRLSet set_crlset(
11994 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {}));
[email protected]51523f52013-07-31 21:57:2811995
11996 CertStatus cert_status;
11997 DoConnection(ssl_options, &cert_status);
11998
11999 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
12000 // revocation check for EV.
12001 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12002 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
12003 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
12004 EXPECT_FALSE(
12005 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
12006}
12007
12008TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
12009 if (!SystemSupportsOCSP()) {
12010 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12011 return;
12012 }
12013
[email protected]ce7d0cbc2013-05-03 18:57:2212014 SpawnedTestServer::SSLOptions ssl_options(
12015 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812016 ssl_options.ocsp_status =
12017 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1312018 ScopedSetCRLSet set_crlset(CRLSet::EmptyCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0212019
[email protected]51523f52013-07-31 21:57:2812020 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1212021 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212022
[email protected]51523f52013-07-31 21:57:2812023 // Even with a fresh CRLSet, we should still do online revocation checks when
12024 // the certificate chain isn't covered by the CRLSet, which it isn't in this
12025 // test.
mattmaf868e72016-09-23 23:25:2012026 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2812027 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0212028
[email protected]51523f52013-07-31 21:57:2812029 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0212030 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2812031 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0212032}
12033
12034class HTTPSCRLSetTest : public HTTPSOCSPTest {
12035 protected:
rsleevid6de8302016-06-21 01:33:2012036 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5612037 context_.set_ssl_config_service(
12038 new TestSSLConfigService(false /* online revocation checking */,
12039 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1412040 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5612041 false /* token binding enabled */));
12042 }
12043
12044 void SetUp() override {
12045 HTTPSOCSPTest::SetUp();
12046
12047 // Unmark the certificate's OID as EV, which should disable revocation
12048 // checking (as per the user preference).
12049 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0212050 }
12051};
12052
12053TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2212054 SpawnedTestServer::SSLOptions ssl_options(
12055 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5812056 ssl_options.ocsp_status =
12057 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1312058 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0212059
[email protected]924e9f92012-12-16 22:00:5312060 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1212061 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0212062
12063 // If we're not trying EV verification then, even if the CRLSet has expired,
12064 // we don't fall back to online revocation checks.
12065 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12066 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12067 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12068}
[email protected]51523f52013-07-31 21:57:2812069
Ryan Sleevi5b4702a2018-04-06 22:23:5612070TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
12071 // Test that when online revocation checking is disabled, and the leaf
12072 // certificate is not EV, that no revocation checking actually happens.
12073 if (!SystemSupportsOCSP()) {
12074 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
12075 return;
12076 }
12077
12078 SpawnedTestServer::SSLOptions ssl_options(
12079 SpawnedTestServer::SSLOptions::CERT_AUTO);
12080 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
12081 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
12082
12083 CertStatus cert_status;
12084 DoConnection(ssl_options, &cert_status);
12085
12086 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12087
12088 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
12089 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
12090}
12091
[email protected]51523f52013-07-31 21:57:2812092TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2512093#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812094 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12095 return;
12096#endif
12097
12098 SpawnedTestServer::SSLOptions ssl_options(
12099 SpawnedTestServer::SSLOptions::CERT_AUTO);
12100 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12101 ssl_options.cert_serial = 10;
Eric Romane2243cc62017-10-17 03:59:1312102 ScopedSetCRLSet set_crlset(
Adam Langleyea6d6782017-12-05 23:57:3312103 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {}));
[email protected]51523f52013-07-31 21:57:2812104
12105 CertStatus cert_status = 0;
12106 DoConnection(ssl_options, &cert_status);
12107
12108 // If the certificate is recorded as revoked in the CRLSet, that should be
12109 // reflected without online revocation checking.
12110 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12111 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612112 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812113}
Adam Langleyea6d6782017-12-05 23:57:3312114
12115TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12116#if defined(OS_ANDROID)
12117 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12118 return;
12119#endif
12120
12121 SpawnedTestServer::SSLOptions ssl_options(
12122 SpawnedTestServer::SSLOptions::CERT_AUTO);
12123 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12124 static const char kCommonName[] = "Test CN";
12125 ssl_options.cert_common_name = kCommonName;
12126
12127 {
12128 ScopedSetCRLSet set_crlset(
12129 CRLSet::ForTesting(false, nullptr, "", kCommonName, {}));
12130
12131 CertStatus cert_status = 0;
12132 DoConnection(ssl_options, &cert_status);
12133
12134 // If the certificate is recorded as revoked in the CRLSet, that should be
12135 // reflected without online revocation checking.
12136 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12137 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612138 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312139 }
12140
12141 const uint8_t kTestServerSPKISHA256[32] = {
12142 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12143 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12144 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12145 };
12146 const std::string spki_hash(
12147 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12148 sizeof(kTestServerSPKISHA256));
12149
12150 {
12151 ScopedSetCRLSet set_crlset(
12152 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash}));
12153
12154 CertStatus cert_status = 0;
12155 DoConnection(ssl_options, &cert_status);
12156
12157 // When the correct SPKI hash is specified, the connection should succeed
12158 // even though the subject is listed in the CRLSet.
12159 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12160 }
12161}
[email protected]316c1e5e2012-09-12 15:17:4412162#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712163
Sergey Ulanovc4580e72017-09-13 23:30:1112164#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12165 !defined(OS_FUCHSIA)
12166// FTP uses a second TCP connection with the port number allocated dynamically
12167// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12168// connections reliably. FTP tests are disabled on platforms that use
12169// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112170class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112171 public:
[email protected]d9fca99a2012-02-24 16:16:2012172 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512173 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512174 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712175 // Can't use |default_context_|'s HostResolver to set up the
12176 // FTPTransactionFactory because it hasn't been created yet.
12177 default_context_.set_host_resolver(&host_resolver_);
12178 }
12179
12180 // URLRequestTest interface:
12181 void SetUpFactory() override {
12182 // Add FTP support to the default URLRequestContext.
12183 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0512184 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4712185 }
12186
12187 std::string GetTestFileContents() {
12188 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912189 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712190 path = path.Append(kTestFilePath);
12191 path = path.AppendASCII(kFtpTestFile);
12192 std::string contents;
12193 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12194 return contents;
[email protected]95409e12010-08-17 20:07:1112195 }
12196
[email protected]b89ca032009-08-31 21:41:3112197 protected:
mmenkecd4c7532016-10-19 18:36:0512198 // Note that this is destroyed before the FtpProtocolHandler that references
12199 // it, which is owned by the parent class. Since no requests are made during
12200 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4712201 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4712202
tommycli59a63432015-11-06 00:10:5512203 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112204};
12205
[email protected]d2a133182012-08-05 16:44:0812206// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912207TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812208 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812209
12210 TestDelegate d;
12211 {
rhalavatib7bd7c792017-04-27 05:25:1612212 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12213 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912214 r->Start();
12215 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812216
Wez2a31b222018-06-07 22:07:1512217 d.RunUntilComplete();
[email protected]d2a133182012-08-05 16:44:0812218
[email protected]f7022f32014-08-21 16:32:1912219 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012220 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812221 }
12222}
12223
mmenke9f2ec60c2015-06-01 20:59:4712224TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512225 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112226
[email protected]a25e90e2009-09-09 17:05:3712227 TestDelegate d;
12228 {
danakj8522a25b2016-04-16 00:17:3612229 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612230 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12231 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912232 r->Start();
12233 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712234
Wez2a31b222018-06-07 22:07:1512235 d.RunUntilComplete();
[email protected]a25e90e2009-09-09 17:05:3712236
[email protected]f7022f32014-08-21 16:32:1912237 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712238 EXPECT_EQ(1, d.response_started_count());
12239 EXPECT_FALSE(d.received_data_before_response());
12240 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512241 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912242 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512243 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912244 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3712245 }
12246}
12247
mmenke9f2ec60c2015-06-01 20:59:4712248TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512249 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112250
[email protected]dd265012009-01-08 20:45:2712251 TestDelegate d;
12252 {
danakj8522a25b2016-04-16 00:17:3612253 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612254 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12255 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912256 r->Start();
12257 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712258
Wez2a31b222018-06-07 22:07:1512259 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712260
[email protected]f7022f32014-08-21 16:32:1912261 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712262 EXPECT_EQ(1, d.response_started_count());
12263 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712264 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512265 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912266 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512267 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912268 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2712269 }
12270}
12271
mmenke9f2ec60c2015-06-01 20:59:4712272TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512273 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112274
[email protected]dd265012009-01-08 20:45:2712275 TestDelegate d;
12276 {
danakj8522a25b2016-04-16 00:17:3612277 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512278 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12279 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612280 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912281 r->Start();
12282 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712283
Wez2a31b222018-06-07 22:07:1512284 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712285
[email protected]f7022f32014-08-21 16:32:1912286 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712287 EXPECT_EQ(1, d.response_started_count());
12288 EXPECT_FALSE(d.received_data_before_response());
12289 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512290 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912291 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512292 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912293 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2512294
12295 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912296 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512297 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712298 }
12299}
12300
mmenke9f2ec60c2015-06-01 20:59:4712301TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512302 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112303
[email protected]dd265012009-01-08 20:45:2712304 TestDelegate d;
12305 {
danakj8522a25b2016-04-16 00:17:3612306 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512307 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12308 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612309 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912310 r->Start();
12311 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712312
Wez2a31b222018-06-07 22:07:1512313 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712314
[email protected]f7022f32014-08-21 16:32:1912315 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712316 EXPECT_EQ(1, d.response_started_count());
12317 EXPECT_FALSE(d.received_data_before_response());
12318 EXPECT_EQ(d.bytes_received(), 0);
12319 }
12320}
12321
mmenke9f2ec60c2015-06-01 20:59:4712322TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512323 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112324
[email protected]8b8a197d2009-08-26 15:57:5812325 TestDelegate d;
12326 // Set correct login credentials. The delegate will be asked for them when
12327 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812328 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812329 {
danakj8522a25b2016-04-16 00:17:3612330 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512331 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12332 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612333 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912334 r->Start();
12335 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812336
Wez2a31b222018-06-07 22:07:1512337 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812338
[email protected]f7022f32014-08-21 16:32:1912339 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812340 EXPECT_EQ(1, d.response_started_count());
12341 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712342 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812343 }
12344}
12345
mmenke9f2ec60c2015-06-01 20:59:4712346TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512347 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112348
[email protected]dd265012009-01-08 20:45:2712349 TestDelegate d;
12350 {
danakj8522a25b2016-04-16 00:17:3612351 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512352 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12353 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612354 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912355 r->Start();
12356 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712357
Wez2a31b222018-06-07 22:07:1512358 d.RunUntilComplete();
[email protected]dd265012009-01-08 20:45:2712359
[email protected]f7022f32014-08-21 16:32:1912360 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712361 EXPECT_EQ(1, d.response_started_count());
12362 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712363 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712364 }
12365}
[email protected]8b8a197d2009-08-26 15:57:5812366
mmenke9f2ec60c2015-06-01 20:59:4712367TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512368 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112369
[email protected]8b8a197d2009-08-26 15:57:5812370 TestDelegate d;
12371 // Set correct login credentials. The delegate will be asked for them when
12372 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812373 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812374 {
danakj8522a25b2016-04-16 00:17:3612375 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512376 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12377 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612378 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912379 r->Start();
12380 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812381
Wez2a31b222018-06-07 22:07:1512382 d.RunUntilComplete();
[email protected]8b8a197d2009-08-26 15:57:5812383
[email protected]f7022f32014-08-21 16:32:1912384 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812385 EXPECT_EQ(1, d.response_started_count());
12386 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712387 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812388 }
12389}
[email protected]60a3df52009-09-22 16:13:2412390
mmenke9f2ec60c2015-06-01 20:59:4712391TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512392 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112393
danakj8522a25b2016-04-16 00:17:3612394 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412395 {
12396 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3612397 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512398 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12399 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612400 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912401 r->Start();
12402 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412403
Wez2a31b222018-06-07 22:07:1512404 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412405
[email protected]f7022f32014-08-21 16:32:1912406 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412407 EXPECT_EQ(1, d->response_started_count());
12408 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712409 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412410 }
12411
12412 d.reset(new TestDelegate);
12413 {
12414 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3612415 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612416 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12417 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912418 r->Start();
12419 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412420
Wez2a31b222018-06-07 22:07:1512421 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412422
[email protected]f7022f32014-08-21 16:32:1912423 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412424 EXPECT_EQ(1, d->response_started_count());
12425 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712426 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412427 }
12428}
12429
mmenke9f2ec60c2015-06-01 20:59:4712430TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512431 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112432
danakj8522a25b2016-04-16 00:17:3612433 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412434 // Set correct login credentials. The delegate will be asked for them when
12435 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812436 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412437 {
danakj8522a25b2016-04-16 00:17:3612438 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512439 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12440 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612441 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912442 r->Start();
12443 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412444
Wez2a31b222018-06-07 22:07:1512445 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412446
[email protected]f7022f32014-08-21 16:32:1912447 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412448 EXPECT_EQ(1, d->response_started_count());
12449 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712450 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412451 }
12452
12453 // Use a new delegate without explicit credentials. The cached ones should be
12454 // used.
12455 d.reset(new TestDelegate);
12456 {
12457 // Don't pass wrong credentials in the URL, they would override valid cached
12458 // ones.
danakj8522a25b2016-04-16 00:17:3612459 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612460 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12461 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912462 r->Start();
12463 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412464
Wez2a31b222018-06-07 22:07:1512465 d->RunUntilComplete();
[email protected]60a3df52009-09-22 16:13:2412466
[email protected]f7022f32014-08-21 16:32:1912467 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412468 EXPECT_EQ(1, d->response_started_count());
12469 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712470 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412471 }
12472}
ricea3a1c71f2016-06-17 10:05:2612473
12474TEST_F(URLRequestTestFTP, RawBodyBytes) {
12475 ASSERT_TRUE(ftp_test_server_.Start());
12476
12477 TestDelegate d;
12478 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612479 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12480 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612481 req->Start();
Wez2a31b222018-06-07 22:07:1512482 d.RunUntilComplete();
ricea3a1c71f2016-06-17 10:05:2612483
12484 EXPECT_EQ(6, req->GetRawBodyBytes());
12485}
12486
brettwa1228ebb2016-10-28 03:51:3412487#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112488
ttuttlec0c828492015-05-15 01:25:5512489TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12490 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612491 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12492 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512493
12494 EXPECT_FALSE(req->response_info().network_accessed);
12495
12496 req->Start();
Wez2a31b222018-06-07 22:07:1512497 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512498
12499 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12500 EXPECT_FALSE(req->response_info().network_accessed);
12501}
12502
12503TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12504 MockHostResolver host_resolver;
12505 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12506 TestURLRequestContext context(true);
12507 context.set_network_delegate(&network_delegate);
12508 context.set_host_resolver(&host_resolver);
12509 host_resolver.rules()->AddSimulatedFailure("*");
12510 context.Init();
12511
12512 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612513 std::unique_ptr<URLRequest> req(
12514 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12515 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512516
12517 EXPECT_FALSE(req->response_info().network_accessed);
12518
12519 req->Start();
Wez2a31b222018-06-07 22:07:1512520 d.RunUntilComplete();
ttuttlec0c828492015-05-15 01:25:5512521 EXPECT_TRUE(req->response_info().network_accessed);
12522}
12523
mmenkeed0498b2015-12-08 23:20:4212524// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212525// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212526TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212527 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3612528 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612529 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12530 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212531
danakj8522a25b2016-04-16 00:17:3612532 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212533 req.get(), &default_network_delegate_,
12534 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212535 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12536 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212537
12538 req->Start();
12539 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212540 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012541 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212542 EXPECT_EQ(0, d.received_redirect_count());
12543}
12544
Andrey Kosyakov2e893e62017-08-31 17:00:5212545TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412546 ASSERT_TRUE(http_test_server()->Start());
12547 TestURLRequestContext context;
12548 GURL url(http_test_server()->GetURL("/cachetime"));
12549 TestDelegate delegate;
12550 HttpRequestHeaders extra_headers;
12551 extra_headers.SetHeader("X-Foo", "bar");
12552
12553 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212554 HttpRawRequestHeaders raw_req_headers;
12555 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12556
Andrey Kosyakov83a6eee2017-08-14 19:20:0412557 std::unique_ptr<URLRequest> r(context.CreateRequest(
12558 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12559 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212560 r->SetRequestHeadersCallback(base::Bind(
12561 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12562 r->SetResponseHeadersCallback(base::Bind(
12563 [](scoped_refptr<const HttpResponseHeaders>* left,
12564 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12565 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412566 r->Start();
12567 while (!delegate.response_started_count())
12568 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212569 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412570 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212571 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412572 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212573 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412574 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212575 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12576 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12577 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12578 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412579 }
12580 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412581 std::unique_ptr<URLRequest> r(context.CreateRequest(
12582 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12583 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212584 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412585 FAIL() << "Callback should not be called unless request is sent";
12586 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212587 r->SetResponseHeadersCallback(
12588 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12589 FAIL() << "Callback should not be called unless request is sent";
12590 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412591 r->Start();
Wez2a31b222018-06-07 22:07:1512592 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412593 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412594 }
12595}
12596
Andrey Kosyakov2e893e62017-08-31 17:00:5212597TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412598 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212599 HttpRawRequestHeaders raw_req_headers;
12600 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12601
Andrey Kosyakov83a6eee2017-08-14 19:20:0412602 TestURLRequestContext context;
12603 TestDelegate delegate;
12604 HttpRequestHeaders extra_headers;
12605 extra_headers.SetHeader("X-Foo", "bar");
12606 delegate.set_quit_on_redirect(true);
12607 GURL url(http_test_server()->GetURL("/redirect-test.html"));
12608 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12609 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12610 r->SetExtraRequestHeaders(extra_headers);
12611 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212612 base::Unretained(&raw_req_headers)));
12613 r->SetResponseHeadersCallback(base::Bind(
12614 [](scoped_refptr<const HttpResponseHeaders>* left,
12615 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12616 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412617 r->Start();
Wez2a31b222018-06-07 22:07:1512618 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412619
12620 ASSERT_EQ(1, delegate.received_redirect_count());
12621 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212622 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412623 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212624 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412625 EXPECT_EQ("gzip, deflate", value);
12626 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212627 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12628 raw_req_headers.request_line());
12629 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12630 EXPECT_EQ(302, raw_resp_headers->response_code());
12631 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412632
Andrey Kosyakov2e893e62017-08-31 17:00:5212633 raw_req_headers = HttpRawRequestHeaders();
12634 raw_resp_headers = nullptr;
Chong Zhang7607f1f2018-06-01 20:52:2012635 r->FollowDeferredRedirect(base::nullopt /* modified_request_headers */);
Wez2a31b222018-06-07 22:07:1512636 delegate.RunUntilComplete();
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);
Andrey Kosyakov2e893e62017-08-31 17:00:5212641 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12642 raw_req_headers.request_line());
12643 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412644}
12645
Andrey Kosyakov2e893e62017-08-31 17:00:5212646TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412647 TestDelegate request_delegate;
12648
12649 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12650 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12651 TRAFFIC_ANNOTATION_FOR_TESTS));
12652 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12653 FAIL() << "Callback should not be called unless request is sent";
12654 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212655 r->SetResponseHeadersCallback(
12656 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12657 FAIL() << "Callback should not be called unless request is sent";
12658 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412659 r->Start();
Wez2a31b222018-06-07 22:07:1512660 request_delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412661 EXPECT_FALSE(r->is_pending());
12662}
12663
Andrey Kosyakov2e893e62017-08-31 17:00:5212664TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412665 ASSERT_TRUE(http_test_server()->Start());
12666 GURL url(http_test_server()->GetURL("/auth-basic"));
12667
12668 TestURLRequestContext context;
12669 TestDelegate delegate;
12670
12671 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12672 HttpRequestHeaders extra_headers;
12673 extra_headers.SetHeader("X-Foo", "bar");
12674
Andrey Kosyakov2e893e62017-08-31 17:00:5212675 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12676 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412677
Andrey Kosyakov2e893e62017-08-31 17:00:5212678 using RespHeadersVector =
12679 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12680 RespHeadersVector raw_resp_headers;
12681
12682 auto req_headers_callback = base::Bind(
12683 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12684 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12685 },
12686 &raw_req_headers);
12687 auto resp_headers_callback = base::Bind(
12688 [](RespHeadersVector* vec,
12689 scoped_refptr<const HttpResponseHeaders> headers) {
12690 vec->push_back(headers);
12691 },
12692 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412693 std::unique_ptr<URLRequest> r(context.CreateRequest(
12694 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12695 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212696 r->SetRequestHeadersCallback(req_headers_callback);
12697 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412698 r->Start();
Wez2a31b222018-06-07 22:07:1512699 delegate.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412700 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212701 ASSERT_EQ(raw_req_headers.size(), 2u);
12702 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412703 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212704 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12705 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412706 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212707 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12708 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412709 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212710 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12711 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12712 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12713 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12714
12715 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12716 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12717 r2->SetExtraRequestHeaders(extra_headers);
12718 r2->SetRequestHeadersCallback(req_headers_callback);
12719 r2->SetResponseHeadersCallback(resp_headers_callback);
12720 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12721 r2->Start();
Wez2a31b222018-06-07 22:07:1512722 delegate.RunUntilComplete();
Andrey Kosyakov2e893e62017-08-31 17:00:5212723 EXPECT_FALSE(r2->is_pending());
12724 ASSERT_EQ(raw_req_headers.size(), 3u);
12725 ASSERT_EQ(raw_resp_headers.size(), 3u);
12726 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12727 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12728 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12729 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412730}
12731
Andrey Kosyakov2e893e62017-08-31 17:00:5212732TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412733 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12734 TestDelegate d;
12735 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12736 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12737 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212738 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412739 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212740 r->SetResponseHeadersCallback(
12741 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12742 FAIL() << "Callback should not be called for non-HTTP schemes";
12743 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412744 r->Start();
Wez2a31b222018-06-07 22:07:1512745 d.RunUntilComplete();
Andrey Kosyakov83a6eee2017-08-14 19:20:0412746 EXPECT_FALSE(r->is_pending());
12747}
12748
Carlos ILaef65d62018-06-04 21:24:1312749TEST_F(URLRequestTest, UpgradeIfInsecureFlagSet) {
12750 TestDelegate d;
12751 BlockingNetworkDelegate network_delegate(
12752 BlockingNetworkDelegate::SYNCHRONOUS);
12753 const GURL kOriginalUrl("https://original.test");
12754 const GURL kRedirectUrl("http://redirect.test");
12755 network_delegate.set_redirect_url(kRedirectUrl);
12756 TestURLRequestContext context(true /* delay_initialization */);
12757 context.set_network_delegate(&network_delegate);
12758 context.Init();
12759
12760 std::unique_ptr<URLRequest> r(context.CreateRequest(
12761 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12762 r->set_upgrade_if_insecure(true);
12763 d.set_quit_on_redirect(true);
12764 r->Start();
12765 base::RunLoop().Run();
12766 GURL::Replacements replacements;
12767 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12768 // was set.
12769 replacements.SetSchemeStr("https");
12770 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12771 d.redirect_info().new_url);
12772}
12773
12774TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetExplicitPort80) {
12775 TestDelegate d;
12776 BlockingNetworkDelegate network_delegate(
12777 BlockingNetworkDelegate::SYNCHRONOUS);
12778 const GURL kOriginalUrl("https://original.test");
12779 const GURL kRedirectUrl("http://redirect.test:80");
12780 network_delegate.set_redirect_url(kRedirectUrl);
12781 TestURLRequestContext context(true /* delay_initialization */);
12782 context.set_network_delegate(&network_delegate);
12783 context.Init();
12784
12785 std::unique_ptr<URLRequest> r(context.CreateRequest(
12786 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12787 r->set_upgrade_if_insecure(true);
12788 d.set_quit_on_redirect(true);
12789 r->Start();
12790 base::RunLoop().Run();
12791 GURL::Replacements replacements;
12792 // The URL host should have not been changed.
12793 EXPECT_EQ(d.redirect_info().new_url.host(), kRedirectUrl.host());
12794 // The scheme should now be https, and the effective port should now be 443.
12795 EXPECT_TRUE(d.redirect_info().new_url.SchemeIs("https"));
12796 EXPECT_EQ(d.redirect_info().new_url.EffectiveIntPort(), 443);
12797}
12798
12799TEST_F(URLRequestTest, UpgradeIfInsecureFlagSetNonStandardPort) {
12800 TestDelegate d;
12801 BlockingNetworkDelegate network_delegate(
12802 BlockingNetworkDelegate::SYNCHRONOUS);
12803 const GURL kOriginalUrl("https://original.test");
12804 const GURL kRedirectUrl("http://redirect.test:1234");
12805 network_delegate.set_redirect_url(kRedirectUrl);
12806 TestURLRequestContext context(true /* delay_initialization */);
12807 context.set_network_delegate(&network_delegate);
12808 context.Init();
12809
12810 std::unique_ptr<URLRequest> r(context.CreateRequest(
12811 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12812 r->set_upgrade_if_insecure(true);
12813 d.set_quit_on_redirect(true);
12814 r->Start();
12815 base::RunLoop().Run();
12816 GURL::Replacements replacements;
12817 // Check that the redirect URL was upgraded to HTTPS since upgrade_if_insecure
12818 // was set, nonstandard port should not have been modified.
12819 replacements.SetSchemeStr("https");
12820 EXPECT_EQ(kRedirectUrl.ReplaceComponents(replacements),
12821 d.redirect_info().new_url);
12822}
12823
12824TEST_F(URLRequestTest, UpgradeIfInsecureFlagNotSet) {
12825 TestDelegate d;
12826 BlockingNetworkDelegate network_delegate(
12827 BlockingNetworkDelegate::SYNCHRONOUS);
12828 const GURL kOriginalUrl("https://original.test");
12829 const GURL kRedirectUrl("http://redirect.test");
12830 network_delegate.set_redirect_url(kRedirectUrl);
12831 TestURLRequestContext context(true /* delay_initialization */);
12832 context.set_network_delegate(&network_delegate);
12833 context.Init();
12834 std::unique_ptr<URLRequest> r(context.CreateRequest(
12835 kOriginalUrl, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12836 r->set_upgrade_if_insecure(false);
12837 d.set_quit_on_redirect(true);
12838 r->Start();
12839 base::RunLoop().Run();
12840 // The redirect URL should not be changed if the upgrade_if_insecure flag is
12841 // not set.
12842 EXPECT_EQ(kRedirectUrl, d.redirect_info().new_url);
12843}
12844
Paul Jensen60e45532018-02-19 16:04:1812845// Test that URLRequests get properly tagged.
12846#if defined(OS_ANDROID)
12847TEST_F(URLRequestTestHTTP, TestTagging) {
12848 ASSERT_TRUE(http_test_server()->Start());
12849
12850 // The tag under which the system reports untagged traffic.
12851 static const int32_t UNTAGGED_TAG = 0;
12852
12853 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12854
12855 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12856 TestDelegate delegate;
12857 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12858 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12859 TRAFFIC_ANNOTATION_FOR_TESTS));
12860 EXPECT_EQ(SocketTag(), req->socket_tag());
12861 req->Start();
Wez2a31b222018-06-07 22:07:1512862 delegate.RunUntilComplete();
Paul Jensen60e45532018-02-19 16:04:1812863
12864 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12865
12866 int32_t tag_val1 = 0x12345678;
12867 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12868 old_traffic = GetTaggedBytes(tag_val1);
12869
12870 // Test specific tag value.
12871 req = default_context_.CreateRequest(http_test_server()->GetURL("/"),
12872 DEFAULT_PRIORITY, &delegate,
12873 TRAFFIC_ANNOTATION_FOR_TESTS);
12874 req->set_socket_tag(tag1);
12875 EXPECT_EQ(tag1, 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(tag_val1), old_traffic);
12880}
12881#endif
12882
[email protected]7461a402011-03-24 23:19:5112883} // namespace net