blob: b3a71959ccb0669b012396762981f176e4feb2f7 [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>
Gyuyoung Kimb480aba2018-01-27 07:00:0420#include <memory>
avibf0746c2015-12-09 19:53:1421#include <limits>
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"
tbansalea2fb8c2015-05-22 22:23:0046#include "base/test/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"
rhalavatib7bd7c792017-04-27 05:25:16113#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34114#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43115#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52116#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50117#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14118#include "net/url_request/url_request_http_job.h"
Thiemo Nagel0793b9c532018-04-18 16:57:58119#include "net/url_request/url_request_http_job_histogram.h"
bengr1bf8e942014-11-07 01:36:50120#include "net/url_request/url_request_intercepting_job_factory.h"
121#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49122#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51123#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47124#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44125#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01126#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52127#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15128#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52129
Eric Romanefddd0a2017-10-10 02:14:25130#if defined(OS_FUCHSIA)
131#define USE_BUILTIN_CERT_VERIFIER
132#endif
133
brettwa1228ebb2016-10-28 03:51:34134#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55135#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29136#include "net/url_request/file_protocol_handler.h"
137#include "net/url_request/url_request_file_dir_job.h"
138#endif
139
brettwa1228ebb2016-10-28 03:51:34140#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47141#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29142#include "net/url_request/ftp_protocol_handler.h"
143#endif
144
[email protected]dffe8242012-03-20 15:14:27145#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48146#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27147#endif
148
mmenkefd9d15c2017-06-29 13:45:54149#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27150#include "net/network_error_logging/network_error_logging_service.h"
Julia Tuttle91a655d2018-01-26 18:03:03151#include "net/reporting/reporting_policy.h"
mmenkefd9d15c2017-06-29 13:45:54152#include "net/reporting/reporting_service.h"
153#endif // BUILDFLAG(ENABLE_REPORTING)
154
Matt Muellerfb271992018-01-30 18:10:48155#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25156#include "net/cert/cert_net_fetcher.h"
157#include "net/cert_net/cert_net_fetcher_impl.h"
158#endif
159
160#if defined(USE_NSS_CERTS)
161#include "net/cert_net/nss_ocsp.h"
162#endif
163
robpercival214763f2016-07-01 23:27:01164using net::test::IsError;
165using net::test::IsOk;
166
[email protected]ad65a3e2013-12-25 18:18:01167using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33168using base::Time;
halton.huoe4e45742014-12-08 07:55:46169using std::string;
[email protected]e1acf6f2008-10-27 20:43:33170
[email protected]7461a402011-03-24 23:19:51171namespace net {
172
initial.commit586acc5fe2008-07-26 22:42:52173namespace {
174
Martijn Croonenb1383da2017-10-11 11:56:35175namespace test_default {
176#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35177}
178
[email protected]42cba2fb2013-03-29 19:58:57179const base::string16 kChrome(ASCIIToUTF16("chrome"));
180const base::string16 kSecret(ASCIIToUTF16("secret"));
181const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44182
mmenke9f2ec60c2015-06-01 20:59:47183const base::FilePath::CharType kTestFilePath[] =
184 FILE_PATH_LITERAL("net/data/url_request_unittest");
185
Sergey Ulanovc4580e72017-09-13 23:30:11186#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
187 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47188// Test file used in most FTP tests.
189const char kFtpTestFile[] = "BullRunSpeech.txt";
190#endif
191
[email protected]2bba3252013-04-08 19:50:59192// Tests load timing information in the case a fresh connection was used, with
193// no proxy.
[email protected]cba24642014-08-15 20:49:59194void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25195 int connect_timing_flags) {
196 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19197 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25198
199 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
200 EXPECT_FALSE(load_timing_info.request_start.is_null());
201
202 EXPECT_LE(load_timing_info.request_start,
203 load_timing_info.connect_timing.connect_start);
204 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
205 connect_timing_flags);
206 EXPECT_LE(load_timing_info.connect_timing.connect_end,
207 load_timing_info.send_start);
208 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
209 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
210
[email protected]58e32bb2013-01-21 18:23:25211 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
212 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
213}
214
[email protected]2bba3252013-04-08 19:50:59215// Same as above, but with proxy times.
216void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59217 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59218 int connect_timing_flags) {
219 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19220 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59221
222 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
223 EXPECT_FALSE(load_timing_info.request_start.is_null());
224
225 EXPECT_LE(load_timing_info.request_start,
226 load_timing_info.proxy_resolve_start);
227 EXPECT_LE(load_timing_info.proxy_resolve_start,
228 load_timing_info.proxy_resolve_end);
229 EXPECT_LE(load_timing_info.proxy_resolve_end,
230 load_timing_info.connect_timing.connect_start);
231 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
232 connect_timing_flags);
233 EXPECT_LE(load_timing_info.connect_timing.connect_end,
234 load_timing_info.send_start);
235 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
236 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
237}
238
239// Same as above, but with a reused socket and proxy times.
240void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59241 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59242 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19243 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59244
245 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
246 EXPECT_FALSE(load_timing_info.request_start.is_null());
247
248 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
249
250 EXPECT_LE(load_timing_info.request_start,
251 load_timing_info.proxy_resolve_start);
252 EXPECT_LE(load_timing_info.proxy_resolve_start,
253 load_timing_info.proxy_resolve_end);
254 EXPECT_LE(load_timing_info.proxy_resolve_end,
255 load_timing_info.send_start);
256 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
257 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
258}
259
brettwa1228ebb2016-10-28 03:51:34260#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25261// Tests load timing information in the case of a cache hit, when no cache
262// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17263base::StringPiece TestNetResourceProvider(int key) {
264 return "header";
265}
266
267void FillBuffer(char* buffer, size_t len) {
268 static bool called = false;
269 if (!called) {
270 called = true;
271 int seed = static_cast<int>(Time::Now().ToInternalValue());
272 srand(seed);
273 }
274
275 for (size_t i = 0; i < len; i++) {
276 buffer[i] = static_cast<char>(rand());
277 if (!buffer[i])
278 buffer[i] = 'g';
279 }
280}
xunjielia6888202015-04-14 21:34:25281#endif
[email protected]e3a85452013-11-14 01:46:17282
[email protected]3b23a222013-05-15 21:33:25283void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59284 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25285 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19286 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25287
288 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
289 EXPECT_FALSE(load_timing_info.request_start.is_null());
290
291 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
292 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
293 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
294 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
295
296 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
297 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
298}
299
Sergey Ulanovc4580e72017-09-13 23:30:11300#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
301 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25302// Tests load timing in the case that there is no HTTP response. This can be
303// used to test in the case of errors or non-HTTP requests.
304void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59305 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25306 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19307 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25308
309 // Only the request times should be non-null.
310 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
311 EXPECT_FALSE(load_timing_info.request_start.is_null());
312
313 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
314
315 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
316 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
317 EXPECT_TRUE(load_timing_info.send_start.is_null());
318 EXPECT_TRUE(load_timing_info.send_end.is_null());
319 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
320}
xunjielia6888202015-04-14 21:34:25321#endif
[email protected]58e32bb2013-01-21 18:23:25322
mmenkefb18c772015-09-30 22:22:50323// Test power monitor source that can simulate entering suspend mode. Can't use
324// the one in base/ because it insists on bringing its own MessageLoop.
325class TestPowerMonitorSource : public base::PowerMonitorSource {
326 public:
Chris Watkins7a41d3552017-12-01 02:13:27327 TestPowerMonitorSource() = default;
328 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50329
330 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
331
332 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
333
334 bool IsOnBatteryPowerImpl() override { return false; }
335
336 private:
337 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
338};
339
mmenkeed0498b2015-12-08 23:20:42340// Job that allows monitoring of its priority.
341class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
342 public:
343 // The latest priority of the job is always written to |request_priority_|.
344 PriorityMonitoringURLRequestJob(URLRequest* request,
345 NetworkDelegate* network_delegate,
346 RequestPriority* request_priority)
347 : URLRequestTestJob(request, network_delegate),
348 request_priority_(request_priority) {
349 *request_priority_ = DEFAULT_PRIORITY;
350 }
351
352 void SetPriority(RequestPriority priority) override {
353 *request_priority_ = priority;
354 URLRequestTestJob::SetPriority(priority);
355 }
356
357 private:
358 RequestPriority* const request_priority_;
359};
360
[email protected]71c64f62008-11-15 04:36:51361// Do a case-insensitive search through |haystack| for |needle|.
362bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50363 std::string::const_iterator it = std::search(
364 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
365 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51366 return it != haystack.end();
367}
368
danakj8522a25b2016-04-16 00:17:36369std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
370 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28371 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48372 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23373}
374
[email protected]96adadb2010-08-28 01:16:17375// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51376void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17377 // -1 means unknown. 0 means no encryption.
378 EXPECT_GT(ssl_info.security_bits, 0);
379
380 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14381 uint16_t cipher_suite =
382 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29383 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17384}
385
[email protected]79e1fd62013-06-20 06:50:04386void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
387 const GURL& host_url) {
388 std::string sent_value;
389
390 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
391 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
392
393 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
394 EXPECT_EQ("keep-alive", sent_value);
395}
396
[email protected]dc5a5cf2012-09-26 02:49:30397// A network delegate that allows the user to choose a subset of request stages
398// to block in. When blocking, the delegate can do one of the following:
399// * synchronously return a pre-specified error code, or
400// * asynchronously return that value via an automatically called callback,
401// or
402// * block and wait for the user to do a callback.
403// Additionally, the user may also specify a redirect URL -- then each request
404// with the current URL different from the redirect target will be redirected
405// to that target, in the on-before-URL-request stage, independent of whether
406// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12407class BlockingNetworkDelegate : public TestNetworkDelegate {
408 public:
[email protected]dc5a5cf2012-09-26 02:49:30409 // Stages in which the delegate can block.
410 enum Stage {
[email protected]9045b8822012-01-13 20:35:35411 NOT_BLOCKED = 0,
412 ON_BEFORE_URL_REQUEST = 1 << 0,
413 ON_BEFORE_SEND_HEADERS = 1 << 1,
414 ON_HEADERS_RECEIVED = 1 << 2,
415 ON_AUTH_REQUIRED = 1 << 3
416 };
417
[email protected]dc5a5cf2012-09-26 02:49:30418 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59419 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30420 enum BlockMode {
421 SYNCHRONOUS, // No callback, returns specified return values.
422 AUTO_CALLBACK, // |this| posts a task to run the callback using the
423 // specified return codes.
424 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
425 // |auth_retval_| are ignored. In every blocking stage the
426 // message loop is quit.
427 };
428
429 // Creates a delegate which does not block at all.
430 explicit BlockingNetworkDelegate(BlockMode block_mode);
431
432 // For users to trigger a callback returning |response|.
433 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
434 // Only call if |block_mode_| == USER_CALLBACK.
435 void DoCallback(int response);
436 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
437
438 // Setters.
439 void set_retval(int retval) {
440 ASSERT_NE(USER_CALLBACK, block_mode_);
441 ASSERT_NE(ERR_IO_PENDING, retval);
442 ASSERT_NE(OK, retval);
443 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35444 }
445
[email protected]dc5a5cf2012-09-26 02:49:30446 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
447 // |auth_credentials_| will be passed with the response.
448 void set_auth_retval(AuthRequiredResponse auth_retval) {
449 ASSERT_NE(USER_CALLBACK, block_mode_);
450 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
451 auth_retval_ = auth_retval;
452 }
453 void set_auth_credentials(const AuthCredentials& auth_credentials) {
454 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35455 }
456
[email protected]dc5a5cf2012-09-26 02:49:30457 void set_redirect_url(const GURL& url) {
458 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35459 }
460
[email protected]dc5a5cf2012-09-26 02:49:30461 void set_block_on(int block_on) {
462 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35463 }
464
[email protected]dc5a5cf2012-09-26 02:49:30465 // Allows the user to check in which state did we block.
466 Stage stage_blocked_for_callback() const {
467 EXPECT_EQ(USER_CALLBACK, block_mode_);
468 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35469 }
470
471 private:
[email protected]dc5a5cf2012-09-26 02:49:30472 void RunCallback(int response, const CompletionCallback& callback);
473 void RunAuthCallback(AuthRequiredResponse response,
474 const AuthCallback& callback);
475
[email protected]9045b8822012-01-13 20:35:35476 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20477 int OnBeforeURLRequest(URLRequest* request,
478 const CompletionCallback& callback,
479 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35480
ryansturm2343cb62016-06-15 01:09:00481 int OnBeforeStartTransaction(URLRequest* request,
482 const CompletionCallback& callback,
483 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35484
dchengb03027d2014-10-21 12:00:20485 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35486 URLRequest* request,
487 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32488 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16489 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13490 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35491
dchengb03027d2014-10-21 12:00:20492 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35493 URLRequest* request,
494 const AuthChallengeInfo& auth_info,
495 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13496 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35497
[email protected]dc5a5cf2012-09-26 02:49:30498 // Resets the callbacks and |stage_blocked_for_callback_|.
499 void Reset();
[email protected]9045b8822012-01-13 20:35:35500
[email protected]dc5a5cf2012-09-26 02:49:30501 // Checks whether we should block in |stage|. If yes, returns an error code
502 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24503 int MaybeBlockStage(Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24504 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30505
506 // Configuration parameters, can be adjusted by public methods:
507 const BlockMode block_mode_;
508
509 // Values returned on blocking stages when mode is SYNCHRONOUS or
510 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
511 int retval_; // To be returned in non-auth stages.
512 AuthRequiredResponse auth_retval_;
513
[email protected]5f714132014-03-26 10:41:16514 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30515 int block_on_; // Bit mask: in which stages to block.
516
517 // |auth_credentials_| will be copied to |*target_auth_credential_| on
518 // callback.
519 AuthCredentials auth_credentials_;
520 AuthCredentials* target_auth_credentials_;
521
522 // Internal variables, not set by not the user:
523 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
524 // USER_CALLBACK).
525 Stage stage_blocked_for_callback_;
526
527 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35528 CompletionCallback callback_;
529 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30530
531 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
532
533 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35534};
535
[email protected]dc5a5cf2012-09-26 02:49:30536BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
537 : block_mode_(block_mode),
538 retval_(OK),
539 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
540 block_on_(0),
541 target_auth_credentials_(NULL),
542 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32543 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30544}
545
546void BlockingNetworkDelegate::DoCallback(int response) {
547 ASSERT_EQ(USER_CALLBACK, block_mode_);
548 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
549 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
550 CompletionCallback callback = callback_;
551 Reset();
552 RunCallback(response, callback);
553}
554
555void BlockingNetworkDelegate::DoAuthCallback(
556 NetworkDelegate::AuthRequiredResponse response) {
557 ASSERT_EQ(USER_CALLBACK, block_mode_);
558 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
559 AuthCallback auth_callback = auth_callback_;
560 Reset();
561 RunAuthCallback(response, auth_callback);
562}
563
564void BlockingNetworkDelegate::RunCallback(int response,
565 const CompletionCallback& callback) {
566 callback.Run(response);
567}
568
569void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
570 const AuthCallback& callback) {
571 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
572 ASSERT_TRUE(target_auth_credentials_ != NULL);
573 *target_auth_credentials_ = auth_credentials_;
574 }
575 callback.Run(response);
576}
577
578int BlockingNetworkDelegate::OnBeforeURLRequest(
579 URLRequest* request,
580 const CompletionCallback& callback,
581 GURL* new_url) {
582 if (redirect_url_ == request->url())
583 return OK; // We've already seen this request and redirected elsewhere.
584
585 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
586
587 if (!redirect_url_.is_empty())
588 *new_url = redirect_url_;
589
Helen Lib495c3802018-03-30 13:46:09590 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
[email protected]dc5a5cf2012-09-26 02:49:30591}
592
ryansturm2343cb62016-06-15 01:09:00593int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30594 URLRequest* request,
595 const CompletionCallback& callback,
596 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00597 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30598
Helen Lib495c3802018-03-30 13:46:09599 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
[email protected]dc5a5cf2012-09-26 02:49:30600}
601
602int BlockingNetworkDelegate::OnHeadersReceived(
603 URLRequest* request,
604 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32605 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16606 scoped_refptr<HttpResponseHeaders>* override_response_headers,
607 GURL* allowed_unsafe_redirect_url) {
608 TestNetworkDelegate::OnHeadersReceived(request,
609 callback,
610 original_response_headers,
611 override_response_headers,
612 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30613
Helen Lib495c3802018-03-30 13:46:09614 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
[email protected]dc5a5cf2012-09-26 02:49:30615}
616
617NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
618 URLRequest* request,
619 const AuthChallengeInfo& auth_info,
620 const AuthCallback& callback,
621 AuthCredentials* credentials) {
622 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
623 credentials);
624 // Check that the user has provided callback for the previous blocked stage.
625 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
626
627 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
628 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
629 }
630
631 target_auth_credentials_ = credentials;
632
633 switch (block_mode_) {
634 case SYNCHRONOUS:
635 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
636 *target_auth_credentials_ = auth_credentials_;
637 return auth_retval_;
638
639 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45640 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30641 FROM_HERE,
642 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
643 weak_factory_.GetWeakPtr(), auth_retval_, callback));
644 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
645
646 case USER_CALLBACK:
647 auth_callback_ = callback;
648 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45649 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17650 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30651 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
652 }
653 NOTREACHED();
654 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
655}
656
657void BlockingNetworkDelegate::Reset() {
658 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
659 stage_blocked_for_callback_ = NOT_BLOCKED;
660 callback_.Reset();
661 auth_callback_.Reset();
662}
663
664int BlockingNetworkDelegate::MaybeBlockStage(
665 BlockingNetworkDelegate::Stage stage,
666 const CompletionCallback& callback) {
667 // Check that the user has provided callback for the previous blocked stage.
668 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
669
670 if ((block_on_ & stage) == 0) {
671 return OK;
672 }
673
674 switch (block_mode_) {
675 case SYNCHRONOUS:
676 EXPECT_NE(OK, retval_);
677 return retval_;
678
679 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45680 base::ThreadTaskRunnerHandle::Get()->PostTask(
681 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
682 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30683 return ERR_IO_PENDING;
684
685 case USER_CALLBACK:
686 callback_ = callback;
687 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45688 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17689 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30690 return ERR_IO_PENDING;
691 }
692 NOTREACHED();
693 return 0;
694}
695
[email protected]d5a4dd62012-05-23 01:41:04696class TestURLRequestContextWithProxy : public TestURLRequestContext {
697 public:
698 // Does not own |delegate|.
699 TestURLRequestContextWithProxy(const std::string& proxy,
700 NetworkDelegate* delegate)
701 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59702 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49703 ProxyResolutionService::CreateFixed(proxy,
704 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04705 set_network_delegate(delegate);
706 Init();
707 }
Chris Watkins7a41d3552017-12-01 02:13:27708 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04709};
710
stefanocsbd5be5202016-06-10 03:37:55711// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01712// URI and report to be sent.
713class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55714 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01715 public:
Chris Watkins7a41d3552017-12-01 02:13:27716 MockCertificateReportSender() = default;
717 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01718
meacer5d4dc5a2017-04-27 20:37:48719 void Send(const GURL& report_uri,
720 base::StringPiece content_type,
721 base::StringPiece report,
722 const base::Callback<void()>& success_callback,
723 const base::Callback<void(const GURL&, int, int)>& error_callback)
724 override {
estark06e0dac2015-08-07 21:56:01725 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44726 report.CopyToString(&latest_report_);
727 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01728 }
estark06e0dac2015-08-07 21:56:01729 const GURL& latest_report_uri() { return latest_report_uri_; }
730 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44731 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01732
733 private:
734 GURL latest_report_uri_;
735 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44736 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01737};
738
estarkcd39c11f2015-10-19 19:46:36739class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
740 public:
741 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
742};
743
dadrian612337a2016-07-20 22:36:58744// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
745// This is needed because after the certificate failure, the URLRequest will
746// retry the connection, and return a partial SSLInfo with a cached cert status.
747// The partial SSLInfo does not have the OCSP information filled out.
748class OCSPErrorTestDelegate : public TestDelegate {
749 public:
750 void OnSSLCertificateError(URLRequest* request,
751 const SSLInfo& ssl_info,
752 bool fatal) override {
753 ssl_info_ = ssl_info;
754 on_ssl_certificate_error_called_ = true;
755 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
756 }
757
758 bool on_ssl_certificate_error_called() {
759 return on_ssl_certificate_error_called_;
760 }
761
762 SSLInfo ssl_info() { return ssl_info_; }
763
764 private:
765 bool on_ssl_certificate_error_called_ = false;
766 SSLInfo ssl_info_;
767};
768
[email protected]d5a4dd62012-05-23 01:41:04769} // namespace
770
[email protected]a592c0432012-12-01 18:10:29771// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
Bence Béky98447b12018-05-08 03:14:01772class URLRequestTest : public PlatformTest, public WithScopedTaskEnvironment {
[email protected]abb26092010-11-11 22:19:00773 public:
fdorayf33fede2017-05-11 21:18:10774 URLRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:09775 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25776 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50777 job_factory_impl_ = new URLRequestJobFactoryImpl();
778 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50779 }
bengr1bf8e942014-11-07 01:36:50780
dcheng67be2b1f2014-10-27 21:47:29781 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18782 // URLRequestJobs may post clean-up tasks on destruction.
783 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35784
785 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18786 }
[email protected]87a09a92011-07-14 15:50:50787
dcheng2339883c2014-12-23 00:23:05788 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50789 SetUpFactory();
790 default_context_.set_job_factory(job_factory_.get());
791 default_context_.Init();
792 PlatformTest::SetUp();
793 }
794
795 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20796 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04797 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34798#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50799 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19800 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07801 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50802#endif
803 }
804
805 TestNetworkDelegate* default_network_delegate() {
806 return &default_network_delegate_;
807 }
808
809 const TestURLRequestContext& default_context() const {
810 return default_context_;
811 }
812
813
[email protected]3c5ca8c2011-09-29 01:14:51814 // Adds the TestJobInterceptor to the default context.
815 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23816 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20817 job_factory_impl_->SetProtocolHandler("http", nullptr);
818 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36819 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23820 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51821 }
822
Sergey Ulanov2e49f492017-09-14 19:37:51823 // Creates a temp test file and writes |data| to the file. The file will be
824 // deleted after the test completes.
825 void CreateTestFile(const char* data,
826 size_t data_size,
827 base::FilePath* test_file) {
828 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
829 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
830 // now, Mac and Android bots return a path with a symbolic link.
831 base::FilePath absolute_temp_dir =
832 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
833
834 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
835 ASSERT_EQ(static_cast<int>(data_size),
836 base::WriteFile(*test_file, data, data_size));
837 }
838
[email protected]87a09a92011-07-14 15:50:50839 protected:
vishal.b62985ca92015-04-17 08:45:51840 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24841 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50842 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36843 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09844 TestURLRequestContext default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51845 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48846};
847
satoruxddac0442017-05-29 06:06:18848// This NetworkDelegate is picky about what files are accessible. Only
849// whitelisted files are allowed.
850class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
851 public:
Chris Watkins7a41d3552017-12-01 02:13:27852 CookieBlockingNetworkDelegate() = default;
853 ;
satoruxddac0442017-05-29 06:06:18854
855 // Adds |directory| to the access white list.
856 void AddToWhitelist(const base::FilePath& directory) {
857 whitelist_.insert(directory);
858 }
859
860 private:
861 // Returns true if |path| matches the white list.
862 bool OnCanAccessFileInternal(const base::FilePath& path) const {
863 for (const auto& directory : whitelist_) {
864 if (directory == path || directory.IsParent(path))
865 return true;
866 }
867 return false;
868 }
869
870 // Returns true only if both |original_path| and |absolute_path| match the
871 // white list.
872 bool OnCanAccessFile(const URLRequest& request,
873 const base::FilePath& original_path,
874 const base::FilePath& absolute_path) const override {
875 return (OnCanAccessFileInternal(original_path) &&
876 OnCanAccessFileInternal(absolute_path));
877 }
878
879 std::set<base::FilePath> whitelist_;
880
881 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
882};
883
[email protected]316c1e5e2012-09-12 15:17:44884TEST_F(URLRequestTest, AboutBlankTest) {
885 TestDelegate d;
886 {
rhalavatib7bd7c792017-04-27 05:25:16887 std::unique_ptr<URLRequest> r(
888 default_context_.CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
889 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44890
[email protected]f7022f32014-08-21 16:32:19891 r->Start();
892 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44893
[email protected]255620da2013-08-19 13:14:29894 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44895
[email protected]f7022f32014-08-21 16:32:19896 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44897 EXPECT_FALSE(d.received_data_before_response());
898 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19899 EXPECT_EQ("", r->GetSocketAddress().host());
900 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04901
902 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19903 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44904 }
905}
906
907TEST_F(URLRequestTest, DataURLImageTest) {
908 TestDelegate d;
909 {
910 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36911 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
912 GURL("data:image/png;base64,"
913 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
914 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
915 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
916 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
917 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
918 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
919 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
920 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
921 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
922 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
923 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
924 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
925 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
926 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
927 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
928 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
929 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
930 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
931 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16932 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44933
[email protected]f7022f32014-08-21 16:32:19934 r->Start();
935 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44936
[email protected]255620da2013-08-19 13:14:29937 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44938
[email protected]f7022f32014-08-21 16:32:19939 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44940 EXPECT_FALSE(d.received_data_before_response());
941 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19942 EXPECT_EQ("", r->GetSocketAddress().host());
943 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04944
945 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19946 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44947 }
948}
949
brettwa1228ebb2016-10-28 03:51:34950#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44951TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51952 const char kTestFileContent[] = "Hello";
953 base::FilePath test_file;
954 ASSERT_NO_FATAL_FAILURE(
955 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04956
Sergey Ulanov2e49f492017-09-14 19:37:51957 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44958
959 TestDelegate d;
960 {
rhalavatib7bd7c792017-04-27 05:25:16961 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51962 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44963
[email protected]f7022f32014-08-21 16:32:19964 r->Start();
965 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44966
[email protected]255620da2013-08-19 13:14:29967 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44968
[email protected]f7022f32014-08-21 16:32:19969 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44970 EXPECT_EQ(1, d.response_started_count());
971 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:51972 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:19973 EXPECT_EQ("", r->GetSocketAddress().host());
974 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04975
976 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19977 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44978 }
979}
980
[email protected]ba40bb762012-12-17 07:11:04981TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:51982 const char kTestFileContent[] = "Hello";
983 base::FilePath test_file;
984 ASSERT_NO_FATAL_FAILURE(
985 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
986
987 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:04988
989 TestDelegate d;
990 {
rhalavatib7bd7c792017-04-27 05:25:16991 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51992 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:04993
[email protected]f7022f32014-08-21 16:32:19994 r->Start();
995 EXPECT_TRUE(r->is_pending());
996 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04997 }
[email protected]79e1fd62013-06-20 06:50:04998 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04999 // destroyed.
[email protected]255620da2013-08-19 13:14:291000 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:041001}
1002
[email protected]316c1e5e2012-09-12 15:17:441003TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1004 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361005 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441006 FillBuffer(buffer.get(), buffer_size);
1007
Sergey Ulanov2e49f492017-09-14 19:37:511008 base::FilePath test_file;
1009 ASSERT_NO_FATAL_FAILURE(
1010 CreateTestFile(buffer.get(), buffer_size, &test_file));
1011 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441012
1013 const size_t first_byte_position = 500;
1014 const size_t last_byte_position = buffer_size - first_byte_position;
1015 const size_t content_length = last_byte_position - first_byte_position + 1;
1016 std::string partial_buffer_string(buffer.get() + first_byte_position,
1017 buffer.get() + last_byte_position + 1);
1018
1019 TestDelegate d;
1020 {
rhalavatib7bd7c792017-04-27 05:25:161021 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1022 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441023
1024 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381025 headers.SetHeader(
1026 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591027 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381028 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191029 r->SetExtraRequestHeaders(headers);
1030 r->Start();
1031 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441032
[email protected]255620da2013-08-19 13:14:291033 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191034 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441035 EXPECT_EQ(1, d.response_started_count());
1036 EXPECT_FALSE(d.received_data_before_response());
1037 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1038 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1039 EXPECT_TRUE(partial_buffer_string == d.data_received());
1040 }
[email protected]316c1e5e2012-09-12 15:17:441041}
1042
1043TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1044 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361045 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441046 FillBuffer(buffer.get(), buffer_size);
1047
Sergey Ulanov2e49f492017-09-14 19:37:511048 base::FilePath test_file;
1049 ASSERT_NO_FATAL_FAILURE(
1050 CreateTestFile(buffer.get(), buffer_size, &test_file));
1051 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441052
1053 const size_t first_byte_position = 500;
1054 const size_t last_byte_position = buffer_size - 1;
1055 const size_t content_length = last_byte_position - first_byte_position + 1;
1056 std::string partial_buffer_string(buffer.get() + first_byte_position,
1057 buffer.get() + last_byte_position + 1);
1058
1059 TestDelegate d;
1060 {
rhalavatib7bd7c792017-04-27 05:25:161061 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1062 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441063
1064 HttpRequestHeaders headers;
1065 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591066 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381067 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191068 r->SetExtraRequestHeaders(headers);
1069 r->Start();
1070 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441071
[email protected]255620da2013-08-19 13:14:291072 base::RunLoop().Run();
[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, FileTestMultipleRanges) {
1083 const size_t buffer_size = 400000;
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 TestDelegate d;
1093 {
rhalavatib7bd7c792017-04-27 05:25:161094 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1095 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441096
1097 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381098 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191099 r->SetExtraRequestHeaders(headers);
1100 r->Start();
1101 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441102
[email protected]255620da2013-08-19 13:14:291103 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441104 EXPECT_TRUE(d.request_failed());
1105 }
[email protected]316c1e5e2012-09-12 15:17:441106}
1107
[email protected]3ca8b362013-11-11 22:18:071108TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511109 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071110 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511111 ASSERT_NO_FATAL_FAILURE(
1112 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1113
satoruxddac0442017-05-29 06:06:181114 // The directory part of the path returned from CreateTemporaryFileInDir()
1115 // can be slightly different from |absolute_temp_dir| on Windows.
1116 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1117 // Hence the test should use the directory name of |test_file|, rather than
1118 // |absolute_temp_dir|, for whitelisting.
1119 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591120 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071121 {
1122 TestDelegate d;
satoruxddac0442017-05-29 06:06:181123 CookieBlockingNetworkDelegate network_delegate;
1124 network_delegate.AddToWhitelist(real_temp_dir);
[email protected]3ca8b362013-11-11 22:18:071125 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161126 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1127 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191128 r->Start();
[email protected]3ca8b362013-11-11 22:18:071129 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181130 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071131 EXPECT_FALSE(d.request_failed());
1132 EXPECT_EQ(test_data, d.data_received());
1133 }
1134
1135 {
1136 TestDelegate d;
satoruxddac0442017-05-29 06:06:181137 CookieBlockingNetworkDelegate network_delegate;
[email protected]3ca8b362013-11-11 22:18:071138 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161139 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1140 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191141 r->Start();
[email protected]3ca8b362013-11-11 22:18:071142 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181143 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071144 EXPECT_TRUE(d.request_failed());
1145 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181146 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071147 }
1148}
1149
Kevin Marshalla9f05ec2017-07-14 02:10:051150#if defined(OS_POSIX) && !defined(OS_FUCHSIA) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181151
1152TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511153 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181154 // Get an absolute path since temp_dir can contain a symbolic link.
1155 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511156 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181157
1158 // Create a good directory (will be whitelisted) and a good file.
1159 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1160 ASSERT_TRUE(base::CreateDirectory(good_dir));
1161 base::FilePath good_file;
1162 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1163 std::string good_data("good");
1164 base::WriteFile(good_file, good_data.data(), good_data.size());
1165 // See the comment in AllowFileURLs() for why this is done.
1166 base::FilePath real_good_dir = good_file.DirName();
1167
1168 // Create a bad directory (will not be whitelisted) and a bad file.
1169 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1170 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1171 base::FilePath bad_file;
1172 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1173 std::string bad_data("bad");
1174 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1175
1176 // This symlink will point to the good file. Access to the symlink will be
1177 // allowed as both the symlink and the destination file are in the same
1178 // good directory.
1179 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1180 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1181 GURL good_file_url = FilePathToFileURL(good_symlink);
1182 // This symlink will point to the bad file. Even though the symlink is in
1183 // the good directory, access to the symlink will be rejected since it
1184 // points to the bad file.
1185 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1186 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1187 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1188
1189 CookieBlockingNetworkDelegate network_delegate;
1190 network_delegate.AddToWhitelist(real_good_dir);
1191 {
1192 TestDelegate d;
1193 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371194 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1195 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181196 r->Start();
1197 base::RunLoop().Run();
1198 // good_file_url should be allowed.
1199 EXPECT_FALSE(d.request_failed());
1200 EXPECT_EQ(good_data, d.data_received());
1201 }
1202
1203 {
1204 TestDelegate d;
1205 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371206 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1207 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181208 r->Start();
1209 base::RunLoop().Run();
1210 // bad_file_url should be rejected.
1211 EXPECT_TRUE(d.request_failed());
1212 EXPECT_EQ("", d.data_received());
1213 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1214 }
1215}
1216
1217TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511218 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181219 // Get an absolute path since temp_dir can contain a symbolic link.
1220 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511221 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181222
1223 // Create a good directory (will be whitelisted).
1224 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1225 ASSERT_TRUE(base::CreateDirectory(good_dir));
1226
1227 // Create a bad directory (will not be whitelisted).
1228 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1229 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1230
1231 // This symlink will point to the good directory. Access to the symlink
1232 // will be allowed as the symlink is in the good dir that'll be white
1233 // listed.
1234 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1235 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1236 GURL good_file_url = FilePathToFileURL(good_symlink);
1237 // This symlink will point to the bad directory. Even though the symlink is
1238 // in the good directory, access to the symlink will be rejected since it
1239 // points to the bad directory.
1240 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1241 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1242 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1243
1244 CookieBlockingNetworkDelegate network_delegate;
1245 network_delegate.AddToWhitelist(good_dir);
1246 {
1247 TestDelegate d;
1248 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371249 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1250 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181251 r->Start();
1252 base::RunLoop().Run();
1253 // good_file_url should be allowed.
1254 EXPECT_FALSE(d.request_failed());
1255 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1256 }
1257
1258 {
1259 TestDelegate d;
1260 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371261 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1262 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181263 r->Start();
1264 base::RunLoop().Run();
1265 // bad_file_url should be rejected.
1266 EXPECT_TRUE(d.request_failed());
1267 EXPECT_EQ("", d.data_received());
1268 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1269 }
1270}
1271
Kevin Marshalla9f05ec2017-07-14 02:10:051272#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]316c1e5e2012-09-12 15:17:441273
1274TEST_F(URLRequestTest, FileDirCancelTest) {
1275 // Put in mock resource provider.
1276 NetModule::SetResourceProvider(TestNetResourceProvider);
1277
1278 TestDelegate d;
1279 {
[email protected]6cdfd7f2013-02-08 20:40:151280 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:191281 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
[email protected]316c1e5e2012-09-12 15:17:441282 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1283 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1284
danakj8522a25b2016-04-16 00:17:361285 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161286 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1287 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191288 req->Start();
1289 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441290
1291 d.set_cancel_in_received_data_pending(true);
1292
[email protected]255620da2013-08-19 13:14:291293 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441294 }
1295
1296 // Take out mock resource provider.
1297 NetModule::SetResourceProvider(NULL);
1298}
1299
[email protected]5f9581402013-10-30 13:08:321300TEST_F(URLRequestTest, FileDirOutputSanity) {
1301 // Verify the general sanity of the the output of the file:
1302 // directory lister by checking for the output of a known existing
1303 // file.
1304 const char sentinel_name[] = "filedir-sentinel";
1305
1306 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191307 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471308 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321309
1310 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161311 std::unique_ptr<URLRequest> req(
1312 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1313 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191314 req->Start();
[email protected]5f9581402013-10-30 13:08:321315 base::RunLoop().Run();
1316
1317 // Generate entry for the sentinel file.
1318 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581319 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491320 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321321 EXPECT_GT(info.size, 0);
1322 std::string sentinel_output = GetDirectoryListingEntry(
1323 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181324 std::string(sentinel_name), false /* is_dir */, info.size,
1325
[email protected]5f9581402013-10-30 13:08:321326 info.last_modified);
1327
1328 ASSERT_LT(0, d.bytes_received());
1329 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501330 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321331 // Check for the entry generated for the "sentinel" file.
1332 const std::string& data = d.data_received();
1333 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1334}
1335
[email protected]316c1e5e2012-09-12 15:17:441336TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1337 // There is an implicit redirect when loading a file path that matches a
1338 // directory and does not end with a slash. Ensure that following such
1339 // redirects does not crash. See http://crbug.com/18686.
1340
[email protected]6cdfd7f2013-02-08 20:40:151341 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:191342 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471343 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441344
1345 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161346 std::unique_ptr<URLRequest> req(
1347 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1348 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191349 req->Start();
[email protected]255620da2013-08-19 13:14:291350 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441351
1352 ASSERT_EQ(1, d.received_redirect_count());
1353 ASSERT_LT(0, d.bytes_received());
1354 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501355 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441356}
1357
1358#if defined(OS_WIN)
1359// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1360TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1361 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161362 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
1363 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191364 req->Start();
[email protected]255620da2013-08-19 13:14:291365 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441366
1367 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501368 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441369}
[email protected]5ecf7cb282014-05-11 01:49:551370#endif // defined(OS_WIN)
1371
brettwa1228ebb2016-10-28 03:51:341372#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551373
1374TEST_F(URLRequestTest, InvalidUrlTest) {
1375 TestDelegate d;
1376 {
rhalavatib7bd7c792017-04-27 05:25:161377 std::unique_ptr<URLRequest> r(
1378 default_context_.CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1379 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551380
[email protected]f7022f32014-08-21 16:32:191381 r->Start();
1382 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551383
1384 base::RunLoop().Run();
1385 EXPECT_TRUE(d.request_failed());
1386 }
1387}
1388
jochen0e3b3a62014-09-16 18:31:231389TEST_F(URLRequestTest, InvalidReferrerTest) {
1390 TestURLRequestContext context;
1391 TestNetworkDelegate network_delegate;
1392 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1393 context.set_network_delegate(&network_delegate);
1394 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361395 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161396 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1397 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231398 req->SetReferrer("https://somewhere.com/");
1399
1400 req->Start();
1401 base::RunLoop().Run();
1402 EXPECT_TRUE(d.request_failed());
1403}
1404
[email protected]5ecf7cb282014-05-11 01:49:551405#if defined(OS_WIN)
1406TEST_F(URLRequestTest, ResolveShortcutTest) {
1407 base::FilePath app_path;
Avi Drissman5c80d832018-05-01 17:01:191408 base::PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471409 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551410 app_path = app_path.AppendASCII("with-headers.html");
1411
1412 std::wstring lnk_path = app_path.value() + L".lnk";
1413
1414 base::win::ScopedCOMInitializer com_initializer;
1415
1416 // Temporarily create a shortcut for test
1417 {
Robert Liaoc88f99d12017-10-17 21:48:331418 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161419 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1420 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331421 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001422 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551423 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1424 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1425 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1426 }
1427
1428 TestDelegate d;
1429 {
danakj8522a25b2016-04-16 00:17:361430 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161431 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1432 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551433
[email protected]f7022f32014-08-21 16:32:191434 r->Start();
1435 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551436
1437 base::RunLoop().Run();
1438
1439 WIN32_FILE_ATTRIBUTE_DATA data;
1440 GetFileAttributesEx(app_path.value().c_str(),
1441 GetFileExInfoStandard, &data);
1442 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1443 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1444 FILE_ATTRIBUTE_NORMAL, NULL);
1445 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361446 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551447 DWORD read_size;
1448 BOOL result;
1449 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1450 &read_size, NULL);
1451 std::string content(buffer.get(), read_size);
1452 CloseHandle(file);
1453
[email protected]f7022f32014-08-21 16:32:191454 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551455 EXPECT_EQ(1, d.received_redirect_count());
1456 EXPECT_EQ(content, d.data_received());
1457 }
1458
1459 // Clean the shortcut
1460 DeleteFile(lnk_path.c_str());
1461}
1462#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441463
1464// Custom URLRequestJobs for use with interceptor tests
1465class RestartTestJob : public URLRequestTestJob {
1466 public:
1467 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1468 : URLRequestTestJob(request, network_delegate, true) {}
1469 protected:
dchengb03027d2014-10-21 12:00:201470 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441471 private:
Chris Watkins7a41d3552017-12-01 02:13:271472 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441473};
1474
1475class CancelTestJob : public URLRequestTestJob {
1476 public:
1477 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1478 : URLRequestTestJob(request, network_delegate, true) {}
1479 protected:
dchengb03027d2014-10-21 12:00:201480 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441481 private:
Chris Watkins7a41d3552017-12-01 02:13:271482 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441483};
1484
1485class CancelThenRestartTestJob : public URLRequestTestJob {
1486 public:
1487 explicit CancelThenRestartTestJob(URLRequest* request,
1488 NetworkDelegate* network_delegate)
1489 : URLRequestTestJob(request, network_delegate, true) {
1490 }
1491 protected:
dchengb03027d2014-10-21 12:00:201492 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441493 request_->Cancel();
1494 this->NotifyRestartRequired();
1495 }
1496 private:
Chris Watkins7a41d3552017-12-01 02:13:271497 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441498};
1499
bengr1bf8e942014-11-07 01:36:501500// An Interceptor for use with interceptor tests.
1501class MockURLRequestInterceptor : public URLRequestInterceptor {
1502 public:
1503 // Static getters for canned response header and data strings.
1504 static std::string ok_data() {
1505 return URLRequestTestJob::test_data_1();
1506 }
1507
1508 static std::string ok_headers() {
1509 return URLRequestTestJob::test_headers();
1510 }
1511
1512 static std::string redirect_data() {
1513 return std::string();
1514 }
1515
1516 static std::string redirect_headers() {
1517 return URLRequestTestJob::test_redirect_headers();
1518 }
1519
1520 static std::string error_data() {
1521 return std::string("ohhh nooooo mr. bill!");
1522 }
1523
1524 static std::string error_headers() {
1525 return URLRequestTestJob::test_error_headers();
1526 }
1527
1528 MockURLRequestInterceptor()
1529 : intercept_main_request_(false), restart_main_request_(false),
1530 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1531 simulate_main_network_error_(false),
1532 intercept_redirect_(false), cancel_redirect_request_(false),
1533 intercept_final_response_(false), cancel_final_request_(false),
1534 use_url_request_http_job_(false),
1535 did_intercept_main_(false), did_restart_main_(false),
1536 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1537 did_simulate_error_main_(false),
1538 did_intercept_redirect_(false), did_cancel_redirect_(false),
1539 did_intercept_final_(false), did_cancel_final_(false) {
1540 }
1541
Chris Watkins7a41d3552017-12-01 02:13:271542 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501543
1544 // URLRequestInterceptor implementation:
1545 URLRequestJob* MaybeInterceptRequest(
1546 URLRequest* request,
1547 NetworkDelegate* network_delegate) const override {
1548 if (restart_main_request_) {
1549 restart_main_request_ = false;
1550 did_restart_main_ = true;
1551 return new RestartTestJob(request, network_delegate);
1552 }
1553 if (cancel_main_request_) {
1554 cancel_main_request_ = false;
1555 did_cancel_main_ = true;
1556 return new CancelTestJob(request, network_delegate);
1557 }
1558 if (cancel_then_restart_main_request_) {
1559 cancel_then_restart_main_request_ = false;
1560 did_cancel_then_restart_main_ = true;
1561 return new CancelThenRestartTestJob(request, network_delegate);
1562 }
1563 if (simulate_main_network_error_) {
1564 simulate_main_network_error_ = false;
1565 did_simulate_error_main_ = true;
1566 if (use_url_request_http_job_) {
1567 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1568 }
1569 // This job will result in error since the requested URL is not one of the
1570 // URLs supported by these tests.
1571 return new URLRequestTestJob(request, network_delegate, true);
1572 }
1573 if (!intercept_main_request_)
1574 return nullptr;
1575 intercept_main_request_ = false;
1576 did_intercept_main_ = true;
1577 URLRequestTestJob* job = new URLRequestTestJob(request,
1578 network_delegate,
1579 main_headers_,
1580 main_data_,
1581 true);
1582 job->set_load_timing_info(main_request_load_timing_info_);
1583 return job;
1584 }
1585
1586 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1587 NetworkDelegate* network_delegate,
1588 const GURL& location) const override {
1589 if (cancel_redirect_request_) {
1590 cancel_redirect_request_ = false;
1591 did_cancel_redirect_ = true;
1592 return new CancelTestJob(request, network_delegate);
1593 }
1594 if (!intercept_redirect_)
1595 return nullptr;
1596 intercept_redirect_ = false;
1597 did_intercept_redirect_ = true;
1598 if (use_url_request_http_job_) {
1599 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1600 }
1601 return new URLRequestTestJob(request,
1602 network_delegate,
1603 redirect_headers_,
1604 redirect_data_,
1605 true);
1606 }
1607
1608 URLRequestJob* MaybeInterceptResponse(
1609 URLRequest* request,
1610 NetworkDelegate* network_delegate) const override {
1611 if (cancel_final_request_) {
1612 cancel_final_request_ = false;
1613 did_cancel_final_ = true;
1614 return new CancelTestJob(request, network_delegate);
1615 }
1616 if (!intercept_final_response_)
1617 return nullptr;
1618 intercept_final_response_ = false;
1619 did_intercept_final_ = true;
1620 if (use_url_request_http_job_) {
1621 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1622 }
1623 return new URLRequestTestJob(request,
1624 network_delegate,
1625 final_headers_,
1626 final_data_,
1627 true);
1628 }
1629
1630 void set_intercept_main_request(bool intercept_main_request) {
1631 intercept_main_request_ = intercept_main_request;
1632 }
1633
1634 void set_main_headers(const std::string& main_headers) {
1635 main_headers_ = main_headers;
1636 }
1637
1638 void set_main_data(const std::string& main_data) {
1639 main_data_ = main_data;
1640 }
1641
1642 void set_main_request_load_timing_info(
1643 const LoadTimingInfo& main_request_load_timing_info) {
1644 main_request_load_timing_info_ = main_request_load_timing_info;
1645 }
1646
1647 void set_restart_main_request(bool restart_main_request) {
1648 restart_main_request_ = restart_main_request;
1649 }
1650
1651 void set_cancel_main_request(bool cancel_main_request) {
1652 cancel_main_request_ = cancel_main_request;
1653 }
1654
1655 void set_cancel_then_restart_main_request(
1656 bool cancel_then_restart_main_request) {
1657 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1658 }
1659
1660 void set_simulate_main_network_error(bool simulate_main_network_error) {
1661 simulate_main_network_error_ = simulate_main_network_error;
1662 }
1663
1664 void set_intercept_redirect(bool intercept_redirect) {
1665 intercept_redirect_ = intercept_redirect;
1666 }
1667
1668 void set_redirect_headers(const std::string& redirect_headers) {
1669 redirect_headers_ = redirect_headers;
1670 }
1671
1672 void set_redirect_data(const std::string& redirect_data) {
1673 redirect_data_ = redirect_data;
1674 }
1675
1676 void set_cancel_redirect_request(bool cancel_redirect_request) {
1677 cancel_redirect_request_ = cancel_redirect_request;
1678 }
1679
1680 void set_intercept_final_response(bool intercept_final_response) {
1681 intercept_final_response_ = intercept_final_response;
1682 }
1683
1684 void set_final_headers(const std::string& final_headers) {
1685 final_headers_ = final_headers;
1686 }
1687
1688 void set_final_data(const std::string& final_data) {
1689 final_data_ = final_data;
1690 }
1691
1692 void set_cancel_final_request(bool cancel_final_request) {
1693 cancel_final_request_ = cancel_final_request;
1694 }
1695
1696 void set_use_url_request_http_job(bool use_url_request_http_job) {
1697 use_url_request_http_job_ = use_url_request_http_job;
1698 }
1699
1700 bool did_intercept_main() const {
1701 return did_intercept_main_;
1702 }
1703
1704 bool did_restart_main() const {
1705 return did_restart_main_;
1706 }
1707
1708 bool did_cancel_main() const {
1709 return did_cancel_main_;
1710 }
1711
1712 bool did_cancel_then_restart_main() const {
1713 return did_cancel_then_restart_main_;
1714 }
1715
1716 bool did_simulate_error_main() const {
1717 return did_simulate_error_main_;
1718 }
1719
1720 bool did_intercept_redirect() const {
1721 return did_intercept_redirect_;
1722 }
1723
1724 bool did_cancel_redirect() const {
1725 return did_cancel_redirect_;
1726 }
1727
1728 bool did_intercept_final() const {
1729 return did_intercept_final_;
1730 }
1731
1732 bool did_cancel_final() const {
1733 return did_cancel_final_;
1734 }
1735
1736 private:
1737 // Indicate whether to intercept the main request, and if so specify the
1738 // response to return and the LoadTimingInfo to use.
1739 mutable bool intercept_main_request_;
1740 mutable std::string main_headers_;
1741 mutable std::string main_data_;
1742 mutable LoadTimingInfo main_request_load_timing_info_;
1743
1744 // These indicate actions that can be taken within MaybeInterceptRequest.
1745 mutable bool restart_main_request_;
1746 mutable bool cancel_main_request_;
1747 mutable bool cancel_then_restart_main_request_;
1748 mutable bool simulate_main_network_error_;
1749
1750 // Indicate whether to intercept redirects, and if so specify the response to
1751 // return.
1752 mutable bool intercept_redirect_;
1753 mutable std::string redirect_headers_;
1754 mutable std::string redirect_data_;
1755
1756 // Cancel the request within MaybeInterceptRedirect.
1757 mutable bool cancel_redirect_request_;
1758
1759 // Indicate whether to intercept the final response, and if so specify the
1760 // response to return.
1761 mutable bool intercept_final_response_;
1762 mutable std::string final_headers_;
1763 mutable std::string final_data_;
1764
1765 // Cancel the final request within MaybeInterceptResponse.
1766 mutable bool cancel_final_request_;
1767
1768 // Instruct the interceptor to use a real URLRequestHTTPJob.
1769 mutable bool use_url_request_http_job_;
1770
1771 // These indicate if the interceptor did something or not.
1772 mutable bool did_intercept_main_;
1773 mutable bool did_restart_main_;
1774 mutable bool did_cancel_main_;
1775 mutable bool did_cancel_then_restart_main_;
1776 mutable bool did_simulate_error_main_;
1777 mutable bool did_intercept_redirect_;
1778 mutable bool did_cancel_redirect_;
1779 mutable bool did_intercept_final_;
1780 mutable bool did_cancel_final_;
1781};
1782
1783// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1784class URLRequestInterceptorTest : public URLRequestTest {
1785 public:
1786 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1787 }
1788
1789 ~URLRequestInterceptorTest() override {
1790 // URLRequestJobs may post clean-up tasks on destruction.
1791 base::RunLoop().RunUntilIdle();
1792 }
1793
1794 void SetUpFactory() override {
1795 interceptor_ = new MockURLRequestInterceptor();
1796 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361797 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501798 }
1799
1800 MockURLRequestInterceptor* interceptor() const {
1801 return interceptor_;
1802 }
1803
1804 private:
1805 MockURLRequestInterceptor* interceptor_;
1806};
1807
1808TEST_F(URLRequestInterceptorTest, Intercept) {
1809 // Intercept the main request and respond with a simple response.
1810 interceptor()->set_intercept_main_request(true);
1811 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1812 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591813 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361814 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161815 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1816 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501817 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1818 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1819 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091820 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041821 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1822 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501823 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191824 req->Start();
[email protected]255620da2013-08-19 13:14:291825 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591826
bengr1bf8e942014-11-07 01:36:501827 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091828 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501829 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1830 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591831
bengr1bf8e942014-11-07 01:36:501832 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501833 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501834 EXPECT_EQ(200, req->response_headers()->response_code());
1835 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1836 EXPECT_EQ(1, d.response_started_count());
1837 EXPECT_EQ(0, d.received_redirect_count());
1838}
[email protected]2bba3252013-04-08 19:50:591839
bengr1bf8e942014-11-07 01:36:501840TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1841 // Intercept the main request and respond with a redirect.
1842 interceptor()->set_intercept_main_request(true);
1843 interceptor()->set_main_headers(
1844 MockURLRequestInterceptor::redirect_headers());
1845 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1846
1847 // Intercept that redirect and respond with a final OK response.
1848 interceptor()->set_intercept_redirect(true);
1849 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1850 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1851
1852 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361853 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161854 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1855 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501856 req->set_method("GET");
1857 req->Start();
1858 base::RunLoop().Run();
1859
1860 // Check that the interceptor got called as expected.
1861 EXPECT_TRUE(interceptor()->did_intercept_main());
1862 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1863
1864 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501865 int status = d.request_status();
1866 EXPECT_EQ(OK, status);
1867 if (status == OK)
bengr1bf8e942014-11-07 01:36:501868 EXPECT_EQ(200, req->response_headers()->response_code());
1869
1870 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1871 EXPECT_EQ(1, d.response_started_count());
1872 EXPECT_EQ(0, d.received_redirect_count());
1873}
1874
1875TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1876 // Intercept the main request to generate a server error response.
1877 interceptor()->set_intercept_main_request(true);
1878 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1879 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1880
1881 // Intercept that error and respond with an OK response.
1882 interceptor()->set_intercept_final_response(true);
1883 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1884 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1885
1886 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361887 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161888 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1889 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501890 req->set_method("GET");
1891 req->Start();
1892 base::RunLoop().Run();
1893
1894 // Check that the interceptor got called as expected.
1895 EXPECT_TRUE(interceptor()->did_intercept_main());
1896 EXPECT_TRUE(interceptor()->did_intercept_final());
1897
1898 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501899 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501900 EXPECT_EQ(200, req->response_headers()->response_code());
1901 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1902 EXPECT_EQ(1, d.response_started_count());
1903 EXPECT_EQ(0, d.received_redirect_count());
1904}
1905
1906TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1907 // Intercept the main request to simulate a network error.
1908 interceptor()->set_simulate_main_network_error(true);
1909
1910 // Intercept that error and respond with an OK response.
1911 interceptor()->set_intercept_final_response(true);
1912 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1913 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1914
1915 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361916 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161917 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1918 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501919 req->set_method("GET");
1920 req->Start();
1921 base::RunLoop().Run();
1922
1923 // Check that the interceptor got called as expected.
1924 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1925 EXPECT_TRUE(interceptor()->did_intercept_final());
1926
1927 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501928 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501929 EXPECT_EQ(200, req->response_headers()->response_code());
1930 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1931 EXPECT_EQ(1, d.response_started_count());
1932 EXPECT_EQ(0, d.received_redirect_count());
1933}
1934
1935TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1936 // Restart the main request.
1937 interceptor()->set_restart_main_request(true);
1938
1939 // then intercept the new main request and respond with an OK response
1940 interceptor()->set_intercept_main_request(true);
1941 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1942 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1943
1944 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361945 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161946 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1947 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501948 req->set_method("GET");
1949 req->Start();
1950 base::RunLoop().Run();
1951
1952 // Check that the interceptor got called as expected.
1953 EXPECT_TRUE(interceptor()->did_restart_main());
1954 EXPECT_TRUE(interceptor()->did_intercept_main());
1955
1956 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501957 int status = d.request_status();
1958 EXPECT_EQ(OK, status);
1959 if (status == OK)
bengr1bf8e942014-11-07 01:36:501960 EXPECT_EQ(200, req->response_headers()->response_code());
1961
1962 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1963 EXPECT_EQ(1, d.response_started_count());
1964 EXPECT_EQ(0, d.received_redirect_count());
1965}
1966
1967TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1968 // Intercept the main request and cancel from within the restarted job.
1969 interceptor()->set_cancel_main_request(true);
1970
1971 // Set up to intercept the final response and override it with an OK response.
1972 interceptor()->set_intercept_final_response(true);
1973 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1974 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1975
1976 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361977 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161978 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1979 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501980 req->set_method("GET");
1981 req->Start();
1982 base::RunLoop().Run();
1983
1984 // Check that the interceptor got called as expected.
1985 EXPECT_TRUE(interceptor()->did_cancel_main());
1986 EXPECT_FALSE(interceptor()->did_intercept_final());
1987
1988 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501989 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501990}
1991
1992TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1993 // Intercept the main request and respond with a redirect.
1994 interceptor()->set_intercept_main_request(true);
1995 interceptor()->set_main_headers(
1996 MockURLRequestInterceptor::redirect_headers());
1997 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1998
1999 // Intercept the redirect and cancel from within that job.
2000 interceptor()->set_cancel_redirect_request(true);
2001
2002 // Set up to intercept the final response and override it with an OK response.
2003 interceptor()->set_intercept_final_response(true);
2004 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2005 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2006
2007 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362008 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162009 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2010 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502011 req->set_method("GET");
2012 req->Start();
2013 base::RunLoop().Run();
2014
2015 // Check that the interceptor got called as expected.
2016 EXPECT_TRUE(interceptor()->did_intercept_main());
2017 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2018 EXPECT_FALSE(interceptor()->did_intercept_final());
2019
2020 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502021 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502022}
2023
2024TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2025 // Intercept the main request to simulate a network error.
2026 interceptor()->set_simulate_main_network_error(true);
2027
2028 // Set up to intercept final the response and cancel from within that job.
2029 interceptor()->set_cancel_final_request(true);
2030
2031 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362032 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162033 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2034 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502035 req->set_method("GET");
2036 req->Start();
2037 base::RunLoop().Run();
2038
2039 // Check that the interceptor got called as expected.
2040 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2041 EXPECT_TRUE(interceptor()->did_cancel_final());
2042
2043 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502044 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502045}
2046
2047TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2048 // Intercept the main request and cancel then restart from within that job.
2049 interceptor()->set_cancel_then_restart_main_request(true);
2050
2051 // Set up to intercept the final response and override it with an OK response.
2052 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502053 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2054 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502055
2056 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362057 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162058 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2059 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502060 req->set_method("GET");
2061 req->Start();
2062 base::RunLoop().Run();
2063
2064 // Check that the interceptor got called as expected.
2065 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2066 EXPECT_FALSE(interceptor()->did_intercept_final());
2067
2068 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502069 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592070}
2071
2072// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2073// reused. |connect_time_flags| is used to indicate if there should be dns
2074// or SSL times, and |used_proxy| is used for proxy times.
2075LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2076 int connect_time_flags,
2077 bool used_proxy) {
2078 LoadTimingInfo load_timing;
2079 load_timing.socket_log_id = 1;
2080
2081 if (used_proxy) {
2082 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2083 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2084 }
2085
2086 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2087 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2088 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2089 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2090 }
2091 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2092 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2093 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2094 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2095 }
2096 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2097
2098 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2099 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2100 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2101 return load_timing;
2102}
2103
2104// Same as above, but in the case of a reused socket.
2105LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2106 bool used_proxy) {
2107 LoadTimingInfo load_timing;
2108 load_timing.socket_log_id = 1;
2109 load_timing.socket_reused = true;
2110
2111 if (used_proxy) {
2112 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2113 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2114 }
2115
2116 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2117 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2118 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2119 return load_timing;
2120}
2121
bengr1bf8e942014-11-07 01:36:502122LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2123 const LoadTimingInfo& job_load_timing,
2124 const URLRequestContext& context,
2125 MockURLRequestInterceptor* interceptor) {
2126 interceptor->set_intercept_main_request(true);
2127 interceptor->set_main_request_load_timing_info(job_load_timing);
2128 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162129 std::unique_ptr<URLRequest> req(
2130 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2131 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502132 req->Start();
2133 base::RunLoop().Run();
2134
2135 LoadTimingInfo resulting_load_timing;
2136 req->GetLoadTimingInfo(&resulting_load_timing);
2137
2138 // None of these should be modified by the URLRequest.
2139 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2140 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2141 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2142 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2143 EXPECT_EQ(job_load_timing.receive_headers_end,
2144 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572145 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2146 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502147
2148 return resulting_load_timing;
2149}
2150
[email protected]2bba3252013-04-08 19:50:592151// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502152TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592153 base::TimeTicks now = base::TimeTicks::Now();
2154 LoadTimingInfo job_load_timing =
2155 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2156
[email protected]2ca01e52013-10-31 22:05:192157 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502158 RunURLRequestInterceptorLoadTimingTest(
2159 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592160
2161 // Nothing should have been changed by the URLRequest.
2162 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2163 load_timing_result.proxy_resolve_start);
2164 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2165 load_timing_result.proxy_resolve_end);
2166 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2167 load_timing_result.connect_timing.dns_start);
2168 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2169 load_timing_result.connect_timing.dns_end);
2170 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2171 load_timing_result.connect_timing.connect_start);
2172 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2173 load_timing_result.connect_timing.connect_end);
2174 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2175 load_timing_result.connect_timing.ssl_start);
2176 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2177 load_timing_result.connect_timing.ssl_end);
2178
2179 // Redundant sanity check.
2180 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2181}
2182
2183// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502184TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592185 base::TimeTicks now = base::TimeTicks::Now();
2186 LoadTimingInfo job_load_timing =
2187 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2188
[email protected]2ca01e52013-10-31 22:05:192189 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502190 RunURLRequestInterceptorLoadTimingTest(
2191 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592192
2193 // Nothing should have been changed by the URLRequest.
2194 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2195 load_timing_result.proxy_resolve_start);
2196 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2197 load_timing_result.proxy_resolve_end);
2198 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2199 load_timing_result.connect_timing.dns_start);
2200 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2201 load_timing_result.connect_timing.dns_end);
2202 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2203 load_timing_result.connect_timing.connect_start);
2204 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2205 load_timing_result.connect_timing.connect_end);
2206 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2207 load_timing_result.connect_timing.ssl_start);
2208 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2209 load_timing_result.connect_timing.ssl_end);
2210
2211 // Redundant sanity check.
2212 TestLoadTimingNotReusedWithProxy(load_timing_result,
2213 CONNECT_TIMING_HAS_SSL_TIMES);
2214}
2215
2216// Make sure that URLRequest correctly adjusts proxy times when they're before
2217// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102218// the case of reusing a SPDY session. The connected socket is not considered
2219// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592220//
2221// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502222TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592223 base::TimeTicks now = base::TimeTicks::Now();
2224 LoadTimingInfo job_load_timing =
2225 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2226 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2227 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2228 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2229 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2230 job_load_timing.connect_timing.connect_start =
2231 now - base::TimeDelta::FromDays(2);
2232 job_load_timing.connect_timing.connect_end =
2233 now - base::TimeDelta::FromDays(1);
2234
[email protected]2ca01e52013-10-31 22:05:192235 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502236 RunURLRequestInterceptorLoadTimingTest(
2237 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592238
2239 // Proxy times, connect times, and DNS times should all be replaced with
2240 // request_start.
2241 EXPECT_EQ(load_timing_result.request_start,
2242 load_timing_result.proxy_resolve_start);
2243 EXPECT_EQ(load_timing_result.request_start,
2244 load_timing_result.proxy_resolve_end);
2245 EXPECT_EQ(load_timing_result.request_start,
2246 load_timing_result.connect_timing.dns_start);
2247 EXPECT_EQ(load_timing_result.request_start,
2248 load_timing_result.connect_timing.dns_end);
2249 EXPECT_EQ(load_timing_result.request_start,
2250 load_timing_result.connect_timing.connect_start);
2251 EXPECT_EQ(load_timing_result.request_start,
2252 load_timing_result.connect_timing.connect_end);
2253
2254 // Other times should have been left null.
2255 TestLoadTimingNotReusedWithProxy(load_timing_result,
2256 CONNECT_TIMING_HAS_DNS_TIMES);
2257}
2258
2259// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502260TEST_F(URLRequestInterceptorTest,
2261 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592262 base::TimeTicks now = base::TimeTicks::Now();
2263 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2264 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2265 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2266
[email protected]2ca01e52013-10-31 22:05:192267 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502268 RunURLRequestInterceptorLoadTimingTest(
2269 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592270
2271 // Proxy times and connect times should all be replaced with request_start.
2272 EXPECT_EQ(load_timing_result.request_start,
2273 load_timing_result.proxy_resolve_start);
2274 EXPECT_EQ(load_timing_result.request_start,
2275 load_timing_result.proxy_resolve_end);
2276
2277 // Other times should have been left null.
2278 TestLoadTimingReusedWithProxy(load_timing_result);
2279}
2280
2281// Make sure that URLRequest correctly adjusts connect times when they're before
2282// |request_start|, due to reusing a connected socket. The connected socket is
2283// not considered reused in this test (May be a preconnect).
2284//
2285// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502286TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592287 base::TimeTicks now = base::TimeTicks::Now();
2288 LoadTimingInfo job_load_timing =
2289 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2290 job_load_timing.connect_timing.connect_start =
2291 now - base::TimeDelta::FromDays(1);
2292 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2293 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2294 job_load_timing.connect_timing.connect_end =
2295 now - base::TimeDelta::FromDays(4);
2296
[email protected]2ca01e52013-10-31 22:05:192297 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502298 RunURLRequestInterceptorLoadTimingTest(
2299 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592300
2301 // Connect times, and SSL times should be replaced with request_start.
2302 EXPECT_EQ(load_timing_result.request_start,
2303 load_timing_result.connect_timing.connect_start);
2304 EXPECT_EQ(load_timing_result.request_start,
2305 load_timing_result.connect_timing.ssl_start);
2306 EXPECT_EQ(load_timing_result.request_start,
2307 load_timing_result.connect_timing.ssl_end);
2308 EXPECT_EQ(load_timing_result.request_start,
2309 load_timing_result.connect_timing.connect_end);
2310
2311 // Other times should have been left null.
2312 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2313}
2314
2315// Make sure that URLRequest correctly adjusts connect times when they're before
2316// |request_start|, due to reusing a connected socket in the case that there
2317// are also proxy times. The connected socket is not considered reused in this
2318// test (May be a preconnect).
2319//
2320// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502321TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592322 base::TimeTicks now = base::TimeTicks::Now();
2323 LoadTimingInfo job_load_timing =
2324 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2325 job_load_timing.connect_timing.connect_start =
2326 now - base::TimeDelta::FromDays(1);
2327 job_load_timing.connect_timing.connect_end =
2328 now - base::TimeDelta::FromDays(2);
2329
[email protected]2ca01e52013-10-31 22:05:192330 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502331 RunURLRequestInterceptorLoadTimingTest(
2332 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592333
2334 // Connect times should be replaced with proxy_resolve_end.
2335 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2336 load_timing_result.connect_timing.connect_start);
2337 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2338 load_timing_result.connect_timing.connect_end);
2339
2340 // Other times should have been left null.
2341 TestLoadTimingNotReusedWithProxy(load_timing_result,
2342 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2343}
2344
[email protected]316c1e5e2012-09-12 15:17:442345// Check that two different URL requests have different identifiers.
2346TEST_F(URLRequestTest, Identifiers) {
2347 TestDelegate d;
2348 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362349 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162350 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2351 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362352 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162353 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2354 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442355
mmenke19378d22014-09-09 04:12:592356 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442357}
2358
blundellb8163592f2015-12-16 14:22:422359#if defined(OS_IOS)
2360// TODO(droger): Check that a failure to connect to the proxy is reported to
2361// the network delegate. crbug.com/496743
2362#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2363#else
2364#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2365#endif
2366TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442367 MockHostResolver host_resolver;
2368 host_resolver.rules()->AddSimulatedFailure("*");
2369
[email protected]ceefd7fd2012-11-29 00:36:242370 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442371 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2372
2373 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362374 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162375 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2376 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192377 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442378
[email protected]f7022f32014-08-21 16:32:192379 req->Start();
[email protected]255620da2013-08-19 13:14:292380 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442381
2382 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152383 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472384 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502385 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442386
2387 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012388 EXPECT_THAT(network_delegate.last_error(),
2389 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442390 EXPECT_EQ(1, network_delegate.completed_requests());
2391}
2392
[email protected]cba24642014-08-15 20:49:592393// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442394// content is empty.
2395TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2396 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162397 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2398 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192399 req->Start();
[email protected]255620da2013-08-19 13:14:292400 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442401 EXPECT_EQ("", d.data_received());
2402 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2403}
2404
[email protected]5033ab82013-03-22 20:17:462405// Make sure that SetPriority actually sets the URLRequest's priority
2406// correctly, both before and after start.
2407TEST_F(URLRequestTest, SetPriorityBasic) {
2408 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362409 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162410 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2411 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192412 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462413
[email protected]f7022f32014-08-21 16:32:192414 req->SetPriority(LOW);
2415 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462416
[email protected]f7022f32014-08-21 16:32:192417 req->Start();
2418 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462419
[email protected]f7022f32014-08-21 16:32:192420 req->SetPriority(MEDIUM);
2421 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462422}
2423
2424// Make sure that URLRequest calls SetPriority on a job before calling
2425// Start on it.
2426TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2427 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362428 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162429 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2430 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192431 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462432
mmenkeed0498b2015-12-08 23:20:422433 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362434 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422435 req.get(), &default_network_delegate_, &job_priority));
2436 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2437 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462438
[email protected]f7022f32014-08-21 16:32:192439 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462440
[email protected]f7022f32014-08-21 16:32:192441 req->Start();
mmenkeed0498b2015-12-08 23:20:422442 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462443}
2444
2445// Make sure that URLRequest passes on its priority updates to its
2446// job.
2447TEST_F(URLRequestTest, SetJobPriority) {
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]5033ab82013-03-22 20:17:462452
mmenkeed0498b2015-12-08 23:20:422453 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362454 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422455 req.get(), &default_network_delegate_, &job_priority));
2456 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462457
[email protected]f7022f32014-08-21 16:32:192458 req->SetPriority(LOW);
2459 req->Start();
mmenkeed0498b2015-12-08 23:20:422460 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462461
[email protected]f7022f32014-08-21 16:32:192462 req->SetPriority(MEDIUM);
2463 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422464 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462465}
2466
[email protected]bb1c4662013-11-14 00:00:072467// Setting the IGNORE_LIMITS load flag should be okay if the priority
2468// is MAXIMUM_PRIORITY.
2469TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2470 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362471 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162472 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2473 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192474 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072475
mmenkeed0498b2015-12-08 23:20:422476 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362477 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422478 req.get(), &default_network_delegate_, &job_priority));
2479 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072480
[email protected]f7022f32014-08-21 16:32:192481 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2482 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072483
[email protected]f7022f32014-08-21 16:32:192484 req->SetPriority(MAXIMUM_PRIORITY);
2485 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072486
[email protected]f7022f32014-08-21 16:32:192487 req->Start();
2488 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422489 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072490}
2491
nick5d570de92015-05-04 20:16:162492namespace {
2493
2494// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392495class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442496 public:
David Benjamin42116f62017-11-20 21:45:392497 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552498 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272499 }
tommycli59a63432015-11-06 00:10:552500
David Benjamin42116f62017-11-20 21:45:392501 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552502};
tommyclieae5f75f2015-11-05 19:07:272503
nick5d570de92015-05-04 20:16:162504} // namespace
2505
[email protected]f2f31b32013-01-16 23:24:092506TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392507 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442508 ASSERT_TRUE(test_server.Start());
2509
2510 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362511 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502512 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442513
2514 // Set up a cookie.
2515 {
2516 TestNetworkDelegate network_delegate;
2517 context.set_network_delegate(&network_delegate);
2518 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362519 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552520 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162521 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192522 req->Start();
[email protected]255620da2013-08-19 13:14:292523 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442524 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2525 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2526 EXPECT_EQ(1, network_delegate.set_cookie_count());
2527 }
2528
2529 // Verify that the cookie is set.
2530 {
2531 TestNetworkDelegate network_delegate;
2532 context.set_network_delegate(&network_delegate);
2533 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362534 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162535 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2536 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192537 req->Start();
[email protected]255620da2013-08-19 13:14:292538 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442539
2540 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2541 != std::string::npos);
2542 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2543 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2544 }
2545}
2546
[email protected]f2f31b32013-01-16 23:24:092547TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392548 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442549 ASSERT_TRUE(test_server.Start());
2550
2551 // Set up a cookie.
2552 {
2553 TestNetworkDelegate network_delegate;
2554 default_context_.set_network_delegate(&network_delegate);
2555 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362556 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552557 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162558 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192559 req->Start();
[email protected]255620da2013-08-19 13:14:292560 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442561 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2562 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2563 }
2564
2565 // Verify that the cookie is set.
2566 {
2567 TestNetworkDelegate network_delegate;
2568 default_context_.set_network_delegate(&network_delegate);
2569 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362570 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162571 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2572 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192573 req->Start();
[email protected]255620da2013-08-19 13:14:292574 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442575
2576 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2577 != std::string::npos);
2578 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2579 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2580 }
2581
2582 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2583 {
2584 TestNetworkDelegate network_delegate;
2585 default_context_.set_network_delegate(&network_delegate);
2586 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362587 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162588 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2589 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192590 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2591 req->Start();
[email protected]255620da2013-08-19 13:14:292592 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442593
2594 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2595 == std::string::npos);
2596
2597 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2598 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2599 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2600 }
2601}
2602
2603TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392604 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442605 ASSERT_TRUE(test_server.Start());
2606
2607 // Set up a cookie.
2608 {
2609 TestNetworkDelegate network_delegate;
2610 default_context_.set_network_delegate(&network_delegate);
2611 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362612 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552613 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162614 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192615 req->Start();
[email protected]255620da2013-08-19 13:14:292616 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442617
2618 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2619 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2620 EXPECT_EQ(1, network_delegate.set_cookie_count());
2621 }
2622
2623 // Try to set-up another cookie and update the previous cookie.
2624 {
2625 TestNetworkDelegate network_delegate;
2626 default_context_.set_network_delegate(&network_delegate);
2627 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362628 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552629 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162630 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192631 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2632 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442633
[email protected]255620da2013-08-19 13:14:292634 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442635
2636 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2637 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2638 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2639 EXPECT_EQ(0, network_delegate.set_cookie_count());
2640 }
2641
2642 // Verify the cookies weren't saved or updated.
2643 {
2644 TestNetworkDelegate network_delegate;
2645 default_context_.set_network_delegate(&network_delegate);
2646 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362647 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162648 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2649 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192650 req->Start();
[email protected]255620da2013-08-19 13:14:292651 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442652
2653 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2654 == std::string::npos);
2655 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2656 != std::string::npos);
2657
2658 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2659 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2660 EXPECT_EQ(0, network_delegate.set_cookie_count());
2661 }
2662}
2663
2664TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392665 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442666 ASSERT_TRUE(test_server.Start());
2667
2668 // Set up a cookie.
2669 {
2670 TestNetworkDelegate network_delegate;
2671 default_context_.set_network_delegate(&network_delegate);
2672 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362673 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552674 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162675 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192676 req->Start();
[email protected]255620da2013-08-19 13:14:292677 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442678
2679 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2680 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2681 }
2682
2683 // Verify that the cookie is set.
2684 {
2685 TestNetworkDelegate network_delegate;
2686 default_context_.set_network_delegate(&network_delegate);
2687 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362688 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162689 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2690 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192691 req->Start();
[email protected]255620da2013-08-19 13:14:292692 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442693
2694 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2695 != std::string::npos);
2696
2697 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2698 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2699 }
2700
2701 // Verify that the cookie isn't sent.
2702 {
2703 TestNetworkDelegate network_delegate;
2704 default_context_.set_network_delegate(&network_delegate);
2705 TestDelegate d;
2706 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362707 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162708 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2709 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192710 req->Start();
[email protected]255620da2013-08-19 13:14:292711 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442712
2713 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2714 == std::string::npos);
2715
[email protected]22e045f2013-09-20 03:54:032716 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442717 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2718 }
2719}
2720
marqf14fff8d2015-12-02 15:52:292721// TODO(crbug.com/564656) This test is flaky on iOS.
2722#if defined(OS_IOS)
2723#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2724#else
2725#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2726#endif
[email protected]316c1e5e2012-09-12 15:17:442727TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392728 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442729 ASSERT_TRUE(test_server.Start());
2730
2731 // Set up a cookie.
2732 {
2733 TestNetworkDelegate network_delegate;
2734 default_context_.set_network_delegate(&network_delegate);
2735 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362736 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552737 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162738 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192739 req->Start();
[email protected]255620da2013-08-19 13:14:292740 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442741
2742 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2743 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2744 }
2745
2746 // Try to set-up another cookie and update the previous cookie.
2747 {
2748 TestNetworkDelegate network_delegate;
2749 default_context_.set_network_delegate(&network_delegate);
2750 TestDelegate d;
2751 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362752 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552753 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162754 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192755 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442756
[email protected]255620da2013-08-19 13:14:292757 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442758
2759 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2760 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2761 }
2762
2763 // Verify the cookies weren't saved or updated.
2764 {
2765 TestNetworkDelegate network_delegate;
2766 default_context_.set_network_delegate(&network_delegate);
2767 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362768 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162769 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2770 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192771 req->Start();
[email protected]255620da2013-08-19 13:14:292772 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442773
2774 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2775 == std::string::npos);
2776 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2777 != std::string::npos);
2778
2779 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2780 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2781 }
2782}
2783
2784TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:392785 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442786 ASSERT_TRUE(test_server.Start());
2787
2788 // Set up an empty cookie.
2789 {
2790 TestNetworkDelegate network_delegate;
2791 default_context_.set_network_delegate(&network_delegate);
2792 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362793 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162794 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2795 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192796 req->Start();
[email protected]255620da2013-08-19 13:14:292797 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442798
2799 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2800 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2801 EXPECT_EQ(0, network_delegate.set_cookie_count());
2802 }
2803}
2804
2805TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392806 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442807 ASSERT_TRUE(test_server.Start());
2808
2809 // Set up a cookie.
2810 {
2811 TestNetworkDelegate network_delegate;
2812 default_context_.set_network_delegate(&network_delegate);
2813 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362814 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552815 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162816 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192817 req->Start();
[email protected]255620da2013-08-19 13:14:292818 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442819
2820 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2821 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2822 }
2823
2824 // Verify that the cookie is set.
2825 {
2826 TestNetworkDelegate network_delegate;
2827 default_context_.set_network_delegate(&network_delegate);
2828 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362829 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162830 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2831 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192832 req->Start();
[email protected]255620da2013-08-19 13:14:292833 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442834
2835 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2836 != std::string::npos);
2837
2838 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2839 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2840 }
2841
2842 // Verify that the cookie isn't sent.
2843 {
2844 TestNetworkDelegate network_delegate;
2845 default_context_.set_network_delegate(&network_delegate);
2846 TestDelegate d;
2847 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362848 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162849 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2850 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192851 req->Start();
[email protected]255620da2013-08-19 13:14:292852 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442853
2854 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2855 == std::string::npos);
2856
[email protected]22e045f2013-09-20 03:54:032857 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442858 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2859 }
2860}
2861
2862TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392863 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442864 ASSERT_TRUE(test_server.Start());
2865
2866 // Set up a cookie.
2867 {
2868 TestNetworkDelegate network_delegate;
2869 default_context_.set_network_delegate(&network_delegate);
2870 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362871 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552872 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162873 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192874 req->Start();
[email protected]255620da2013-08-19 13:14:292875 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442876
2877 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2878 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2879 }
2880
2881 // Try to set-up another cookie and update the previous cookie.
2882 {
2883 TestNetworkDelegate network_delegate;
2884 default_context_.set_network_delegate(&network_delegate);
2885 TestDelegate d;
2886 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362887 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552888 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162889 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192890 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442891
[email protected]255620da2013-08-19 13:14:292892 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442893
2894 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2895 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2896 }
2897
2898 // Verify the cookies weren't saved or updated.
2899 {
2900 TestNetworkDelegate network_delegate;
2901 default_context_.set_network_delegate(&network_delegate);
2902 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362903 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162904 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2905 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192906 req->Start();
[email protected]255620da2013-08-19 13:14:292907 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442908
2909 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2910 == std::string::npos);
2911 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2912 != std::string::npos);
2913
2914 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2915 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2916 }
2917}
2918
mkwstc5fa7762016-03-28 09:28:232919TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:392920 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:262921 ASSERT_TRUE(test_server.Start());
2922
mkwst202534e32016-01-15 16:07:152923 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152924 default_context_.set_network_delegate(&network_delegate);
2925
mkwstf71d0bd2016-03-21 14:15:242926 const std::string kHost = "example.test";
2927 const std::string kSubHost = "subdomain.example.test";
2928 const std::string kCrossHost = "cross-origin.test";
2929
2930 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262931 {
mkwst3f3daac2015-02-26 20:15:262932 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362933 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242934 test_server.GetURL(kHost,
2935 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2936 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162937 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262938 req->Start();
2939 base::RunLoop().Run();
2940 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2941 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242942 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262943 }
2944
mkwstf71d0bd2016-03-21 14:15:242945 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262946 {
mkwst3f3daac2015-02-26 20:15:262947 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362948 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162949 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2950 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462951 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:462952 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262953 req->Start();
2954 base::RunLoop().Run();
2955
mkwstf71d0bd2016-03-21 14:15:242956 EXPECT_NE(std::string::npos,
2957 d.data_received().find("StrictSameSiteCookie=1"));
2958 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262959 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2960 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2961 }
2962
clamyfd58ca072016-12-21 17:18:322963 // Verify that both cookies are sent when the request has no initiator (can
2964 // happen for main frame browser-initiated navigations).
2965 {
2966 TestDelegate d;
2967 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162968 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2969 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462970 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:322971 req->Start();
2972 base::RunLoop().Run();
2973
2974 EXPECT_NE(std::string::npos,
2975 d.data_received().find("StrictSameSiteCookie=1"));
2976 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2977 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2978 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2979 }
2980
mkwstf71d0bd2016-03-21 14:15:242981 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262982 {
mkwst3f3daac2015-02-26 20:15:262983 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362984 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162985 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2986 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462987 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:462988 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152989 req->Start();
2990 base::RunLoop().Run();
2991
mkwstf71d0bd2016-03-21 14:15:242992 EXPECT_NE(std::string::npos,
2993 d.data_received().find("StrictSameSiteCookie=1"));
2994 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152995 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2996 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2997 }
2998
mkwstf71d0bd2016-03-21 14:15:242999 // Verify that neither cookie is not sent for cross-site requests.
3000 {
3001 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363002 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163003 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3004 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463005 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463006 req->set_initiator(
3007 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243008 req->Start();
3009 base::RunLoop().Run();
3010
3011 EXPECT_EQ(std::string::npos,
3012 d.data_received().find("StrictSameSiteCookie=1"));
3013 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3014 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3015 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3016 }
3017
3018 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153019 // method is "safe".
3020 {
3021 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363022 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163023 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3024 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463025 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463026 req->set_initiator(
3027 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243028 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153029 req->Start();
3030 base::RunLoop().Run();
3031
mkwstf71d0bd2016-03-21 14:15:243032 EXPECT_EQ(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 sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153040 // method is unsafe (e.g. POST).
3041 {
3042 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363043 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163044 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3045 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463046 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463047 req->set_initiator(
3048 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153049 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263050 req->Start();
3051 base::RunLoop().Run();
3052
mkwstf71d0bd2016-03-21 14:15:243053 EXPECT_EQ(std::string::npos,
3054 d.data_received().find("StrictSameSiteCookie=1"));
3055 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263056 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3057 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3058 }
3059}
3060
estark557a5eb82015-12-01 22:57:103061// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363062TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553063 EmbeddedTestServer http_server;
3064 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363065 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553066 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3067 https_server.AddDefaultHandlers(
3068 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3069 ASSERT_TRUE(http_server.Start());
3070 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363071
estarkb15166b2015-12-18 16:56:383072 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363073 TestURLRequestContext context(true);
3074 context.set_network_delegate(&network_delegate);
3075 context.Init();
3076
estarkb15166b2015-12-18 16:56:383077 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363078 {
3079 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363080 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103081 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163082 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363083 req->Start();
3084 base::RunLoop().Run();
3085 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3086 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3087 }
3088
3089 // Verify that the cookie is not set.
3090 {
3091 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363092 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163093 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3094 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363095 req->Start();
3096 base::RunLoop().Run();
3097
jww79aceda2015-12-07 01:56:343098 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3099 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363100 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3101 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3102 }
3103}
3104
estarkb15166b2015-12-18 16:56:383105TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553106 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3107 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363108 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553109 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363110
3111 TestNetworkDelegate network_delegate;
3112 TestURLRequestContext context(true);
3113 context.set_network_delegate(&network_delegate);
3114 context.Init();
3115
estarkb15166b2015-12-18 16:56:383116 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363117 {
3118 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163119 std::unique_ptr<URLRequest> req(context.CreateRequest(
3120 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3121 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363122 req->Start();
3123 base::RunLoop().Run();
Thiemo Nagel0793b9c532018-04-18 16:57:583124 EXPECT_EQ(0, network_delegate.set_cookie_count());
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();
3136 base::RunLoop().Run();
3137
jww79aceda2015-12-07 01:56:343138 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363139 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3140 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3141 }
3142}
3143
estarkb15166b2015-12-18 16:56:383144TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553145 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3146 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363147 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553148 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363149
estarkb15166b2015-12-18 16:56:383150 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363151 TestURLRequestContext context(true);
3152 context.set_network_delegate(&network_delegate);
3153 context.Init();
3154
estarkb15166b2015-12-18 16:56:383155 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363156 {
3157 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363158 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103159 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163160 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363161 req->Start();
3162 base::RunLoop().Run();
3163 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3164 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3165 }
3166
3167 // Verify that the cookie is set.
3168 {
3169 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363170 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163171 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3172 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363173 req->Start();
3174 base::RunLoop().Run();
3175
jww79aceda2015-12-07 01:56:343176 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3177 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3178 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3179 }
3180}
3181
3182// Tests that secure cookies can't be set on non-secure origins if strict secure
3183// cookies are enabled.
3184TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3185 EmbeddedTestServer http_server;
3186 http_server.AddDefaultHandlers(
3187 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3188 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3189 https_server.AddDefaultHandlers(
3190 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3191 ASSERT_TRUE(http_server.Start());
3192 ASSERT_TRUE(https_server.Start());
3193
3194 TestExperimentalFeaturesNetworkDelegate network_delegate;
3195 TestURLRequestContext context(true);
3196 context.set_network_delegate(&network_delegate);
3197 context.Init();
3198
3199 // Try to set a Secure cookie, with experimental features enabled.
3200 {
3201 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363202 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343203 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163204 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343205 req->Start();
3206 base::RunLoop().Run();
3207 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3208 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3209 }
3210
3211 // Verify that the cookie is not set.
3212 {
3213 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363214 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163215 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3216 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343217 req->Start();
3218 base::RunLoop().Run();
3219
3220 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3221 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3222 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3223 }
3224}
3225
3226// Tests that secure cookies can be set on secure origins even if strict secure
3227// cookies are enabled.
3228TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3229 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3230 https_server.AddDefaultHandlers(
3231 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
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 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163244 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343245 req->Start();
3246 base::RunLoop().Run();
3247 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();
3258 base::RunLoop().Run();
3259
3260 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363261 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3262 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3263 }
3264}
3265
Thiemo Nagel0793b9c532018-04-18 16:57:583266// The parameter is true for same-site and false for cross-site requests.
3267class URLRequestTestParameterizedSameSite
3268 : public URLRequestTest,
3269 public ::testing::WithParamInterface<bool> {
3270 protected:
3271 URLRequestTestParameterizedSameSite() {
3272 auto params = std::make_unique<HttpNetworkSession::Params>();
3273 params->ignore_certificate_errors = true;
3274 context_.set_http_network_session_params(std::move(params));
3275 context_.set_network_delegate(&network_delegate_);
3276 https_server_.AddDefaultHandlers(
3277 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3278 EXPECT_TRUE(https_server_.Start());
3279 }
3280
3281 // To be called after configuration of |context_| has been finalized.
3282 void InitContext() { context_.Init(); }
3283
3284 const std::string kHost_ = "example.test";
3285 const std::string kCrossHost_ = "cross-site.test";
3286 TestURLRequestContext context_{true};
3287 TestNetworkDelegate network_delegate_;
3288 base::HistogramTester histograms_;
3289 EmbeddedTestServer https_server_{EmbeddedTestServer::TYPE_HTTPS};
3290};
3291
3292INSTANTIATE_TEST_CASE_P(URLRequestTest,
3293 URLRequestTestParameterizedSameSite,
3294 ::testing::Bool());
3295
3296TEST_P(URLRequestTestParameterizedSameSite, CookieAgeMetrics) {
3297 const bool same_site = GetParam();
3298 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3299 InitContext();
3300
Mike West86149882017-07-28 10:41:493301 EmbeddedTestServer http_server;
3302 http_server.AddDefaultHandlers(
3303 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
Thiemo Nagel23e0b322018-04-18 12:46:543304 ASSERT_TRUE(http_server.Start());
3305
Thiemo Nagel0793b9c532018-04-18 16:57:583306 // Set two test cookies.
Thiemo Nagel23e0b322018-04-18 12:46:543307 {
3308 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583309 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3310 http_server.GetURL(kHost_, "/set-cookie?cookie=value&cookie2=value2"),
Thiemo Nagel23e0b322018-04-18 12:46:543311 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3312 req->Start();
3313 base::RunLoop().Run();
Thiemo Nagel0793b9c532018-04-18 16:57:583314 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3315 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3316 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3317 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3318 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 0);
3319 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3320 0);
3321 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3322 0);
3323 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3324 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 0);
Thiemo Nagel23e0b322018-04-18 12:46:543325 }
3326
Thiemo Nagel0793b9c532018-04-18 16:57:583327 // Make a secure request.
Thiemo Nagel23e0b322018-04-18 12:46:543328 {
3329 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583330 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3331 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3332 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3333 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103334 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583335 url::Origin::Create(https_server_.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103336 req->Start();
3337 base::RunLoop().Run();
Thiemo Nagel0793b9c532018-04-18 16:57:583338 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3339 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3340 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3341 !same_site);
3342 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3343 same_site);
3344 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3345 0);
3346 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3347 0);
3348 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3349 same_site ? 0 : 2);
3350 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3351 same_site ? 2 : 0);
3352 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3353 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
Mohsen Izadiad6f7592018-04-18 15:57:103354 }
3355
Thiemo Nagel0793b9c532018-04-18 16:57:583356 // Make a non-secure request.
Mohsen Izadiad6f7592018-04-18 15:57:103357 {
3358 TestDelegate d;
Thiemo Nagel0793b9c532018-04-18 16:57:583359 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3360 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
Mohsen Izadiad6f7592018-04-18 15:57:103361 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel0793b9c532018-04-18 16:57:583362 req->set_site_for_cookies(http_server.GetURL(kInitiatingHost, "/"));
Mohsen Izadiad6f7592018-04-18 15:57:103363 req->set_initiator(
Thiemo Nagel0793b9c532018-04-18 16:57:583364 url::Origin::Create(http_server.GetURL(kInitiatingHost, "/")));
Mohsen Izadiad6f7592018-04-18 15:57:103365 req->Start();
3366 base::RunLoop().Run();
Thiemo Nagel0793b9c532018-04-18 16:57:583367 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest",
3368 !same_site);
3369 histograms_.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest",
3370 same_site);
3371 histograms_.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest",
3372 !same_site);
3373 histograms_.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest",
3374 same_site);
3375 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3376 same_site ? 0 : 2);
3377 histograms_.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest",
3378 same_site ? 2 : 0);
3379 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest",
3380 same_site ? 0 : 2);
3381 histograms_.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest",
3382 same_site ? 2 : 0);
3383 EXPECT_TRUE(d.data_received().find("cookie=value") != std::string::npos);
3384 EXPECT_TRUE(d.data_received().find("cookie2=value2") != std::string::npos);
3385 }
3386}
3387
3388// Cookies with secure attribute (no HSTS) --> k1pSecureAttribute
3389TEST_P(URLRequestTestParameterizedSameSite,
3390 CookieNetworkSecurityMetricSecureAttribute) {
3391 const bool same_site = GetParam();
3392 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3393 InitContext();
3394
3395 // Set cookies.
3396 {
3397 TestDelegate d;
3398 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3399 https_server_.GetURL(kHost_,
3400 "/set-cookie?session-cookie=value;Secure&"
3401 "longlived-cookie=value;Secure;domain=" +
3402 kHost_ + ";Max-Age=360000"),
3403 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3404 req->Start();
3405 base::RunLoop().Run();
3406 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3407 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3408 }
3409
3410 // Verify that the cookies fall into the correct metrics bucket.
3411 {
3412 TestDelegate d;
3413 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3414 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3415 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3416 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3417 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3418 req->Start();
3419 base::RunLoop().Run();
3420 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3421 // Static cast of boolean required for MSVC 1911.
3422 histograms_.ExpectBucketCount(
3423 "Cookie.NetworkSecurity",
3424 static_cast<int>(CookieNetworkSecurity::k1pSecureAttribute) |
3425 static_cast<int>(!same_site),
3426 2);
3427 }
3428}
3429
3430// Short-lived host cookie --> k1pHSTSHostCookie
3431TEST_P(URLRequestTestParameterizedSameSite,
3432 CookieNetworkSecurityMetricShortlivedHostCookie) {
3433 const bool same_site = GetParam();
3434 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3435
3436 TransportSecurityState transport_security_state;
3437 transport_security_state.AddHSTS(
3438 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3439 false /* include_subdomains */);
3440 context_.set_transport_security_state(&transport_security_state);
3441 InitContext();
3442
3443 // Set cookie.
3444 {
3445 TestDelegate d;
3446 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3447 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;Max-Age=3600"),
3448 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3449 req->Start();
3450 base::RunLoop().Run();
3451 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3452 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3453 }
3454
3455 // Verify that the cookie falls into the correct metrics bucket.
3456 {
3457 TestDelegate d;
3458 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3459 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3460 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3461 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3462 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3463 req->Start();
3464 base::RunLoop().Run();
3465 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3466 // Static cast of boolean required for MSVC 1911.
3467 histograms_.ExpectBucketCount(
3468 "Cookie.NetworkSecurity",
3469 static_cast<int>(CookieNetworkSecurity::k1pHSTSHostCookie) |
3470 static_cast<int>(!same_site),
3471 1);
3472 }
3473}
3474
3475// Long-lived (either due to expiry or due to being a session cookie) host
3476// cookies --> k1pExpiringHSTSHostCookie
3477TEST_P(URLRequestTestParameterizedSameSite,
3478 CookieNetworkSecurityMetricLonglivedHostCookie) {
3479 const bool same_site = GetParam();
3480 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3481
3482 TransportSecurityState transport_security_state;
3483 transport_security_state.AddHSTS(
3484 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3485 false /* include_subdomains */);
3486 context_.set_transport_security_state(&transport_security_state);
3487 InitContext();
3488
3489 // Set cookies.
3490 {
3491 TestDelegate d;
3492 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3493 https_server_.GetURL(kHost_,
3494 "/set-cookie?session-cookie=value&"
3495 "longlived-cookie=value;Max-Age=360000"),
3496 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3497 req->Start();
3498 base::RunLoop().Run();
3499 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3500 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3501 }
3502
3503 // Verify that the cookies fall into the correct metrics bucket.
3504 {
3505 TestDelegate d;
3506 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3507 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3508 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3509 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3510 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3511 req->Start();
3512 base::RunLoop().Run();
3513 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3514 // Static cast of boolean required for MSVC 1911.
3515 histograms_.ExpectBucketCount(
3516 "Cookie.NetworkSecurity",
3517 static_cast<int>(CookieNetworkSecurity::k1pExpiringHSTSHostCookie) |
3518 static_cast<int>(!same_site),
3519 2);
3520 }
3521}
3522
3523// Domain cookie with HSTS subdomains with cookie expiry before HSTS expiry -->
3524// k1pHSTSSubdomainsIncluded
3525TEST_P(URLRequestTestParameterizedSameSite,
3526 CookieNetworkSecurityMetricShortlivedDomainCookie) {
3527 const bool same_site = GetParam();
3528 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3529
3530 TransportSecurityState transport_security_state;
3531 transport_security_state.AddHSTS(
3532 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3533 true /* include_subdomains */);
3534 context_.set_transport_security_state(&transport_security_state);
3535 InitContext();
3536
3537 // Set cookie.
3538 {
3539 TestDelegate d;
3540 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3541 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3542 kHost_ + ";Max-Age=3600"),
3543 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3544 req->Start();
3545 base::RunLoop().Run();
3546 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3547 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3548 }
3549
3550 // Verify that the cookie falls into the correct metrics bucket.
3551 {
3552 TestDelegate d;
3553 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3554 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3555 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3556 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3557 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3558 req->Start();
3559 base::RunLoop().Run();
3560 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3561 // Static cast of boolean required for MSVC 1911.
3562 histograms_.ExpectBucketCount(
3563 "Cookie.NetworkSecurity",
3564 static_cast<int>(CookieNetworkSecurity::k1pHSTSSubdomainsIncluded) |
3565 static_cast<int>(!same_site),
3566 1);
3567 }
3568}
3569
3570// Long-lived (either due to expiry or due to being a session cookie) domain
3571// cookies with HSTS subdomains --> k1pExpiringHSTSSubdomainsIncluded
3572TEST_P(URLRequestTestParameterizedSameSite,
3573 CookieNetworkSecurityMetricLonglivedDomainCookie) {
3574 const bool same_site = GetParam();
3575 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3576
3577 TransportSecurityState transport_security_state;
3578 transport_security_state.AddHSTS(
3579 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3580 true /* include_subdomains */);
3581 context_.set_transport_security_state(&transport_security_state);
3582 InitContext();
3583
3584 // Set cookies.
3585 {
3586 TestDelegate d;
3587 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3588 https_server_.GetURL(
3589 kHost_, "/set-cookie?session-cookie=value;domain=" + kHost_ + "&" +
3590 "longlived-cookie=value;domain=" + kHost_ +
3591 ";Max-Age=360000"),
3592 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3593 req->Start();
3594 base::RunLoop().Run();
3595 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3596 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3597 }
3598
3599 // Verify that the cookies fall into the correct metrics bucket.
3600 {
3601 TestDelegate d;
3602 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3603 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3604 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3605 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3606 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3607 req->Start();
3608 base::RunLoop().Run();
3609 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3610 // Static cast of boolean required for MSVC 1911.
3611 histograms_.ExpectBucketCount(
3612 "Cookie.NetworkSecurity",
3613 static_cast<int>(
3614 CookieNetworkSecurity::k1pExpiringHSTSSubdomainsIncluded) |
3615 static_cast<int>(!same_site),
3616 2);
3617 }
3618}
3619
3620// Domain cookie with HSTS subdomains not included --> k1pHSTSSpoofable
3621TEST_P(URLRequestTestParameterizedSameSite,
3622 CookieNetworkSecurityMetricSpoofableDomainCookie) {
3623 const bool same_site = GetParam();
3624 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3625
3626 TransportSecurityState transport_security_state;
3627 transport_security_state.AddHSTS(
3628 kHost_, base::Time::Now() + base::TimeDelta::FromHours(10),
3629 false /* include_subdomains */);
3630 context_.set_transport_security_state(&transport_security_state);
3631 InitContext();
3632
3633 // Set cookie.
3634 {
3635 TestDelegate d;
3636 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3637 https_server_.GetURL(kHost_, "/set-cookie?cookie=value;domain=" +
3638 kHost_ + ";Max-Age=3600"),
3639 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3640 req->Start();
3641 base::RunLoop().Run();
3642 ASSERT_EQ(1, network_delegate_.set_cookie_count());
3643 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3644 }
3645
3646 // Verify that the cookie falls into the correct metrics bucket.
3647 {
3648 TestDelegate d;
3649 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3650 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3651 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3652 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3653 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3654 req->Start();
3655 base::RunLoop().Run();
3656 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 1);
3657 // Static cast of boolean required for MSVC 1911.
3658 histograms_.ExpectBucketCount(
3659 "Cookie.NetworkSecurity",
3660 static_cast<int>(CookieNetworkSecurity::k1pHSTSSpoofable) |
3661 static_cast<int>(!same_site),
3662 1);
3663 }
3664}
3665
3666// Cookie without HSTS --> k1p(Non)SecureConnection
3667TEST_P(URLRequestTestParameterizedSameSite, CookieNetworkSecurityMetricNoHSTS) {
3668 const bool same_site = GetParam();
3669 const std::string kInitiatingHost = same_site ? kHost_ : kCrossHost_;
3670 InitContext();
3671
3672 EmbeddedTestServer http_server;
3673 http_server.AddDefaultHandlers(
3674 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3675 ASSERT_TRUE(http_server.Start());
3676
3677 // Set cookies.
3678 {
3679 TestDelegate d;
3680 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3681 https_server_.GetURL(kHost_,
3682 "/set-cookie?cookie=value;domain=" + kHost_ +
3683 ";Max-Age=3600&host-cookie=value"),
3684 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3685 req->Start();
3686 base::RunLoop().Run();
3687 ASSERT_EQ(2, network_delegate_.set_cookie_count());
3688 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 0);
3689 }
3690
3691 // Verify that the cookie falls into the correct metrics bucket.
3692 {
3693 TestDelegate d;
3694 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3695 https_server_.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY,
3696 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
3697 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3698 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3699 req->Start();
3700 base::RunLoop().Run();
3701 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 2);
3702 // Static cast of boolean required for MSVC 1911.
3703 histograms_.ExpectBucketCount(
3704 "Cookie.NetworkSecurity",
3705 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3706 static_cast<int>(!same_site),
3707 2);
3708 }
3709
3710 // Verify that the cookie falls into the correct metrics bucket.
3711 {
3712 TestDelegate d;
3713 std::unique_ptr<URLRequest> req(context_.CreateRequest(
3714 http_server.GetURL(kHost_, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3715 TRAFFIC_ANNOTATION_FOR_TESTS));
3716 req->set_site_for_cookies(https_server_.GetURL(kInitiatingHost, "/"));
3717 req->set_initiator(url::Origin::Create(https_server_.GetURL(kHost_, "/")));
3718 req->Start();
3719 base::RunLoop().Run();
3720 histograms_.ExpectTotalCount("Cookie.NetworkSecurity", 4);
3721 // Static cast of boolean required for MSVC 1911.
3722 histograms_.ExpectBucketCount(
3723 "Cookie.NetworkSecurity",
3724 static_cast<int>(CookieNetworkSecurity::k1pSecureConnection) |
3725 static_cast<int>(!same_site),
3726 2);
3727 // Static cast of boolean required for MSVC 1911.
3728 histograms_.ExpectBucketCount(
3729 "Cookie.NetworkSecurity",
3730 static_cast<int>(CookieNetworkSecurity::k1pNonsecureConnection) |
3731 static_cast<int>(!same_site),
3732 2);
Mike West86149882017-07-28 10:41:493733 }
3734}
3735
mmenkefb18c772015-09-30 22:22:503736// Tests that a request is cancelled while entering suspend mode. Uses mocks
3737// rather than a spawned test server because the connection used to talk to
3738// the test server is affected by entering suspend mode on Android.
3739TEST_F(URLRequestTest, CancelOnSuspend) {
3740 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363741 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503742
3743 URLRequestFailedJob::AddUrlHandler();
3744
3745 TestDelegate d;
3746 // Request that just hangs.
3747 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
rhalavatib7bd7c792017-04-27 05:25:163748 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3749 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503750 r->Start();
3751
3752 power_monitor_source->Suspend();
3753 // Wait for the suspend notification to cause the request to fail.
3754 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503755 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503756 EXPECT_TRUE(d.request_failed());
3757 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3758
3759 URLRequestFilter::GetInstance()->ClearHandlers();
3760
3761 // Shouldn't be needed, but just in case.
3762 power_monitor_source->Resume();
3763}
3764
[email protected]5095cd72012-11-01 10:29:163765// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3766// value for the |fixed_date| argument given to the constructor.
3767class FixedDateNetworkDelegate : public TestNetworkDelegate {
3768 public:
3769 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3770 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273771 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163772
[email protected]cba24642014-08-15 20:49:593773 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203774 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593775 URLRequest* request,
3776 const CompletionCallback& callback,
3777 const HttpResponseHeaders* original_response_headers,
3778 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133779 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163780
3781 private:
3782 std::string fixed_date_;
3783
3784 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3785};
3786
3787int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593788 URLRequest* request,
3789 const CompletionCallback& callback,
3790 const HttpResponseHeaders* original_response_headers,
3791 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163792 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593793 HttpResponseHeaders* new_response_headers =
3794 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163795
3796 new_response_headers->RemoveHeader("Date");
3797 new_response_headers->AddHeader("Date: " + fixed_date_);
3798
3799 *override_response_headers = new_response_headers;
3800 return TestNetworkDelegate::OnHeadersReceived(request,
3801 callback,
3802 original_response_headers,
[email protected]5f714132014-03-26 10:41:163803 override_response_headers,
3804 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163805}
3806
3807// Test that cookie expiration times are adjusted for server/client clock
3808// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3809// headers by defaulting to GMT. (crbug.com/135131)
3810TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393811 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163812 ASSERT_TRUE(test_server.Start());
3813
3814 // Set up an expired cookie.
3815 {
3816 TestNetworkDelegate network_delegate;
3817 default_context_.set_network_delegate(&network_delegate);
3818 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363819 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193820 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553821 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163822 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193823 req->Start();
[email protected]255620da2013-08-19 13:14:293824 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163825 }
3826 // Verify that the cookie is not set.
3827 {
3828 TestNetworkDelegate network_delegate;
3829 default_context_.set_network_delegate(&network_delegate);
3830 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363831 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163832 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3833 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193834 req->Start();
[email protected]255620da2013-08-19 13:14:293835 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163836
3837 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3838 }
3839 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3840 {
3841 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3842 default_context_.set_network_delegate(&network_delegate);
3843 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363844 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193845 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553846 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163847 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193848 req->Start();
[email protected]255620da2013-08-19 13:14:293849 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163850 }
3851 // Verify that the cookie is set.
3852 {
3853 TestNetworkDelegate network_delegate;
3854 default_context_.set_network_delegate(&network_delegate);
3855 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363856 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163857 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3858 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193859 req->Start();
[email protected]255620da2013-08-19 13:14:293860 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163861
3862 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3863 }
3864}
3865
3866
[email protected]316c1e5e2012-09-12 15:17:443867// Check that it is impossible to change the referrer in the extra headers of
3868// an URLRequest.
3869TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:393870 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443871 ASSERT_TRUE(test_server.Start());
3872
3873 // If extra headers contain referer and the request contains a referer,
3874 // only the latter shall be respected.
3875 {
3876 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363877 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163878 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3879 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193880 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443881
3882 HttpRequestHeaders headers;
3883 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193884 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443885
[email protected]f7022f32014-08-21 16:32:193886 req->Start();
[email protected]255620da2013-08-19 13:14:293887 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443888
3889 EXPECT_EQ("http://foo.com/", d.data_received());
3890 }
3891
3892 // If extra headers contain a referer but the request does not, no referer
3893 // shall be sent in the header.
3894 {
3895 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363896 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163897 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3898 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443899
3900 HttpRequestHeaders headers;
3901 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193902 req->SetExtraRequestHeaders(headers);
3903 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443904
[email protected]f7022f32014-08-21 16:32:193905 req->Start();
[email protected]255620da2013-08-19 13:14:293906 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443907
3908 EXPECT_EQ("None", d.data_received());
3909 }
3910}
3911
[email protected]b89290212009-08-14 22:37:353912class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113913 public:
mmenke9f2ec60c2015-06-01 20:59:473914 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113915
[email protected]b89290212009-08-14 22:37:353916 protected:
[email protected]21184962011-10-26 00:50:303917 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3918 // |request_method| is the method to use for the initial request.
3919 // |redirect_method| is the method that is expected to be used for the second
3920 // request, after redirection.
3921 // If |include_data| is true, data is uploaded with the request. The
3922 // response body is expected to match it exactly, if and only if
3923 // |request_method| == |redirect_method|.
3924 void HTTPRedirectMethodTest(const GURL& redirect_url,
3925 const std::string& request_method,
3926 const std::string& redirect_method,
3927 bool include_data) {
3928 static const char kData[] = "hello world";
3929 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163930 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3931 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193932 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303933 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073934 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303935 HttpRequestHeaders headers;
3936 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:323937 base::NumberToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543938 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193939 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303940 }
[email protected]f7022f32014-08-21 16:32:193941 req->Start();
[email protected]255620da2013-08-19 13:14:293942 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193943 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503944 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303945 if (include_data) {
3946 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543947 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3948 HttpRequestHeaders::kContentLength));
3949 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3950 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303951 EXPECT_EQ(kData, d.data_received());
3952 } else {
svaldez5b3a8972015-10-09 23:23:543953 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3954 HttpRequestHeaders::kContentLength));
3955 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3956 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303957 EXPECT_NE(kData, d.data_received());
3958 }
3959 }
3960 if (HasFailure())
3961 LOG(WARNING) << "Request method was: " << request_method;
3962 }
3963
Alex Clarke1e08882b32017-10-06 14:22:403964 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
3965 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:513966 // |request_method| is the method to use for the initial request.
3967 // |redirect_method| is the method that is expected to be used for the second
3968 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:403969 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:513970 // redirection. If empty, expects that there will be no Origin header.
3971 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3972 const std::string& request_method,
3973 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:403974 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:513975 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163976 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3977 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:513978 req->set_method(request_method);
3979 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3980 redirect_url.GetOrigin().spec(), false);
3981 req->Start();
3982
3983 base::RunLoop().Run();
3984
3985 EXPECT_EQ(redirect_method, req->method());
3986 // Note that there is no check for request success here because, for
3987 // purposes of testing, the request very well may fail. For example, if the
3988 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3989 // origin, there is not an HTTPS server in this unit test framework, so the
3990 // request would fail. However, that's fine, as long as the request headers
3991 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:403992 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:513993 EXPECT_FALSE(
3994 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3995 } else {
3996 std::string origin_header;
3997 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3998 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:403999 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:514000 }
4001 }
4002
[email protected]762d2db2010-01-11 19:03:014003 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:014004 const int kMsgSize = 20000; // multiple of 10
4005 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:484006 char* uploadBytes = new char[kMsgSize+1];
4007 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:014008 char marker = 'a';
4009 for (int idx = 0; idx < kMsgSize/10; idx++) {
4010 memcpy(ptr, "----------", 10);
4011 ptr += 10;
4012 if (idx % 100 == 0) {
4013 ptr--;
4014 *ptr++ = marker;
4015 if (++marker > 'z')
4016 marker = 'a';
4017 }
4018 }
4019 uploadBytes[kMsgSize] = '\0';
4020
[email protected]762d2db2010-01-11 19:03:014021 for (int i = 0; i < kIterations; ++i) {
4022 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364023 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164024 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
4025 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194026 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:014027
mmenkecbc2b712014-10-09 20:29:074028 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:014029
[email protected]f7022f32014-08-21 16:32:194030 r->Start();
4031 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:014032
[email protected]255620da2013-08-19 13:14:294033 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:014034
maksim.sisovb53724b52016-09-16 05:30:504035 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
4036 << d.request_status();
[email protected]762d2db2010-01-11 19:03:014037
4038 EXPECT_FALSE(d.received_data_before_response());
4039 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:014040 }
4041 delete[] uploadBytes;
4042 }
4043
[email protected]ede03212012-09-07 12:52:264044 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:344045 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364046 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554047 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:364048 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:164049 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:344050
[email protected]f7022f32014-08-21 16:32:194051 r->Start();
4052 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:344053
[email protected]255620da2013-08-19 13:14:294054 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:344055
maksim.sisovb53724b52016-09-16 05:30:504056 if (d.request_status() != OK) {
4057 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
4058 return false;
4059 }
[email protected]263163f2012-06-14 22:40:344060
maksim.sisovb53724b52016-09-16 05:30:504061 return true;
[email protected]263163f2012-06-14 22:40:344062 }
4063
David Benjamin42116f62017-11-20 21:45:394064 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:504065
tommycli59a63432015-11-06 00:10:554066 private:
David Benjamin42116f62017-11-20 21:45:394067 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:354068};
4069
tommycli59a63432015-11-06 00:10:554070namespace {
4071
danakj8522a25b2016-04-16 00:17:364072std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:554073 const test_server::HttpRequest& request) {
4074 if (request.headers.find("Host") == request.headers.end() ||
4075 request.headers.at("Host") != "www.redirect.com" ||
4076 request.method != test_server::METHOD_CONNECT) {
4077 return nullptr;
4078 }
4079
danakj8522a25b2016-04-16 00:17:364080 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554081 new test_server::BasicHttpResponse);
4082 http_response->set_code(HTTP_FOUND);
4083 http_response->AddCustomHeader("Location",
4084 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:484085 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554086}
4087
4088} // namespace
4089
nharperb7441ef2016-01-25 23:54:144090class TestSSLConfigService : public SSLConfigService {
4091 public:
Ryan Sleevi5b4702a2018-04-06 22:23:564092 TestSSLConfigService(bool online_rev_checking,
nharperb7441ef2016-01-25 23:54:144093 bool rev_checking_required_local_anchors,
4094 bool token_binding_enabled)
Ryan Sleevi5b4702a2018-04-06 22:23:564095 : online_rev_checking_(online_rev_checking),
nharperb7441ef2016-01-25 23:54:144096 rev_checking_required_local_anchors_(
4097 rev_checking_required_local_anchors),
4098 token_binding_enabled_(token_binding_enabled),
davidben095ebb52017-04-12 22:23:344099 min_version_(kDefaultSSLVersionMin),
4100 max_version_(kDefaultSSLVersionMax) {}
nharperb7441ef2016-01-25 23:54:144101
davidben095ebb52017-04-12 22:23:344102 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:144103 void set_min_version(uint16_t version) { min_version_ = version; }
4104
nharperb7441ef2016-01-25 23:54:144105 // SSLConfigService:
4106 void GetSSLConfig(SSLConfig* config) override {
4107 *config = SSLConfig();
4108 config->rev_checking_enabled = online_rev_checking_;
nharperb7441ef2016-01-25 23:54:144109 config->rev_checking_required_local_anchors =
4110 rev_checking_required_local_anchors_;
davidben095ebb52017-04-12 22:23:344111 config->version_min = min_version_;
4112 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:144113 if (token_binding_enabled_) {
4114 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
4115 }
4116 }
4117
4118 protected:
Chris Watkins7a41d3552017-12-01 02:13:274119 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:144120
4121 private:
nharperb7441ef2016-01-25 23:54:144122 const bool online_rev_checking_;
4123 const bool rev_checking_required_local_anchors_;
4124 const bool token_binding_enabled_;
4125 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:344126 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:144127};
4128
4129// TODO(svaldez): Update tests to use EmbeddedTestServer.
4130#if !defined(OS_IOS)
4131class TokenBindingURLRequestTest : public URLRequestTestHTTP {
4132 public:
fdoray9f0b4782017-02-10 12:55:474133 TokenBindingURLRequestTest() = default;
fdoraya89e673c2017-01-31 21:44:214134
nharperb7441ef2016-01-25 23:54:144135 void SetUp() override {
4136 default_context_.set_ssl_config_service(
Ryan Sleevi5b4702a2018-04-06 22:23:564137 new TestSSLConfigService(false, false, true));
fdoraya89e673c2017-01-31 21:44:214138 channel_id_service_.reset(
4139 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:144140 default_context_.set_channel_id_service(channel_id_service_.get());
4141 URLRequestTestHTTP::SetUp();
4142 }
4143
4144 protected:
danakj8522a25b2016-04-16 00:17:364145 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:144146};
4147
4148TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
4149 SpawnedTestServer::SSLOptions ssl_options;
4150 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4151 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4152 ssl_options,
4153 base::FilePath(kTestFilePath));
4154 ASSERT_TRUE(https_test_server.Start());
4155
4156 TestDelegate d;
4157 {
danakj8522a25b2016-04-16 00:17:364158 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164159 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d,
4160 TRAFFIC_ANNOTATION_FOR_TESTS));
nharperb7441ef2016-01-25 23:54:144161 r->Start();
4162 EXPECT_TRUE(r->is_pending());
4163
4164 base::RunLoop().Run();
4165
maksim.sisovb53724b52016-09-16 05:30:504166 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:144167
4168 HttpRequestHeaders headers;
4169 std::string token_binding_header, token_binding_message;
4170 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4171 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4172 &token_binding_header));
4173 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354174 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:144175 &token_binding_message));
nharperd6e65822016-03-30 23:05:484176 std::vector<TokenBinding> token_bindings;
4177 ASSERT_TRUE(
4178 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4179 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:144180
4181 EXPECT_GT(d.bytes_received(), 0);
4182 std::string ekm = d.data_received();
4183
nharperd6e65822016-03-30 23:05:484184 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354185 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4186 token_bindings[0].signature,
4187 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:144188 }
4189}
nharperd6e65822016-03-30 23:05:484190
4191TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
4192 SpawnedTestServer::SSLOptions ssl_options;
4193 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4194 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4195 ssl_options,
4196 base::FilePath(kTestFilePath));
4197 ASSERT_TRUE(https_test_server.Start());
4198
4199 TestDelegate d;
4200 {
4201 GURL redirect_url =
4202 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
rhalavatib7bd7c792017-04-27 05:25:164203 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4204 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484205 r->Start();
4206 EXPECT_TRUE(r->is_pending());
4207
4208 base::RunLoop().Run();
4209
maksim.sisovb53724b52016-09-16 05:30:504210 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484211
4212 HttpRequestHeaders headers;
4213 std::string token_binding_header, token_binding_message;
4214 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4215 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4216 &token_binding_header));
4217 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354218 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:484219 &token_binding_message));
4220 std::vector<TokenBinding> token_bindings;
4221 ASSERT_TRUE(
4222 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4223 ASSERT_EQ(2ull, token_bindings.size());
4224
4225 EXPECT_GT(d.bytes_received(), 0);
4226 std::string ekm = d.data_received();
4227
4228 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354229 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4230 token_bindings[0].signature,
4231 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:484232 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:354233 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
4234 token_bindings[1].signature,
4235 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:484236 }
4237}
4238
4239// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
4240// EmbeddedTestServer once crbug.com/599187 is resolved.
4241#if !defined(OS_ANDROID)
4242TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
Sergey Ulanov9e8d6f32017-08-14 22:12:584243 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP, base::FilePath());
nharperd6e65822016-03-30 23:05:484244 ASSERT_TRUE(http_server.Start());
4245 SpawnedTestServer::SSLOptions ssl_options;
4246 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4247 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4248 ssl_options,
4249 base::FilePath(kTestFilePath));
4250 ASSERT_TRUE(https_test_server.Start());
4251
4252 TestDelegate d;
4253 {
4254 GURL redirect_url = http_server.GetURL(
4255 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:164256 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4257 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484258 r->Start();
4259 EXPECT_TRUE(r->is_pending());
4260
4261 base::RunLoop().Run();
4262
maksim.sisovb53724b52016-09-16 05:30:504263 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484264
4265 HttpRequestHeaders headers;
4266 std::string token_binding_header, token_binding_message;
4267 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4268 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4269 &token_binding_header));
4270 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:354271 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:484272 &token_binding_message));
4273 std::vector<TokenBinding> token_bindings;
4274 ASSERT_TRUE(
4275 ParseTokenBindingMessage(token_binding_message, &token_bindings));
4276 ASSERT_EQ(1ull, token_bindings.size());
4277
4278 EXPECT_GT(d.bytes_received(), 0);
4279 std::string ekm = d.data_received();
4280
4281 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:354282 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
4283 token_bindings[0].signature,
4284 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:484285 }
4286}
4287
4288// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:364289// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:484290// support Token Binding, then we do not send a Sec-Token-Binding when following
4291// the redirect.
4292TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
4293 SpawnedTestServer::SSLOptions ssl_options;
4294 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
4295 ssl_options,
4296 base::FilePath(kTestFilePath));
4297 ASSERT_TRUE(https_test_server.Start());
4298 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
4299 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
4300 ssl_options,
4301 base::FilePath(kTestFilePath));
4302 ASSERT_TRUE(token_binding_test_server.Start());
4303
4304 TestDelegate d;
4305 {
4306 GURL redirect_url = token_binding_test_server.GetURL(
4307 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:164308 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4309 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:484310 r->Start();
4311 EXPECT_TRUE(r->is_pending());
4312
4313 base::RunLoop().Run();
4314
maksim.sisovb53724b52016-09-16 05:30:504315 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:484316
4317 HttpRequestHeaders headers;
4318 std::string token_binding_header, token_binding_message;
4319 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
4320 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
4321 &token_binding_header));
4322 }
4323}
4324#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:144325#endif // !defined(OS_IOS)
4326
4327// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114328// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:554329// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:114330// follow.
[email protected]f2f31b32013-01-16 23:24:094331TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:554332 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124333 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:554334 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114335
[email protected]ceefd7fd2012-11-29 00:36:244336 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044337 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554338 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504339
[email protected]d1ec59082009-02-11 02:48:154340 TestDelegate d;
4341 {
danakj8522a25b2016-04-16 00:17:364342 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164343 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4344 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194345 r->Start();
4346 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:154347
[email protected]255620da2013-08-19 13:14:294348 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:154349
[email protected]d8fc4722014-06-13 13:17:154350 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474351 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504352 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084353 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:154354 // We should not have followed the redirect.
4355 EXPECT_EQ(0, d.received_redirect_count());
4356 }
4357}
4358
[email protected]8202d0c2011-02-23 08:31:144359// This is the same as the previous test, but checks that the network delegate
4360// registers the error.
[email protected]c044616e2013-02-20 02:01:264361TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554362 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144363
[email protected]ceefd7fd2012-11-29 00:36:244364 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044365 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554366 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504367
[email protected]8202d0c2011-02-23 08:31:144368 TestDelegate d;
4369 {
danakj8522a25b2016-04-16 00:17:364370 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164371 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4372 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194373 r->Start();
4374 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144375
[email protected]255620da2013-08-19 13:14:294376 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:144377
[email protected]d8fc4722014-06-13 13:17:154378 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474379 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144380 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504381 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144382 // We should not have followed the redirect.
4383 EXPECT_EQ(0, d.received_redirect_count());
4384
4385 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014386 EXPECT_THAT(network_delegate.last_error(),
4387 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144388 }
4389}
4390
[email protected]dc5a5cf2012-09-26 02:49:304391// Tests that we can block and asynchronously return OK in various stages.
4392TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4393 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4394 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4395 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4396 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4397 };
4398 static const size_t blocking_stages_length = arraysize(blocking_stages);
4399
tommycli59a63432015-11-06 00:10:554400 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304401
4402 TestDelegate d;
4403 BlockingNetworkDelegate network_delegate(
4404 BlockingNetworkDelegate::USER_CALLBACK);
4405 network_delegate.set_block_on(
4406 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4407 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4408 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4409
4410 TestURLRequestContext context(true);
4411 context.set_network_delegate(&network_delegate);
4412 context.Init();
4413
4414 {
danakj8522a25b2016-04-16 00:17:364415 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164416 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4417 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304418
[email protected]f7022f32014-08-21 16:32:194419 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304420 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:294421 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304422 EXPECT_EQ(blocking_stages[i],
4423 network_delegate.stage_blocked_for_callback());
4424 network_delegate.DoCallback(OK);
4425 }
[email protected]255620da2013-08-19 13:14:294426 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194427 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504428 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304429 EXPECT_EQ(1, network_delegate.created_requests());
4430 EXPECT_EQ(0, network_delegate.destroyed_requests());
4431 }
4432 EXPECT_EQ(1, network_delegate.destroyed_requests());
4433}
4434
[email protected]4c76d7c2011-04-15 19:14:124435// Tests that the network delegate can block and cancel a request.
4436TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554437 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124438
4439 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304440 BlockingNetworkDelegate network_delegate(
4441 BlockingNetworkDelegate::AUTO_CALLBACK);
4442 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4443 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124444
[email protected]d5a4dd62012-05-23 01:41:044445 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554446 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504447
[email protected]4c76d7c2011-04-15 19:14:124448 {
rhalavatib7bd7c792017-04-27 05:25:164449 std::unique_ptr<URLRequest> r(
4450 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4451 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124452
[email protected]f7022f32014-08-21 16:32:194453 r->Start();
[email protected]255620da2013-08-19 13:14:294454 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124455
[email protected]d8fc4722014-06-13 13:17:154456 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474457 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504458 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124459 EXPECT_EQ(1, network_delegate.created_requests());
4460 EXPECT_EQ(0, network_delegate.destroyed_requests());
4461 }
4462 EXPECT_EQ(1, network_delegate.destroyed_requests());
4463}
4464
[email protected]b4438d32012-09-27 06:15:304465// Helper function for NetworkDelegateCancelRequestAsynchronously and
4466// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4467// delegate operating in |block_mode| and a request for |url|. It blocks the
4468// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4469void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4470 BlockingNetworkDelegate::Stage stage,
4471 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364472 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304473 BlockingNetworkDelegate network_delegate(block_mode);
4474 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4475 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364476
[email protected]b4438d32012-09-27 06:15:304477 TestURLRequestContext context(true);
4478 context.set_network_delegate(&network_delegate);
4479 context.Init();
[email protected]3cd384c602011-08-31 16:12:364480
4481 {
rhalavatib7bd7c792017-04-27 05:25:164482 std::unique_ptr<URLRequest> r(context.CreateRequest(
4483 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364484
[email protected]f7022f32014-08-21 16:32:194485 r->Start();
[email protected]255620da2013-08-19 13:14:294486 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:364487
[email protected]d8fc4722014-06-13 13:17:154488 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474489 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4490 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4491 EXPECT_FALSE(r->proxy_server().is_valid());
4492 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4493 EXPECT_TRUE(r->proxy_server().is_direct());
4494 } else {
4495 NOTREACHED();
4496 }
maksim.sisovb53724b52016-09-16 05:30:504497 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364498 EXPECT_EQ(1, network_delegate.created_requests());
4499 EXPECT_EQ(0, network_delegate.destroyed_requests());
4500 }
4501 EXPECT_EQ(1, network_delegate.destroyed_requests());
4502}
4503
[email protected]b4438d32012-09-27 06:15:304504// The following 3 tests check that the network delegate can cancel a request
4505// synchronously in various stages of the request.
4506TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554507 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304508 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4509 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554510 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304511}
4512
4513TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554514 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304515 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4516 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554517 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304518}
4519
4520TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554521 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304522 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4523 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554524 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304525}
4526
4527// The following 3 tests check that the network delegate can cancel a request
4528// asynchronously in various stages of the request.
4529TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554530 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304531 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4532 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554533 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304534}
4535
4536TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554537 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304538 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4539 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554540 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304541}
4542
4543TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554544 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304545 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4546 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554547 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304548}
4549
[email protected]4c76d7c2011-04-15 19:14:124550// Tests that the network delegate can block and redirect a request to a new
4551// URL.
4552TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554553 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124554
4555 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304556 BlockingNetworkDelegate network_delegate(
4557 BlockingNetworkDelegate::AUTO_CALLBACK);
4558 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554559 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:124560 network_delegate.set_redirect_url(redirect_url);
4561
[email protected]d5a4dd62012-05-23 01:41:044562 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554563 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504564
[email protected]4c76d7c2011-04-15 19:14:124565 {
tommycli59a63432015-11-06 00:10:554566 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164567 std::unique_ptr<URLRequest> r(context.CreateRequest(
4568 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124569
[email protected]6be6fa92014-08-06 23:44:564570 // Quit after hitting the redirect, so can check the headers.
4571 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194572 r->Start();
[email protected]255620da2013-08-19 13:14:294573 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124574
[email protected]6be6fa92014-08-06 23:44:564575 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194576 EXPECT_EQ(307, r->GetResponseCode());
4577 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564578 std::string location;
[email protected]f7022f32014-08-21 16:32:194579 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4580 &location));
[email protected]6be6fa92014-08-06 23:44:564581 EXPECT_EQ(redirect_url, GURL(location));
4582
4583 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194584 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564585 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:504586 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474587 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4588 http_test_server()->host_port_pair()),
4589 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094590 // before_send_headers_with_proxy_count only increments for headers sent
4591 // through an untunneled proxy.
4592 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554593 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4594 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274595
maksim.sisovb53724b52016-09-16 05:30:504596 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194597 EXPECT_EQ(redirect_url, r->url());
4598 EXPECT_EQ(original_url, r->original_url());
4599 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124600 EXPECT_EQ(1, network_delegate.created_requests());
4601 EXPECT_EQ(0, network_delegate.destroyed_requests());
4602 }
4603 EXPECT_EQ(1, network_delegate.destroyed_requests());
4604}
4605
[email protected]b813ed72012-04-05 08:21:364606// Tests that the network delegate can block and redirect a request to a new
4607// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4608TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554609 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364610
4611 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304612 BlockingNetworkDelegate network_delegate(
4613 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:554614 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:364615 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364616
[email protected]d5a4dd62012-05-23 01:41:044617 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554618 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364619
4620 {
tommycli59a63432015-11-06 00:10:554621 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164622 std::unique_ptr<URLRequest> r(context.CreateRequest(
4623 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364624
[email protected]6be6fa92014-08-06 23:44:564625 // Quit after hitting the redirect, so can check the headers.
4626 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194627 r->Start();
[email protected]255620da2013-08-19 13:14:294628 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:364629
[email protected]6be6fa92014-08-06 23:44:564630 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194631 EXPECT_EQ(307, r->GetResponseCode());
4632 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564633 std::string location;
[email protected]f7022f32014-08-21 16:32:194634 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4635 &location));
[email protected]6be6fa92014-08-06 23:44:564636 EXPECT_EQ(redirect_url, GURL(location));
4637
4638 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194639 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564640 base::RunLoop().Run();
4641
maksim.sisovb53724b52016-09-16 05:30:504642 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474643 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4644 http_test_server()->host_port_pair()),
4645 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094646 // before_send_headers_with_proxy_count only increments for headers sent
4647 // through an untunneled proxy.
4648 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554649 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4650 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504651 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194652 EXPECT_EQ(redirect_url, r->url());
4653 EXPECT_EQ(original_url, r->original_url());
4654 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364655 EXPECT_EQ(1, network_delegate.created_requests());
4656 EXPECT_EQ(0, network_delegate.destroyed_requests());
4657 }
4658 EXPECT_EQ(1, network_delegate.destroyed_requests());
4659}
4660
[email protected]3c5ca8c2011-09-29 01:14:514661// Tests that redirects caused by the network delegate preserve POST data.
4662TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554663 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514664
4665 const char kData[] = "hello world";
4666
4667 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304668 BlockingNetworkDelegate network_delegate(
4669 BlockingNetworkDelegate::AUTO_CALLBACK);
4670 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554671 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514672 network_delegate.set_redirect_url(redirect_url);
4673
[email protected]ef2bf422012-05-11 03:27:094674 TestURLRequestContext context(true);
4675 context.set_network_delegate(&network_delegate);
4676 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514677
4678 {
tommycli59a63432015-11-06 00:10:554679 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164680 std::unique_ptr<URLRequest> r(context.CreateRequest(
4681 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194682 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074683 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514684 HttpRequestHeaders headers;
4685 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:324686 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194687 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564688
4689 // Quit after hitting the redirect, so can check the headers.
4690 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194691 r->Start();
[email protected]255620da2013-08-19 13:14:294692 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514693
[email protected]6be6fa92014-08-06 23:44:564694 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194695 EXPECT_EQ(307, r->GetResponseCode());
4696 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564697 std::string location;
[email protected]f7022f32014-08-21 16:32:194698 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4699 &location));
[email protected]6be6fa92014-08-06 23:44:564700 EXPECT_EQ(redirect_url, GURL(location));
4701
4702 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194703 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564704 base::RunLoop().Run();
4705
maksim.sisovb53724b52016-09-16 05:30:504706 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194707 EXPECT_EQ(redirect_url, r->url());
4708 EXPECT_EQ(original_url, r->original_url());
4709 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514710 EXPECT_EQ(1, network_delegate.created_requests());
4711 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194712 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514713 EXPECT_EQ(kData, d.data_received());
4714 }
4715 EXPECT_EQ(1, network_delegate.destroyed_requests());
4716}
4717
[email protected]5f714132014-03-26 10:41:164718// Tests that the network delegate can block and redirect a request to a new
4719// URL during OnHeadersReceived.
4720TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554721 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164722
4723 TestDelegate d;
4724 BlockingNetworkDelegate network_delegate(
4725 BlockingNetworkDelegate::AUTO_CALLBACK);
4726 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554727 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164728 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4729
4730 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554731 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164732
4733 {
tommycli59a63432015-11-06 00:10:554734 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164735 std::unique_ptr<URLRequest> r(context.CreateRequest(
4736 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164737
[email protected]f7022f32014-08-21 16:32:194738 r->Start();
[email protected]5f714132014-03-26 10:41:164739 base::RunLoop().Run();
4740
maksim.sisovb53724b52016-09-16 05:30:504741 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474742 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4743 http_test_server()->host_port_pair()),
4744 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094745 // before_send_headers_with_proxy_count only increments for headers sent
4746 // through an untunneled proxy.
4747 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554748 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4749 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194750
maksim.sisovb53724b52016-09-16 05:30:504751 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194752 EXPECT_EQ(redirect_url, r->url());
4753 EXPECT_EQ(original_url, r->original_url());
4754 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164755 EXPECT_EQ(2, network_delegate.created_requests());
4756 EXPECT_EQ(0, network_delegate.destroyed_requests());
4757 }
4758 EXPECT_EQ(1, network_delegate.destroyed_requests());
4759}
4760
[email protected]c2911d72011-10-03 22:16:364761// Tests that the network delegate can synchronously complete OnAuthRequired
4762// by taking no action. This indicates that the NetworkDelegate does not want to
4763// handle the challenge, and is passing the buck along to the
4764// URLRequest::Delegate.
4765TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554766 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364767
4768 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304769 BlockingNetworkDelegate network_delegate(
4770 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364771
[email protected]ef2bf422012-05-11 03:27:094772 TestURLRequestContext context(true);
4773 context.set_network_delegate(&network_delegate);
4774 context.Init();
[email protected]c2911d72011-10-03 22:16:364775
[email protected]f3cf9802011-10-28 18:44:584776 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364777
4778 {
tommycli59a63432015-11-06 00:10:554779 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164780 std::unique_ptr<URLRequest> r(context.CreateRequest(
4781 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194782 r->Start();
[email protected]79e1fd62013-06-20 06:50:044783
[email protected]255620da2013-08-19 13:14:294784 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044785
maksim.sisovb53724b52016-09-16 05:30:504786 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194787 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044788 EXPECT_TRUE(d.auth_required_called());
4789 EXPECT_EQ(1, network_delegate.created_requests());
4790 EXPECT_EQ(0, network_delegate.destroyed_requests());
4791 }
4792 EXPECT_EQ(1, network_delegate.destroyed_requests());
4793}
4794
4795TEST_F(URLRequestTestHTTP,
4796 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554797 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044798
4799 TestDelegate d;
4800 BlockingNetworkDelegate network_delegate(
4801 BlockingNetworkDelegate::SYNCHRONOUS);
4802
4803 TestURLRequestContext context(true);
4804 context.set_network_delegate(&network_delegate);
4805 context.Init();
4806
4807 d.set_credentials(AuthCredentials(kUser, kSecret));
4808
4809 {
tommycli59a63432015-11-06 00:10:554810 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164811 std::unique_ptr<URLRequest> r(context.CreateRequest(
4812 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194813 r->Start();
[email protected]79e1fd62013-06-20 06:50:044814
shivanisha8061c4202017-06-13 23:35:524815 base::RunLoop().Run();
4816
[email protected]79e1fd62013-06-20 06:50:044817 {
4818 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194819 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524820 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044821 }
4822
maksim.sisovb53724b52016-09-16 05:30:504823 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194824 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364825 EXPECT_TRUE(d.auth_required_called());
4826 EXPECT_EQ(1, network_delegate.created_requests());
4827 EXPECT_EQ(0, network_delegate.destroyed_requests());
4828 }
4829 EXPECT_EQ(1, network_delegate.destroyed_requests());
4830}
4831
4832// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404833// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364834TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554835 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364836
4837 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304838 BlockingNetworkDelegate network_delegate(
4839 BlockingNetworkDelegate::SYNCHRONOUS);
4840 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364841 network_delegate.set_auth_retval(
4842 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4843
[email protected]f3cf9802011-10-28 18:44:584844 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364845
[email protected]ef2bf422012-05-11 03:27:094846 TestURLRequestContext context(true);
4847 context.set_network_delegate(&network_delegate);
4848 context.Init();
[email protected]c2911d72011-10-03 22:16:364849
4850 {
tommycli59a63432015-11-06 00:10:554851 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164852 std::unique_ptr<URLRequest> r(context.CreateRequest(
4853 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194854 r->Start();
[email protected]255620da2013-08-19 13:14:294855 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364856
maksim.sisovb53724b52016-09-16 05:30:504857 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194858 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364859 EXPECT_FALSE(d.auth_required_called());
4860 EXPECT_EQ(1, network_delegate.created_requests());
4861 EXPECT_EQ(0, network_delegate.destroyed_requests());
4862 }
4863 EXPECT_EQ(1, network_delegate.destroyed_requests());
4864}
4865
[email protected]79e1fd62013-06-20 06:50:044866// Same as above, but also tests that GetFullRequestHeaders returns the proper
4867// headers (for the first or second request) when called at the proper times.
4868TEST_F(URLRequestTestHTTP,
4869 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554870 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044871
4872 TestDelegate d;
4873 BlockingNetworkDelegate network_delegate(
4874 BlockingNetworkDelegate::SYNCHRONOUS);
4875 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4876 network_delegate.set_auth_retval(
4877 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4878
4879 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4880
4881 TestURLRequestContext context(true);
4882 context.set_network_delegate(&network_delegate);
4883 context.Init();
4884
4885 {
tommycli59a63432015-11-06 00:10:554886 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164887 std::unique_ptr<URLRequest> r(context.CreateRequest(
4888 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194889 r->Start();
[email protected]255620da2013-08-19 13:14:294890 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044891
maksim.sisovb53724b52016-09-16 05:30:504892 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194893 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044894 EXPECT_FALSE(d.auth_required_called());
4895 EXPECT_EQ(1, network_delegate.created_requests());
4896 EXPECT_EQ(0, network_delegate.destroyed_requests());
4897
4898 {
4899 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194900 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044901 EXPECT_TRUE(headers.HasHeader("Authorization"));
4902 }
4903 }
4904 EXPECT_EQ(1, network_delegate.destroyed_requests());
4905}
4906
[email protected]c2911d72011-10-03 22:16:364907// Tests that the network delegate can synchronously complete OnAuthRequired
4908// by cancelling authentication.
4909TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554910 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364911
4912 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304913 BlockingNetworkDelegate network_delegate(
4914 BlockingNetworkDelegate::SYNCHRONOUS);
4915 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364916 network_delegate.set_auth_retval(
4917 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4918
[email protected]ef2bf422012-05-11 03:27:094919 TestURLRequestContext context(true);
4920 context.set_network_delegate(&network_delegate);
4921 context.Init();
[email protected]c2911d72011-10-03 22:16:364922
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();
[email protected]255620da2013-08-19 13:14:294928 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364929
maksim.sisovb53724b52016-09-16 05:30:504930 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194931 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364932 EXPECT_FALSE(d.auth_required_called());
4933 EXPECT_EQ(1, network_delegate.created_requests());
4934 EXPECT_EQ(0, network_delegate.destroyed_requests());
4935 }
4936 EXPECT_EQ(1, network_delegate.destroyed_requests());
4937}
4938
4939// Tests that the network delegate can asynchronously complete OnAuthRequired
4940// by taking no action. This indicates that the NetworkDelegate does not want
4941// to handle the challenge, and is passing the buck along to the
4942// URLRequest::Delegate.
4943TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554944 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364945
4946 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304947 BlockingNetworkDelegate network_delegate(
4948 BlockingNetworkDelegate::AUTO_CALLBACK);
4949 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364950
[email protected]ef2bf422012-05-11 03:27:094951 TestURLRequestContext context(true);
4952 context.set_network_delegate(&network_delegate);
4953 context.Init();
[email protected]c2911d72011-10-03 22:16:364954
[email protected]f3cf9802011-10-28 18:44:584955 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364956
4957 {
tommycli59a63432015-11-06 00:10:554958 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164959 std::unique_ptr<URLRequest> r(context.CreateRequest(
4960 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194961 r->Start();
[email protected]255620da2013-08-19 13:14:294962 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364963
maksim.sisovb53724b52016-09-16 05:30:504964 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194965 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364966 EXPECT_TRUE(d.auth_required_called());
4967 EXPECT_EQ(1, network_delegate.created_requests());
4968 EXPECT_EQ(0, network_delegate.destroyed_requests());
4969 }
4970 EXPECT_EQ(1, network_delegate.destroyed_requests());
4971}
4972
4973// Tests that the network delegate can asynchronously complete OnAuthRequired
4974// by setting credentials.
4975TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554976 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364977
4978 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304979 BlockingNetworkDelegate network_delegate(
4980 BlockingNetworkDelegate::AUTO_CALLBACK);
4981 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364982 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364983 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4984
[email protected]f3cf9802011-10-28 18:44:584985 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364986 network_delegate.set_auth_credentials(auth_credentials);
4987
[email protected]ef2bf422012-05-11 03:27:094988 TestURLRequestContext context(true);
4989 context.set_network_delegate(&network_delegate);
4990 context.Init();
[email protected]c2911d72011-10-03 22:16:364991
4992 {
tommycli59a63432015-11-06 00:10:554993 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164994 std::unique_ptr<URLRequest> r(context.CreateRequest(
4995 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194996 r->Start();
[email protected]255620da2013-08-19 13:14:294997 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364998
maksim.sisovb53724b52016-09-16 05:30:504999 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195000 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365001 EXPECT_FALSE(d.auth_required_called());
5002 EXPECT_EQ(1, network_delegate.created_requests());
5003 EXPECT_EQ(0, network_delegate.destroyed_requests());
5004 }
5005 EXPECT_EQ(1, network_delegate.destroyed_requests());
5006}
5007
5008// Tests that the network delegate can asynchronously complete OnAuthRequired
5009// by cancelling authentication.
5010TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:555011 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:365012
5013 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305014 BlockingNetworkDelegate network_delegate(
5015 BlockingNetworkDelegate::AUTO_CALLBACK);
5016 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:365017 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:365018 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
5019
[email protected]ef2bf422012-05-11 03:27:095020 TestURLRequestContext context(true);
5021 context.set_network_delegate(&network_delegate);
5022 context.Init();
[email protected]c2911d72011-10-03 22:16:365023
5024 {
tommycli59a63432015-11-06 00:10:555025 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:165026 std::unique_ptr<URLRequest> r(context.CreateRequest(
5027 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195028 r->Start();
[email protected]255620da2013-08-19 13:14:295029 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:365030
maksim.sisovb53724b52016-09-16 05:30:505031 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:195032 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:365033 EXPECT_FALSE(d.auth_required_called());
5034 EXPECT_EQ(1, network_delegate.created_requests());
5035 EXPECT_EQ(0, network_delegate.destroyed_requests());
5036 }
5037 EXPECT_EQ(1, network_delegate.destroyed_requests());
5038}
5039
David Benjamin0bda12f2018-02-07 19:58:455040// Tests that NetworkDelegate header overrides from the 401 response do not
5041// affect the 200 response. This is a regression test for
5042// https://crbug.com/801237.
5043TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
5044 ASSERT_TRUE(http_test_server()->Start());
5045
5046 TestDelegate d;
5047 d.set_credentials(AuthCredentials(kUser, kSecret));
5048 default_network_delegate_.set_add_header_to_first_response(true);
5049
5050 {
5051 GURL url(http_test_server()->GetURL("/auth-basic"));
5052 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5053 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5054 r->Start();
5055
5056 base::RunLoop().Run();
5057
5058 EXPECT_EQ(OK, d.request_status());
5059 EXPECT_EQ(200, r->GetResponseCode());
5060 EXPECT_TRUE(d.auth_required_called());
5061 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
5062 }
5063
5064 {
5065 GURL url(http_test_server()->GetURL("/defaultresponse"));
5066 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5067 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
5068 r->Start();
5069
5070 base::RunLoop().Run();
5071
5072 // Check that set_add_header_to_first_response normally adds a header.
5073 EXPECT_EQ(OK, d.request_status());
5074 EXPECT_EQ(200, r->GetResponseCode());
5075 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
5076 }
5077}
5078
[email protected]9045b8822012-01-13 20:35:355079// Tests that we can handle when a network request was canceled while we were
5080// waiting for the network delegate.
5081// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
5082TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:555083 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355084
5085 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305086 BlockingNetworkDelegate network_delegate(
5087 BlockingNetworkDelegate::USER_CALLBACK);
5088 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:355089
[email protected]ef2bf422012-05-11 03:27:095090 TestURLRequestContext context(true);
5091 context.set_network_delegate(&network_delegate);
5092 context.Init();
[email protected]9045b8822012-01-13 20:35:355093
5094 {
rhalavatib7bd7c792017-04-27 05:25:165095 std::unique_ptr<URLRequest> r(
5096 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5097 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355098
[email protected]f7022f32014-08-21 16:32:195099 r->Start();
[email protected]255620da2013-08-19 13:14:295100 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:305101 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
5102 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355103 EXPECT_EQ(0, network_delegate.completed_requests());
5104 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195105 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355106 // Ensure that network delegate is notified.
5107 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505108 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355109 EXPECT_EQ(1, network_delegate.created_requests());
5110 EXPECT_EQ(0, network_delegate.destroyed_requests());
5111 }
5112 EXPECT_EQ(1, network_delegate.destroyed_requests());
5113}
5114
5115// Tests that we can handle when a network request was canceled while we were
5116// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:005117// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
5118// callback.
[email protected]9045b8822012-01-13 20:35:355119TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:555120 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355121
5122 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305123 BlockingNetworkDelegate network_delegate(
5124 BlockingNetworkDelegate::USER_CALLBACK);
5125 network_delegate.set_block_on(
5126 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[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();
[email protected]255620da2013-08-19 13:14:295138 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:305139 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
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.
5155// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
5156TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:555157 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355158
5159 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305160 BlockingNetworkDelegate network_delegate(
5161 BlockingNetworkDelegate::USER_CALLBACK);
5162 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:355163
[email protected]ef2bf422012-05-11 03:27:095164 TestURLRequestContext context(true);
5165 context.set_network_delegate(&network_delegate);
5166 context.Init();
[email protected]9045b8822012-01-13 20:35:355167
5168 {
rhalavatib7bd7c792017-04-27 05:25:165169 std::unique_ptr<URLRequest> r(
5170 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
5171 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355172
[email protected]f7022f32014-08-21 16:32:195173 r->Start();
[email protected]255620da2013-08-19 13:14:295174 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:305175 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
5176 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355177 EXPECT_EQ(0, network_delegate.completed_requests());
5178 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195179 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355180 // Ensure that network delegate is notified.
5181 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505182 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355183 EXPECT_EQ(1, network_delegate.created_requests());
5184 EXPECT_EQ(0, network_delegate.destroyed_requests());
5185 }
5186 EXPECT_EQ(1, network_delegate.destroyed_requests());
5187}
5188
5189// Tests that we can handle when a network request was canceled while we were
5190// waiting for the network delegate.
5191// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:025192TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:555193 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:355194
5195 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:305196 BlockingNetworkDelegate network_delegate(
5197 BlockingNetworkDelegate::USER_CALLBACK);
5198 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:355199
[email protected]ef2bf422012-05-11 03:27:095200 TestURLRequestContext context(true);
5201 context.set_network_delegate(&network_delegate);
5202 context.Init();
[email protected]9045b8822012-01-13 20:35:355203
5204 {
danakj8522a25b2016-04-16 00:17:365205 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165206 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
5207 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:355208
[email protected]f7022f32014-08-21 16:32:195209 r->Start();
[email protected]255620da2013-08-19 13:14:295210 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:305211 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
5212 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:355213 EXPECT_EQ(0, network_delegate.completed_requests());
5214 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:195215 r->Cancel();
[email protected]9045b8822012-01-13 20:35:355216 // Ensure that network delegate is notified.
5217 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:505218 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:355219 EXPECT_EQ(1, network_delegate.created_requests());
5220 EXPECT_EQ(0, network_delegate.destroyed_requests());
5221 }
5222 EXPECT_EQ(1, network_delegate.destroyed_requests());
5223}
5224
tommycli59a63432015-11-06 00:10:555225namespace {
5226
danakj8522a25b2016-04-16 00:17:365227std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:555228 const test_server::HttpRequest& request) {
5229 if (request.headers.find("Host") == request.headers.end() ||
5230 request.headers.at("Host") != "www.server-auth.com" ||
5231 request.method != test_server::METHOD_CONNECT) {
5232 return nullptr;
5233 }
5234
danakj8522a25b2016-04-16 00:17:365235 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:555236 new test_server::BasicHttpResponse);
5237 http_response->set_code(HTTP_UNAUTHORIZED);
5238 http_response->AddCustomHeader("WWW-Authenticate",
5239 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:485240 return std::move(http_response);
tommycli59a63432015-11-06 00:10:555241}
5242
5243} // namespace
5244
5245// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:115246// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:555247// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:355248TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:555249 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:125250 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:555251 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115252
[email protected]ceefd7fd2012-11-29 00:36:245253 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:045254 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:555255 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:505256
[email protected]dc651782009-02-14 01:45:085257 TestDelegate d;
5258 {
danakj8522a25b2016-04-16 00:17:365259 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165260 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
5261 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:085262
[email protected]f7022f32014-08-21 16:32:195263 r->Start();
5264 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:085265
[email protected]255620da2013-08-19 13:14:295266 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:085267
[email protected]d8fc4722014-06-13 13:17:155268 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:475269 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:505270 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:085271 }
5272}
5273
[email protected]b89290212009-08-14 22:37:355274TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:555275 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115276
initial.commit586acc5fe2008-07-26 22:42:525277 TestDelegate d;
5278 {
danakj8522a25b2016-04-16 00:17:365279 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165280 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5281 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525282
[email protected]f7022f32014-08-21 16:32:195283 r->Start();
5284 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525285
[email protected]255620da2013-08-19 13:14:295286 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:525287
5288 EXPECT_EQ(1, d.response_started_count());
5289 EXPECT_FALSE(d.received_data_before_response());
5290 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555291 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195292 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555293 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195294 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:165295
[email protected]9e743cd2010-03-16 07:03:535296 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:525297 }
initial.commit586acc5fe2008-07-26 22:42:525298}
5299
[email protected]263163f2012-06-14 22:40:345300// This test has the server send a large number of cookies to the client.
5301// To ensure that no number of cookies causes a crash, a galloping binary
5302// search is used to estimate that maximum number of cookies that are accepted
5303// by the browser. Beyond the maximum number, the request will fail with
5304// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:315305#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:305306// http://crbug.com/177916
5307#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
5308#else
5309#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
5310#endif // defined(OS_WIN)
5311TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:555312 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:345313
5314 int lower_bound = 0;
5315 int upper_bound = 1;
5316
5317 // Double the number of cookies until the response header limits are
5318 // exceeded.
5319 while (DoManyCookiesRequest(upper_bound)) {
5320 lower_bound = upper_bound;
5321 upper_bound *= 2;
5322 ASSERT_LT(upper_bound, 1000000);
5323 }
5324
pkasting6b68a162014-12-01 22:10:295325 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:345326 if (tolerance < 2)
5327 tolerance = 2;
5328
5329 // Perform a binary search to find the highest possible number of cookies,
5330 // within the desired tolerance.
5331 while (upper_bound - lower_bound >= tolerance) {
5332 int num_cookies = (lower_bound + upper_bound) / 2;
5333
5334 if (DoManyCookiesRequest(num_cookies))
5335 lower_bound = num_cookies;
5336 else
5337 upper_bound = num_cookies;
5338 }
5339 // Success: the test did not crash.
5340}
5341
[email protected]b89290212009-08-14 22:37:355342TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:555343 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:115344
initial.commit586acc5fe2008-07-26 22:42:525345 TestDelegate d;
5346 {
danakj8522a25b2016-04-16 00:17:365347 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165348 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5349 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:525350
[email protected]f7022f32014-08-21 16:32:195351 r->Start();
5352 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:525353
[email protected]255620da2013-08-19 13:14:295354 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:525355
5356 EXPECT_EQ(1, d.response_started_count());
5357 EXPECT_FALSE(d.received_data_before_response());
5358 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555359 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195360 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555361 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195362 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:525363 }
[email protected]5d7b373e2009-09-02 07:19:035364}
5365
[email protected]79e1fd62013-06-20 06:50:045366TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555367 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045368
5369 TestDelegate d;
5370 {
tommycli59a63432015-11-06 00:10:555371 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:165372 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5373 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045374
5375 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195376 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045377
[email protected]f7022f32014-08-21 16:32:195378 r->Start();
5379 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045380
[email protected]255620da2013-08-19 13:14:295381 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045382
5383 EXPECT_EQ(1, d.response_started_count());
5384 EXPECT_FALSE(d.received_data_before_response());
5385 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555386 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195387 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555388 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195389 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:045390
5391 EXPECT_TRUE(d.have_full_request_headers());
5392 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5393 }
5394}
5395
[email protected]58e32bb2013-01-21 18:23:255396TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555397 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255398
5399 TestDelegate d;
5400 {
danakj8522a25b2016-04-16 00:17:365401 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165402 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5403 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255404
[email protected]f7022f32014-08-21 16:32:195405 r->Start();
5406 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255407
[email protected]255620da2013-08-19 13:14:295408 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255409
5410 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195411 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255412 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5413
5414 EXPECT_EQ(1, d.response_started_count());
5415 EXPECT_FALSE(d.received_data_before_response());
5416 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555417 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195418 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555419 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195420 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255421 }
5422}
5423
tommycli59a63432015-11-06 00:10:555424// TODO(svaldez): Update tests to use EmbeddedTestServer.
5425#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395426TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555427 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555428 base::FilePath(kTestFilePath));
5429
5430 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395431
5432 // Parameter that specifies the Content-Length field in the response:
5433 // C - Compressed length.
5434 // U - Uncompressed length.
5435 // L - Large length (larger than both C & U).
5436 // M - Medium length (between C & U).
5437 // S - Small length (smaller than both C & U).
5438 const char test_parameters[] = "CULMS";
5439 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5440 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445441 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395442 // S has too little data, but we seem to accept it.
5443 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375444 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395445
xunjielifb4da222016-07-14 18:38:595446 base::FilePath file_path;
Avi Drissman5c80d832018-05-01 17:01:195447 base::PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
xunjielifb4da222016-07-14 18:38:595448 file_path = file_path.Append(kTestFilePath);
5449 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5450 std::string expected_content;
5451 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5452
5453 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395454 TestDelegate d;
5455 {
tommycli59a63432015-11-06 00:10:555456 std::string test_file = base::StringPrintf(
5457 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395458
[email protected]ceefd7fd2012-11-29 00:36:245459 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095460 TestURLRequestContext context(true);
5461 context.set_network_delegate(&network_delegate);
5462 context.Init();
[email protected]87a09a92011-07-14 15:50:505463
rhalavatib7bd7c792017-04-27 05:25:165464 std::unique_ptr<URLRequest> r(
5465 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5466 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195467 r->Start();
5468 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395469
[email protected]255620da2013-08-19 13:14:295470 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:395471
5472 EXPECT_EQ(1, d.response_started_count());
5473 EXPECT_FALSE(d.received_data_before_response());
5474 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505475 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395476 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505477 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5478 << "\"";
xunjielifb4da222016-07-14 18:38:595479 if (test_parameters[i] == 'S') {
5480 // When content length is smaller than both compressed length and
5481 // uncompressed length, HttpStreamParser might not read the full
5482 // response body.
5483 continue;
5484 }
5485 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395486 } else {
maksim.sisovb53724b52016-09-16 05:30:505487 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395488 << " Parameter = \"" << test_file << "\"";
5489 }
5490 }
5491 }
5492}
tommycli59a63432015-11-06 00:10:555493#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395494
[email protected]58e32bb2013-01-21 18:23:255495TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555496 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255497
tommycli59a63432015-11-06 00:10:555498 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455499 GURL original_url =
tommycli59a63432015-11-06 00:10:555500 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255501 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165502 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5503 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195504 req->Start();
[email protected]255620da2013-08-19 13:14:295505 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255506
5507 EXPECT_EQ(1, d.response_started_count());
5508 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195509 EXPECT_EQ(destination_url, req->url());
5510 EXPECT_EQ(original_url, req->original_url());
5511 ASSERT_EQ(2U, req->url_chain().size());
5512 EXPECT_EQ(original_url, req->url_chain()[0]);
5513 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255514
5515 LoadTimingInfo load_timing_info_before_redirect;
5516 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5517 &load_timing_info_before_redirect));
5518 TestLoadTimingNotReused(load_timing_info_before_redirect,
5519 CONNECT_TIMING_HAS_DNS_TIMES);
5520
5521 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195522 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255523 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5524
5525 // Check that a new socket was used on redirect, since the server does not
5526 // supposed keep-alive sockets, and that the times before the redirect are
5527 // before the ones recorded for the second request.
5528 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5529 load_timing_info.socket_log_id);
5530 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5531 load_timing_info.connect_timing.connect_start);
5532}
5533
[email protected]8f1ac082011-04-19 21:14:135534TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555535 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135536
tommycli59a63432015-11-06 00:10:555537 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455538 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555539 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5540 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5541 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135542 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165543 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5544 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195545 req->Start();
[email protected]255620da2013-08-19 13:14:295546 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:135547
5548 EXPECT_EQ(1, d.response_started_count());
5549 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195550 EXPECT_EQ(destination_url, req->url());
5551 EXPECT_EQ(original_url, req->original_url());
5552 ASSERT_EQ(3U, req->url_chain().size());
5553 EXPECT_EQ(original_url, req->url_chain()[0]);
5554 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5555 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135556}
5557
[email protected]abe1c4a2013-10-25 19:28:515558// First and second pieces of information logged by delegates to URLRequests.
5559const char kFirstDelegateInfo[] = "Wonderful delegate";
5560const char kSecondDelegateInfo[] = "Exciting delegate";
5561
5562// Logs delegate information to a URLRequest. The first string is logged
5563// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5564// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5565// another asynchronous call is used to clear the delegate information
5566// before calling a callback. The object then deletes itself.
5567class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5568 public:
5569 typedef base::Callback<void()> Callback;
5570
5571 // Each time delegate information is added to the URLRequest, the resulting
5572 // load state is checked. The expected load state after each request is
5573 // passed in as an argument.
5574 static void Run(URLRequest* url_request,
5575 LoadState expected_first_load_state,
5576 LoadState expected_second_load_state,
5577 LoadState expected_third_load_state,
5578 const Callback& callback) {
5579 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
5580 url_request,
5581 expected_first_load_state,
5582 expected_second_load_state,
5583 expected_third_load_state,
5584 callback);
5585 logger->Start();
5586 }
5587
5588 // Checks that the log entries, starting with log_position, contain the
5589 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5590 // recorded. Returns the index of entry after the expected number of
5591 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465592 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515593 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515594 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5595 if (log_position + 3 >= entries.size()) {
5596 ADD_FAILURE() << "Not enough log entries";
5597 return entries.size();
5598 }
5599 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005600 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5601 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075602 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515603 &delegate_info));
5604 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5605
5606 ++log_position;
mikecirone8b85c432016-09-08 19:11:005607 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5608 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515609
5610 ++log_position;
mikecirone8b85c432016-09-08 19:11:005611 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5612 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075613 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515614 &delegate_info));
5615 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5616
5617 ++log_position;
mikecirone8b85c432016-09-08 19:11:005618 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5619 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515620
5621 return log_position + 1;
5622 }
5623
5624 private:
5625 friend class base::RefCounted<AsyncDelegateLogger>;
5626
5627 AsyncDelegateLogger(URLRequest* url_request,
5628 LoadState expected_first_load_state,
5629 LoadState expected_second_load_state,
5630 LoadState expected_third_load_state,
5631 const Callback& callback)
5632 : url_request_(url_request),
5633 expected_first_load_state_(expected_first_load_state),
5634 expected_second_load_state_(expected_second_load_state),
5635 expected_third_load_state_(expected_third_load_state),
5636 callback_(callback) {
5637 }
5638
Chris Watkins7a41d3552017-12-01 02:13:275639 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515640
5641 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535642 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515643 LoadStateWithParam load_state = url_request_->GetLoadState();
5644 EXPECT_EQ(expected_first_load_state_, load_state.state);
5645 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455646 base::ThreadTaskRunnerHandle::Get()->PostTask(
5647 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515648 }
5649
5650 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535651 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515652 LoadStateWithParam load_state = url_request_->GetLoadState();
5653 EXPECT_EQ(expected_second_load_state_, load_state.state);
5654 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5655 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5656 } else {
5657 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5658 }
skyostil4891b25b2015-06-11 11:43:455659 base::ThreadTaskRunnerHandle::Get()->PostTask(
5660 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515661 }
5662
5663 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535664 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515665 LoadStateWithParam load_state = url_request_->GetLoadState();
5666 EXPECT_EQ(expected_third_load_state_, load_state.state);
5667 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085668 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515669 callback_.Run();
5670 }
5671
5672 URLRequest* url_request_;
5673 const int expected_first_load_state_;
5674 const int expected_second_load_state_;
5675 const int expected_third_load_state_;
5676 const Callback callback_;
5677
5678 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5679};
5680
5681// NetworkDelegate that logs delegate information before a request is started,
5682// before headers are sent, when headers are read, and when auth information
5683// is requested. Uses AsyncDelegateLogger.
5684class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5685 public:
Chris Watkins7a41d3552017-12-01 02:13:275686 AsyncLoggingNetworkDelegate() = default;
5687 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515688
5689 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205690 int OnBeforeURLRequest(URLRequest* request,
5691 const CompletionCallback& callback,
5692 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:515693 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
5694 return RunCallbackAsynchronously(request, callback);
5695 }
5696
ryansturm2343cb62016-06-15 01:09:005697 int OnBeforeStartTransaction(URLRequest* request,
5698 const CompletionCallback& callback,
5699 HttpRequestHeaders* headers) override {
5700 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:515701 return RunCallbackAsynchronously(request, callback);
5702 }
5703
dchengb03027d2014-10-21 12:00:205704 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515705 URLRequest* request,
5706 const CompletionCallback& callback,
5707 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165708 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135709 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:165710 TestNetworkDelegate::OnHeadersReceived(request,
5711 callback,
[email protected]abe1c4a2013-10-25 19:28:515712 original_response_headers,
[email protected]5f714132014-03-26 10:41:165713 override_response_headers,
5714 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:515715 return RunCallbackAsynchronously(request, callback);
5716 }
5717
dchengb03027d2014-10-21 12:00:205718 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515719 URLRequest* request,
5720 const AuthChallengeInfo& auth_info,
5721 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:135722 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515723 AsyncDelegateLogger::Run(
5724 request,
5725 LOAD_STATE_WAITING_FOR_DELEGATE,
5726 LOAD_STATE_WAITING_FOR_DELEGATE,
5727 LOAD_STATE_WAITING_FOR_DELEGATE,
5728 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5729 callback, credentials));
5730 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5731 }
5732
5733 private:
5734 static int RunCallbackAsynchronously(
5735 URLRequest* request,
5736 const CompletionCallback& callback) {
5737 AsyncDelegateLogger::Run(
5738 request,
5739 LOAD_STATE_WAITING_FOR_DELEGATE,
5740 LOAD_STATE_WAITING_FOR_DELEGATE,
5741 LOAD_STATE_WAITING_FOR_DELEGATE,
5742 base::Bind(callback, OK));
5743 return ERR_IO_PENDING;
5744 }
5745
5746 static void SetAuthAndResume(const AuthCallback& callback,
5747 AuthCredentials* credentials) {
5748 *credentials = AuthCredentials(kUser, kSecret);
5749 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5750 }
5751
5752 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5753};
5754
5755// URLRequest::Delegate that logs delegate information when the headers
5756// are received, when each read completes, and during redirects. Uses
5757// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5758//
5759// Inherits from TestDelegate to reuse the TestDelegate code to handle
5760// advancing to the next step in most cases, as well as cancellation.
5761class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5762 public:
5763 enum CancelStage {
5764 NO_CANCEL = 0,
5765 CANCEL_ON_RECEIVED_REDIRECT,
5766 CANCEL_ON_RESPONSE_STARTED,
5767 CANCEL_ON_READ_COMPLETED
5768 };
5769
5770 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5771 : cancel_stage_(cancel_stage) {
5772 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5773 set_cancel_in_received_redirect(true);
5774 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5775 set_cancel_in_response_started(true);
5776 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5777 set_cancel_in_received_data(true);
5778 }
Chris Watkins7a41d3552017-12-01 02:13:275779 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515780
5781 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205782 void OnReceivedRedirect(URLRequest* request,
5783 const RedirectInfo& redirect_info,
5784 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515785 *defer_redirect = true;
5786 AsyncDelegateLogger::Run(
5787 request,
5788 LOAD_STATE_WAITING_FOR_DELEGATE,
5789 LOAD_STATE_WAITING_FOR_DELEGATE,
5790 LOAD_STATE_WAITING_FOR_DELEGATE,
5791 base::Bind(
5792 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595793 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515794 }
5795
maksim.sisov0f4aa142016-09-05 05:55:285796 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515797 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285798 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5799 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5800 base::Bind(
5801 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5802 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515803 }
5804
dchengb03027d2014-10-21 12:00:205805 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515806 AsyncDelegateLogger::Run(
5807 request,
5808 LOAD_STATE_IDLE,
5809 LOAD_STATE_IDLE,
5810 LOAD_STATE_IDLE,
5811 base::Bind(
5812 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5813 base::Unretained(this), request, bytes_read));
5814 }
5815
5816 private:
5817 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595818 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515819 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595820 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515821 // FollowDeferredRedirect should not be called after cancellation.
5822 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5823 return;
5824 if (!defer_redirect)
5825 request->FollowDeferredRedirect();
5826 }
5827
maksim.sisov0f4aa142016-09-05 05:55:285828 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515829 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285830 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515831 }
5832
5833 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5834 // The parent class continues the request.
5835 TestDelegate::OnReadCompleted(request, bytes_read);
5836 }
5837
5838 const CancelStage cancel_stage_;
5839
5840 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5841};
5842
5843// Tests handling of delegate info before a request starts.
5844TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555845 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515846
5847 TestDelegate request_delegate;
5848 TestURLRequestContext context(true);
5849 context.set_network_delegate(NULL);
5850 context.set_net_log(&net_log_);
5851 context.Init();
5852
5853 {
rhalavatib7bd7c792017-04-27 05:25:165854 std::unique_ptr<URLRequest> r(context.CreateRequest(
5855 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5856 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195857 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515858 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085859 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515860
5861 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195862 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515863 LOAD_STATE_WAITING_FOR_DELEGATE,
5864 LOAD_STATE_WAITING_FOR_DELEGATE,
5865 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195866 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515867
5868 base::RunLoop().Run();
5869
[email protected]f7022f32014-08-21 16:32:195870 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505871 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515872 }
5873
mmenke43758e62015-05-04 21:09:465874 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515875 net_log_.GetEntries(&entries);
5876 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005877 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515878
5879 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5880
5881 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005882 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5883 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515884}
5885
5886// Tests handling of delegate info from a network delegate.
5887TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555888 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515889
5890 TestDelegate request_delegate;
5891 AsyncLoggingNetworkDelegate network_delegate;
5892 TestURLRequestContext context(true);
5893 context.set_network_delegate(&network_delegate);
5894 context.set_net_log(&net_log_);
5895 context.Init();
5896
5897 {
rhalavatib7bd7c792017-04-27 05:25:165898 std::unique_ptr<URLRequest> r(context.CreateRequest(
5899 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5900 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195901 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515902 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085903 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515904
[email protected]f7022f32014-08-21 16:32:195905 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515906 base::RunLoop().Run();
5907
[email protected]f7022f32014-08-21 16:32:195908 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505909 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515910 EXPECT_EQ(1, network_delegate.created_requests());
5911 EXPECT_EQ(0, network_delegate.destroyed_requests());
5912 }
5913 EXPECT_EQ(1, network_delegate.destroyed_requests());
5914
5915 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465916 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515917 net_log_.GetEntries(&entries);
5918 for (size_t i = 0; i < 3; ++i) {
5919 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005920 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5921 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515922
5923 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5924 log_position + 1);
5925
5926 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005927 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5928 entries[log_position].type);
5929 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515930 }
5931
mikecirone8b85c432016-09-08 19:11:005932 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5933 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515934}
5935
5936// Tests handling of delegate info from a network delegate in the case of an
5937// HTTP redirect.
5938TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555939 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515940
5941 TestDelegate request_delegate;
5942 AsyncLoggingNetworkDelegate network_delegate;
5943 TestURLRequestContext context(true);
5944 context.set_network_delegate(&network_delegate);
5945 context.set_net_log(&net_log_);
5946 context.Init();
5947
5948 {
danakj8522a25b2016-04-16 00:17:365949 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555950 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165951 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195952 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515953 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085954 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515955
[email protected]f7022f32014-08-21 16:32:195956 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515957 base::RunLoop().Run();
5958
[email protected]f7022f32014-08-21 16:32:195959 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505960 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515961 EXPECT_EQ(2, network_delegate.created_requests());
5962 EXPECT_EQ(0, network_delegate.destroyed_requests());
5963 }
5964 EXPECT_EQ(1, network_delegate.destroyed_requests());
5965
5966 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465967 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515968 net_log_.GetEntries(&entries);
5969 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005970 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515971 for (size_t i = 0; i < 3; ++i) {
5972 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005973 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5974 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515975
5976 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5977 log_position + 1);
5978
5979 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005980 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5981 entries[log_position].type);
5982 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515983 }
5984
5985 // The URLRequest::Delegate then gets informed about the redirect.
5986 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005987 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5988 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515989
5990 // The NetworkDelegate logged information in the same three events as before.
5991 for (size_t i = 0; i < 3; ++i) {
5992 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005993 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5994 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515995
5996 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5997 log_position + 1);
5998
5999 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006000 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6001 entries[log_position].type);
6002 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516003 }
6004
mikecirone8b85c432016-09-08 19:11:006005 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6006 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516007}
6008
6009// Tests handling of delegate info from a network delegate in the case of HTTP
6010// AUTH.
6011TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:556012 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516013
6014 TestDelegate request_delegate;
6015 AsyncLoggingNetworkDelegate network_delegate;
6016 TestURLRequestContext context(true);
6017 context.set_network_delegate(&network_delegate);
6018 context.set_net_log(&net_log_);
6019 context.Init();
6020
6021 {
rhalavatib7bd7c792017-04-27 05:25:166022 std::unique_ptr<URLRequest> r(context.CreateRequest(
6023 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
6024 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196025 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:516026 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:086027 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:516028
[email protected]f7022f32014-08-21 16:32:196029 r->Start();
[email protected]abe1c4a2013-10-25 19:28:516030 base::RunLoop().Run();
6031
[email protected]f7022f32014-08-21 16:32:196032 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506033 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516034 EXPECT_EQ(1, network_delegate.created_requests());
6035 EXPECT_EQ(0, network_delegate.destroyed_requests());
6036 }
6037 EXPECT_EQ(1, network_delegate.destroyed_requests());
6038
6039 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:466040 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516041 net_log_.GetEntries(&entries);
6042 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:006043 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
6044 // in
6045 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:516046 for (size_t i = 0; i < 6; ++i) {
6047 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006048 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6049 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516050
6051 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6052 log_position + 1);
6053
6054 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006055 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6056 entries[log_position].type);
6057 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516058 }
6059
mikecirone8b85c432016-09-08 19:11:006060 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6061 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516062}
6063
tommycli59a63432015-11-06 00:10:556064// TODO(svaldez): Update tests to use EmbeddedTestServer.
6065#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516066// Tests handling of delegate info from a URLRequest::Delegate.
6067TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:556068 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:556069 base::FilePath(kTestFilePath));
6070
6071 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:516072
6073 AsyncLoggingUrlRequestDelegate request_delegate(
6074 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6075 TestURLRequestContext context(true);
6076 context.set_network_delegate(NULL);
6077 context.set_net_log(&net_log_);
6078 context.Init();
6079
6080 {
6081 // A chunked response with delays between chunks is used to make sure that
6082 // attempts by the URLRequest delegate to log information while reading the
6083 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:486084 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:516085 // that it occurs.
danakj8522a25b2016-04-16 00:17:366086 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556087 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166088 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196089 LoadStateWithParam load_state = r->GetLoadState();
6090 r->Start();
[email protected]abe1c4a2013-10-25 19:28:516091 base::RunLoop().Run();
6092
[email protected]f7022f32014-08-21 16:32:196093 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506094 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516095 }
6096
mmenke43758e62015-05-04 21:09:466097 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516098 net_log_.GetEntries(&entries);
6099
[email protected]1826a402014-01-08 15:40:486100 size_t log_position = 0;
6101
[email protected]abe1c4a2013-10-25 19:28:516102 // The delegate info should only have been logged on header complete. Other
6103 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:006104 log_position = ExpectLogContainsSomewhereAfter(
6105 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
6106 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516107
6108 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6109 log_position + 1);
6110
6111 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006112 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
6113 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516114
mikecirone8b85c432016-09-08 19:11:006115 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6116 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516117 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006118 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516119}
tommycli59a63432015-11-06 00:10:556120#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:516121
6122// Tests handling of delegate info from a URLRequest::Delegate in the case of
6123// an HTTP redirect.
6124TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:556125 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516126
6127 AsyncLoggingUrlRequestDelegate request_delegate(
6128 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
6129 TestURLRequestContext context(true);
6130 context.set_network_delegate(NULL);
6131 context.set_net_log(&net_log_);
6132 context.Init();
6133
6134 {
danakj8522a25b2016-04-16 00:17:366135 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556136 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166137 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196138 LoadStateWithParam load_state = r->GetLoadState();
6139 r->Start();
[email protected]abe1c4a2013-10-25 19:28:516140 base::RunLoop().Run();
6141
[email protected]f7022f32014-08-21 16:32:196142 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:506143 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516144 }
6145
mmenke43758e62015-05-04 21:09:466146 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516147 net_log_.GetEntries(&entries);
6148
6149 // Delegate info should only have been logged in OnReceivedRedirect and
6150 // OnResponseStarted.
6151 size_t log_position = 0;
6152 for (int i = 0; i < 2; ++i) {
6153 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006154 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
6155 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516156
6157 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6158 log_position + 1);
6159
6160 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006161 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6162 entries[log_position].type);
6163 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516164 }
6165
mikecirone8b85c432016-09-08 19:11:006166 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6167 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516168 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006169 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516170}
6171
6172// Tests handling of delegate info from a URLRequest::Delegate in the case of
6173// an HTTP redirect, with cancellation at various points.
6174TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:556175 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:516176
6177 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
6178 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
6179 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
6180 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
6181 };
6182
6183 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
6184 ++test_case) {
6185 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:516186 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:046187 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:516188 context.set_network_delegate(NULL);
6189 context.set_net_log(&net_log);
6190 context.Init();
6191
6192 {
danakj8522a25b2016-04-16 00:17:366193 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556194 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:166195 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196196 LoadStateWithParam load_state = r->GetLoadState();
6197 r->Start();
[email protected]abe1c4a2013-10-25 19:28:516198 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506199 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:516200 }
6201
mmenke43758e62015-05-04 21:09:466202 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:516203 net_log.GetEntries(&entries);
6204
6205 // Delegate info is always logged in both OnReceivedRedirect and
6206 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
6207 // OnResponseStarted delegate call is after cancellation, but logging is
6208 // still currently supported in that call.
6209 size_t log_position = 0;
6210 for (int i = 0; i < 2; ++i) {
6211 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:006212 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
6213 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:516214
6215 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
6216 log_position + 1);
6217
6218 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:006219 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
6220 entries[log_position].type);
6221 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:516222 }
6223
mikecirone8b85c432016-09-08 19:11:006224 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
6225 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:516226 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:006227 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:516228 }
6229}
6230
[email protected]847c0fa92012-11-06 16:37:426231namespace {
6232
6233const char kExtraHeader[] = "Allow-Snafu";
6234const char kExtraValue[] = "fubar";
6235
6236class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206237 void OnReceivedRedirect(URLRequest* request,
6238 const RedirectInfo& redirect_info,
6239 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596240 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:426241 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
6242 }
6243};
6244
6245} // namespace
6246
6247TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:556248 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:426249
tommycli59a63432015-11-06 00:10:556250 GURL destination_url =
6251 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
6252 GURL original_url =
6253 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:426254 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166255 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6256 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196257 req->Start();
[email protected]255620da2013-08-19 13:14:296258 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:426259
6260 std::string value;
[email protected]f7022f32014-08-21 16:32:196261 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:426262 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
6263 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:196264 EXPECT_FALSE(req->is_pending());
6265 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:426266 EXPECT_EQ(kExtraValue, d.data_received());
6267}
6268
[email protected]251a1b92012-11-13 11:01:096269namespace {
6270
6271const char kExtraHeaderToRemove[] = "To-Be-Removed";
6272
6273class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:206274 void OnReceivedRedirect(URLRequest* request,
6275 const RedirectInfo& redirect_info,
6276 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:596277 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:096278 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
6279 }
6280};
6281
6282} // namespace
6283
6284TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:556285 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:096286
tommycli59a63432015-11-06 00:10:556287 GURL destination_url = http_test_server()->GetURL(
6288 "/echoheader?" + std::string(kExtraHeaderToRemove));
6289 GURL original_url =
6290 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:096291 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:166292 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
6293 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196294 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
6295 req->Start();
[email protected]255620da2013-08-19 13:14:296296 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:096297
6298 std::string value;
[email protected]f7022f32014-08-21 16:32:196299 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:096300 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:196301 EXPECT_FALSE(req->is_pending());
6302 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:096303 EXPECT_EQ("None", d.data_received());
6304}
6305
mmenke94f1bd92016-12-07 21:13:056306TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:446307 TestDelegate d;
6308 {
danakj8522a25b2016-04-16 00:17:366309 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166310 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
6311 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446312
[email protected]f7022f32014-08-21 16:32:196313 r->Start();
6314 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446315
[email protected]f7022f32014-08-21 16:32:196316 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446317
[email protected]255620da2013-08-19 13:14:296318 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446319
6320 // We expect to receive OnResponseStarted even though the request has been
6321 // cancelled.
6322 EXPECT_EQ(1, d.response_started_count());
6323 EXPECT_EQ(0, d.bytes_received());
6324 EXPECT_FALSE(d.received_data_before_response());
6325 }
6326}
6327
mmenke94f1bd92016-12-07 21:13:056328TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:556329 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446330
6331 TestDelegate d;
6332 {
danakj8522a25b2016-04-16 00:17:366333 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166334 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6335 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446336
6337 d.set_cancel_in_response_started(true);
6338
[email protected]f7022f32014-08-21 16:32:196339 r->Start();
6340 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446341
[email protected]255620da2013-08-19 13:14:296342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446343
6344 EXPECT_EQ(1, d.response_started_count());
6345 EXPECT_EQ(0, d.bytes_received());
6346 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506347 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446348 }
6349}
6350
mmenke94f1bd92016-12-07 21:13:056351TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:556352 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446353
6354 TestDelegate d;
6355 {
danakj8522a25b2016-04-16 00:17:366356 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166357 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6358 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056359
6360 d.set_cancel_in_received_data(true);
6361
6362 r->Start();
6363 EXPECT_TRUE(r->is_pending());
6364
6365 base::RunLoop().Run();
6366
6367 EXPECT_EQ(1, d.response_started_count());
6368 EXPECT_NE(0, d.received_bytes_count());
6369 EXPECT_FALSE(d.received_data_before_response());
6370 EXPECT_EQ(ERR_ABORTED, d.request_status());
6371 }
6372}
6373
6374TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6375 ASSERT_TRUE(http_test_server()->Start());
6376
6377 TestDelegate d;
6378 {
6379 // This returns an empty response (With headers).
6380 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166381 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6382 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446383
6384 d.set_cancel_in_received_data(true);
6385
[email protected]f7022f32014-08-21 16:32:196386 r->Start();
6387 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446388
[email protected]255620da2013-08-19 13:14:296389 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446390
6391 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056392 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446393 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506394 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446395 }
6396}
6397
mmenke94f1bd92016-12-07 21:13:056398TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556399 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446400
6401 TestDelegate d;
6402 {
danakj8522a25b2016-04-16 00:17:366403 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166404 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6405 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446406
[email protected]f7022f32014-08-21 16:32:196407 r->Start();
6408 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446409
6410 // The request will be implicitly canceled when it is destroyed. The
6411 // test delegate must not post a quit message when this happens because
6412 // this test doesn't actually have a message loop. The quit message would
6413 // get put on this thread's message queue and the next test would exit
6414 // early, causing problems.
6415 d.set_quit_on_complete(false);
6416 }
6417 // expect things to just cleanup properly.
6418
kimwjdalsl2bb4ff02015-12-16 22:06:026419 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446420 // message loop
6421 EXPECT_FALSE(d.received_data_before_response());
6422 EXPECT_EQ(0, d.bytes_received());
6423}
6424
mmenke94f1bd92016-12-07 21:13:056425TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556426 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446427
6428 // populate cache
6429 {
6430 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366431 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166432 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6433 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196434 r->Start();
[email protected]255620da2013-08-19 13:14:296435 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506436 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446437 }
6438
6439 // cancel read from cache (see bug 990242)
6440 {
6441 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366442 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166443 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6444 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196445 r->Start();
6446 r->Cancel();
[email protected]255620da2013-08-19 13:14:296447 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446448
maksim.sisovb53724b52016-09-16 05:30:506449 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446450 EXPECT_EQ(1, d.response_started_count());
6451 EXPECT_EQ(0, d.bytes_received());
6452 EXPECT_FALSE(d.received_data_before_response());
6453 }
6454}
6455
6456TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556457 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446458 HTTPUploadDataOperationTest("POST");
6459}
6460
6461TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556462 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446463 HTTPUploadDataOperationTest("PUT");
6464}
6465
6466TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556467 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446468
6469 TestDelegate d;
6470 {
danakj8522a25b2016-04-16 00:17:366471 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166472 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6473 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196474 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446475
[email protected]f7022f32014-08-21 16:32:196476 r->Start();
6477 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446478
[email protected]255620da2013-08-19 13:14:296479 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446480
maksim.sisovb53724b52016-09-16 05:30:506481 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6482 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446483
6484 EXPECT_FALSE(d.received_data_before_response());
6485 EXPECT_TRUE(d.data_received().empty());
6486 }
6487}
6488
6489TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556490 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446491
6492 TestDelegate d;
6493 {
danakj8522a25b2016-04-16 00:17:366494 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166495 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6496 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196497 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446498
[email protected]6cdfd7f2013-02-08 20:40:156499 base::FilePath dir;
Avi Drissman5c80d832018-05-01 17:01:196500 base::PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026501 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446502
danakj8522a25b2016-04-16 00:17:366503 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446504
[email protected]6cdfd7f2013-02-08 20:40:156505 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:196506 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476507 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446508 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196509 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146510 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076511 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046512 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6513 std::move(element_readers), 0));
[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
[email protected]255620da2013-08-19 13:14:296518 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446519
avibf0746c2015-12-09 19:53:146520 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296521 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6522 ASSERT_LE(size64, std::numeric_limits<int>::max());
6523 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366524 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446525
[email protected]7600d0b2013-12-08 21:43:306526 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446527
maksim.sisovb53724b52016-09-16 05:30:506528 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6529 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446530
6531 EXPECT_FALSE(d.received_data_before_response());
6532
[email protected]329b68b2012-11-14 17:54:276533 EXPECT_EQ(size, d.bytes_received());
6534 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446535 }
6536}
6537
[email protected]999dd8c2013-11-12 06:45:546538TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556539 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546540
6541 TestDelegate d;
6542 {
danakj8522a25b2016-04-16 00:17:366543 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166544 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6545 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196546 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546547
danakj8522a25b2016-04-16 00:17:366548 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546549
Jeremy Roman0579ed62017-08-29 15:56:196550 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456551 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546552 base::FilePath(FILE_PATH_LITERAL(
6553 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076554 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046555 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6556 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546557
[email protected]f7022f32014-08-21 16:32:196558 r->Start();
6559 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546560
6561 base::RunLoop().Run();
6562
[email protected]999dd8c2013-11-12 06:45:546563 EXPECT_TRUE(d.request_failed());
6564 EXPECT_FALSE(d.received_data_before_response());
6565 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506566 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546567 }
6568}
6569
mmenke56b0cbb912016-03-28 21:34:536570namespace {
6571
6572// Adds a standard set of data to an upload for chunked upload integration
6573// tests.
6574void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6575 writer->AppendData("a", 1, false);
6576 writer->AppendData("bcd", 3, false);
6577 writer->AppendData("this is a longer chunk than before.", 35, false);
6578 writer->AppendData("\r\n\r\n", 4, false);
6579 writer->AppendData("0", 1, false);
6580 writer->AppendData("2323", 4, true);
6581}
6582
6583// Checks that the upload data added in AddChunksToUpload() was echoed back from
6584// the server.
6585void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6586 // This should match the chunks sent by AddChunksToUpload().
6587 const std::string expected_data =
6588 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6589
maksim.sisovb53724b52016-09-16 05:30:506590 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6591 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536592
6593 EXPECT_FALSE(d->received_data_before_response());
6594
6595 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6596 EXPECT_EQ(expected_data, d->data_received());
6597}
6598
6599} // namespace
6600
[email protected]316c1e5e2012-09-12 15:17:446601TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556602 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446603
6604 TestDelegate d;
6605 {
danakj8522a25b2016-04-16 00:17:366606 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166607 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6608 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366609 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536610 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366611 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536612 upload_data_stream->CreateWriter();
6613 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196614 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536615 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196616 r->Start();
6617 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446618
[email protected]255620da2013-08-19 13:14:296619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446620
[email protected]f7022f32014-08-21 16:32:196621 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446622 }
6623}
6624
[email protected]329b68b2012-11-14 17:54:276625TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556626 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276627
6628 TestDelegate d;
6629 {
danakj8522a25b2016-04-16 00:17:366630 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166631 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6632 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366633 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536634 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366635 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536636 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046637 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196638 r->set_method("POST");
6639 r->Start();
6640 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536641 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296642 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:276643
[email protected]f7022f32014-08-21 16:32:196644 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276645 }
6646}
6647
[email protected]316c1e5e2012-09-12 15:17:446648TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556649 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446650
6651 TestDelegate d;
6652 {
danakj8522a25b2016-04-16 00:17:366653 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166654 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6655 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366656 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536657 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366658 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536659 upload_data_stream->CreateWriter();
6660 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196661 r->set_method("POST");
6662 r->Start();
6663 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446664
[email protected]255620da2013-08-19 13:14:296665 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536666 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296667 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446668
[email protected]f7022f32014-08-21 16:32:196669 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446670 }
6671}
6672
6673TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556674 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446675
6676 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366677 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166678 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6679 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196680 req->Start();
[email protected]255620da2013-08-19 13:14:296681 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446682
[email protected]f7022f32014-08-21 16:32:196683 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446684
6685 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196686 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446687
6688 std::string header;
6689 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6690 EXPECT_EQ("private", header);
6691
6692 header.clear();
6693 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6694 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6695
6696 // The response has two "X-Multiple-Entries" headers.
6697 // This verfies our output has them concatenated together.
6698 header.clear();
6699 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6700 EXPECT_EQ("a, b", header);
6701}
6702
tommycli59a63432015-11-06 00:10:556703// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6704// security state. (see http://crbug.com/550977).
6705#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466706TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556707 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6708 https_test_server.SetSSLConfig(
6709 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6710 https_test_server.ServeFilesFromSourceDirectory(
6711 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466712 ASSERT_TRUE(https_test_server.Start());
6713
tommycli59a63432015-11-06 00:10:556714 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466715 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366716 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166717 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6718 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196719 request->Start();
[email protected]255620da2013-08-19 13:14:296720 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466721
6722 TransportSecurityState* security_state =
6723 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406724 TransportSecurityState::STSState sts_state;
6725 TransportSecurityState::PKPState pkp_state;
6726 EXPECT_TRUE(
6727 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6728 EXPECT_FALSE(
6729 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6730 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6731 sts_state.upgrade_mode);
6732 EXPECT_TRUE(sts_state.include_subdomains);
6733 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036734#if defined(OS_ANDROID)
6735 // Android's CertVerifyProc does not (yet) handle pins.
6736#else
martijnc0d6b622015-06-30 19:14:406737 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036738#endif
[email protected]37fd55fb2013-06-29 13:13:276739}
6740
estarka5da76702015-04-09 04:00:166741TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556742 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6743 https_test_server.ServeFilesFromSourceDirectory(
6744 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166745 ASSERT_TRUE(https_test_server.Start());
6746 // Make sure this test fails if the test server is changed to not
6747 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556748 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6749 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166750
6751 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366752 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166753 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6754 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166755 request->Start();
6756 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166757 TransportSecurityState* security_state =
6758 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406759 TransportSecurityState::STSState sts_state;
6760 EXPECT_FALSE(
6761 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166762}
6763
estark06e0dac2015-08-07 21:56:016764namespace {
Martijn Croonenb1383da2017-10-11 11:56:356765const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
6766const char kExpectStapleStaticHostname[] = "expect-staple.preloaded.test";
6767const char kExpectStapleReportURI[] =
6768 "http://report-uri.preloaded.test/expect-staple";
estark06e0dac2015-08-07 21:56:016769const char kHPKPReportUri[] = "https://hpkp-report.test";
6770} // namespace
6771
[email protected]37fd55fb2013-06-29 13:13:276772// Tests that enabling HPKP on a domain does not affect the HSTS
6773// validity/expiration.
dadrian2faf2062016-07-16 00:03:176774TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016775 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556776 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6777 https_test_server.SetSSLConfig(
6778 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6779 https_test_server.ServeFilesFromSourceDirectory(
6780 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276781 ASSERT_TRUE(https_test_server.Start());
6782
tommycli59a63432015-11-06 00:10:556783 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166784
[email protected]37fd55fb2013-06-29 13:13:276785 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366786 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166787 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6788 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196789 request->Start();
[email protected]255620da2013-08-19 13:14:296790 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276791 TransportSecurityState* security_state =
6792 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406793 TransportSecurityState::STSState sts_state;
6794 TransportSecurityState::PKPState pkp_state;
6795 EXPECT_FALSE(
6796 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6797 EXPECT_TRUE(
6798 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6799 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6800 sts_state.upgrade_mode);
6801 EXPECT_FALSE(sts_state.include_subdomains);
6802 EXPECT_FALSE(pkp_state.include_subdomains);
6803 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016804 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406805 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466806}
6807
estark06e0dac2015-08-07 21:56:016808// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176809TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016810 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556811 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6812 https_test_server.SetSSLConfig(
6813 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6814 https_test_server.ServeFilesFromSourceDirectory(
6815 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016816 ASSERT_TRUE(https_test_server.Start());
6817
tommycli59a63432015-11-06 00:10:556818 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016819
6820 // Set up a pin for |test_server_hostname|.
6821 TransportSecurityState security_state;
6822 const base::Time current_time(base::Time::Now());
6823 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6824 HashValueVector hashes;
6825 HashValue hash1;
6826 HashValue hash2;
6827 // The values here don't matter, as long as they are different from
6828 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446829 ASSERT_TRUE(
6830 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6831 ASSERT_TRUE(
6832 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016833 hashes.push_back(hash1);
6834 hashes.push_back(hash2);
6835 security_state.AddHPKP(test_server_hostname, expiry,
6836 false, /* include subdomains */
6837 hashes, report_uri);
6838
6839 MockCertificateReportSender mock_report_sender;
6840 security_state.SetReportSender(&mock_report_sender);
6841
6842 // Set up a MockCertVerifier to trigger a violation of the previously
6843 // set pin.
6844 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6845 ASSERT_TRUE(cert);
6846
6847 MockCertVerifier cert_verifier;
6848 CertVerifyResult verify_result;
6849 verify_result.verified_cert = cert;
6850 verify_result.is_issued_by_known_root = true;
6851 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446852 ASSERT_TRUE(
6853 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016854 verify_result.public_key_hashes.push_back(hash3);
6855 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6856
6857 TestNetworkDelegate network_delegate;
6858 TestURLRequestContext context(true);
6859 context.set_transport_security_state(&security_state);
6860 context.set_network_delegate(&network_delegate);
6861 context.set_cert_verifier(&cert_verifier);
6862 context.Init();
6863
6864 // Now send a request to trigger the violation.
6865 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366866 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166867 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6868 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016869 violating_request->Start();
6870 base::RunLoop().Run();
6871
6872 // Check that a report was sent.
6873 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6874 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446875 EXPECT_EQ("application/json; charset=utf-8",
6876 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366877 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016878 base::JSONReader::Read(mock_report_sender.latest_report()));
6879 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086880 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016881 base::DictionaryValue* report_dict;
6882 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6883 std::string report_hostname;
6884 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6885 EXPECT_EQ(test_server_hostname, report_hostname);
6886}
6887
6888// Tests that reports get sent on requests with
6889// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176890TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016891 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556892 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6893 https_test_server.SetSSLConfig(
6894 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6895 https_test_server.ServeFilesFromSourceDirectory(
6896 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016897 ASSERT_TRUE(https_test_server.Start());
6898
tommycli59a63432015-11-06 00:10:556899 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016900
6901 TransportSecurityState security_state;
6902 MockCertificateReportSender mock_report_sender;
6903 security_state.SetReportSender(&mock_report_sender);
6904
6905 // Set up a MockCertVerifier to violate the pin in the Report-Only
6906 // header.
6907 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6908 ASSERT_TRUE(cert);
6909
6910 MockCertVerifier cert_verifier;
6911 CertVerifyResult verify_result;
6912 verify_result.verified_cert = cert;
6913 verify_result.is_issued_by_known_root = true;
6914 HashValue hash;
6915 // This value doesn't matter, as long as it is different from the pins
6916 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446917 ASSERT_TRUE(
6918 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016919 verify_result.public_key_hashes.push_back(hash);
6920 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6921
6922 TestNetworkDelegate network_delegate;
6923 TestURLRequestContext context(true);
6924 context.set_transport_security_state(&security_state);
6925 context.set_network_delegate(&network_delegate);
6926 context.set_cert_verifier(&cert_verifier);
6927 context.Init();
6928
6929 // Now send a request to trigger the violation.
6930 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366931 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556932 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166933 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016934 violating_request->Start();
6935 base::RunLoop().Run();
6936
6937 // Check that a report was sent.
6938 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6939 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446940 EXPECT_EQ("application/json; charset=utf-8",
6941 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366942 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016943 base::JSONReader::Read(mock_report_sender.latest_report()));
6944 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086945 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016946 base::DictionaryValue* report_dict;
6947 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6948 std::string report_hostname;
6949 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6950 EXPECT_EQ(test_server_hostname, report_hostname);
6951}
6952
6953// Tests that reports do not get sent on requests with
6954// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176955TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016956 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556957 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6958 https_test_server.SetSSLConfig(
6959 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6960 https_test_server.ServeFilesFromSourceDirectory(
6961 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016962 ASSERT_TRUE(https_test_server.Start());
6963
tommycli59a63432015-11-06 00:10:556964 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016965
6966 TransportSecurityState security_state;
6967 MockCertificateReportSender mock_report_sender;
6968 security_state.SetReportSender(&mock_report_sender);
6969
6970 TestNetworkDelegate network_delegate;
6971 MockCertVerifier mock_cert_verifier;
6972 TestURLRequestContext context(true);
6973 context.set_transport_security_state(&security_state);
6974 context.set_network_delegate(&network_delegate);
6975 context.set_cert_verifier(&mock_cert_verifier);
6976 mock_cert_verifier.set_default_result(OK);
6977 context.Init();
6978
6979 // Now send a request that does not trigger the violation.
6980 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366981 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556982 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166983 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016984 request->Start();
6985 base::RunLoop().Run();
6986
6987 // Check that a report was not sent.
6988 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6989 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6990}
6991
estarka5da76702015-04-09 04:00:166992TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556993 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6994 https_test_server.ServeFilesFromSourceDirectory(
6995 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166996 ASSERT_TRUE(https_test_server.Start());
6997 // Make sure this test fails if the test server is changed to not
6998 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556999 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
7000 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167001
7002 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367003 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167004 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7005 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:167006 request->Start();
7007 base::RunLoop().Run();
7008
7009 TransportSecurityState* security_state =
7010 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407011 TransportSecurityState::PKPState pkp_state;
7012 EXPECT_FALSE(
7013 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:167014}
7015
dadriandf302c42016-06-10 18:48:597016TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
7017 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7018 https_test_server.SetSSLConfig(
7019 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7020 https_test_server.ServeFilesFromSourceDirectory(
7021 base::FilePath(kTestFilePath));
7022 ASSERT_TRUE(https_test_server.Start());
7023
7024 // Set up a MockCertVerifier to be a local root that violates the pin
7025 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7026 ASSERT_TRUE(cert);
7027
7028 MockCertVerifier cert_verifier;
7029 CertVerifyResult verify_result;
7030 verify_result.verified_cert = cert;
7031 verify_result.is_issued_by_known_root = false;
7032 HashValue hash;
7033 ASSERT_TRUE(
7034 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
7035 verify_result.public_key_hashes.push_back(hash);
7036 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7037 cert_verifier.set_default_result(OK);
7038
7039 std::string test_server_hostname = https_test_server.GetURL("/").host();
7040
7041 // Set up HPKP
7042 base::Time current_time = base::Time::Now();
7043 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
7044 HashValue pin;
7045 ASSERT_TRUE(
7046 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
7047 HashValueVector hashes;
7048 hashes.push_back(pin);
7049 GURL report_uri(kHPKPReportUri);
7050 TransportSecurityState security_state;
7051 security_state.AddHPKP(test_server_hostname, expiry,
7052 false, /* include subdomains */
7053 hashes, report_uri);
7054
7055 TestNetworkDelegate network_delegate;
7056 TestURLRequestContext context(true);
7057 context.set_transport_security_state(&security_state);
7058 context.set_network_delegate(&network_delegate);
7059 context.set_cert_verifier(&cert_verifier);
7060 context.Init();
7061
7062 TestDelegate d;
7063 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167064 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
7065 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:597066 request->Start();
7067 base::RunLoop().Run();
7068
7069 TransportSecurityState::PKPState pkp_state;
7070 EXPECT_TRUE(
7071 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
7072 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
7073}
7074
[email protected]242d8562012-10-30 21:20:467075TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:557076 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7077 https_test_server.SetSSLConfig(
7078 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7079 https_test_server.ServeFilesFromSourceDirectory(
7080 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:467081 ASSERT_TRUE(https_test_server.Start());
7082
tommycli59a63432015-11-06 00:10:557083 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167084
[email protected]242d8562012-10-30 21:20:467085 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367086 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557087 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167088 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197089 request->Start();
[email protected]255620da2013-08-19 13:14:297090 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:467091
7092 // We should have set parameters from the first header, not the second.
7093 TransportSecurityState* security_state =
7094 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407095 TransportSecurityState::STSState sts_state;
7096 EXPECT_TRUE(
7097 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7098 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7099 sts_state.upgrade_mode);
7100 EXPECT_FALSE(sts_state.include_subdomains);
7101 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:467102}
7103
[email protected]9f972ec2013-04-10 20:24:367104TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:557105 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7106 https_test_server.SetSSLConfig(
7107 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7108 https_test_server.ServeFilesFromSourceDirectory(
7109 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:367110 ASSERT_TRUE(https_test_server.Start());
7111
tommycli59a63432015-11-06 00:10:557112 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167113
[email protected]9f972ec2013-04-10 20:24:367114 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367115 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557116 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167117 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197118 request->Start();
[email protected]255620da2013-08-19 13:14:297119 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:367120
7121 // We should have set parameters from the first header, not the second.
7122 TransportSecurityState* security_state =
7123 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407124 TransportSecurityState::STSState sts_state;
7125 TransportSecurityState::PKPState pkp_state;
7126 EXPECT_TRUE(
7127 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7128 EXPECT_TRUE(
7129 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7130 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7131 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037132#if defined(OS_ANDROID)
7133 // Android's CertVerifyProc does not (yet) handle pins.
7134#else
martijnc0d6b622015-06-30 19:14:407135 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037136#endif
martijnc0d6b622015-06-30 19:14:407137 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:367138
[email protected]a165f092013-06-12 16:10:057139 // Even though there is an HSTS header asserting includeSubdomains, it is
7140 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:407141 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:057142 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:407143 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:367144}
7145
[email protected]37fd55fb2013-06-29 13:13:277146// Tests that when multiple HPKP headers are present, asserting different
7147// policies, that only the first such policy is processed.
7148TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:557149 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7150 https_test_server.SetSSLConfig(
7151 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7152 https_test_server.ServeFilesFromSourceDirectory(
7153 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:277154 ASSERT_TRUE(https_test_server.Start());
7155
tommycli59a63432015-11-06 00:10:557156 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:167157
[email protected]37fd55fb2013-06-29 13:13:277158 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367159 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557160 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:167161 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197162 request->Start();
[email protected]255620da2013-08-19 13:14:297163 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:277164
7165 TransportSecurityState* security_state =
7166 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:407167 TransportSecurityState::STSState sts_state;
7168 TransportSecurityState::PKPState pkp_state;
7169 EXPECT_TRUE(
7170 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
7171 EXPECT_TRUE(
7172 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
7173 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
7174 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:037175#if defined(OS_ANDROID)
7176 // Android's CertVerifyProc does not (yet) handle pins.
7177#else
martijnc0d6b622015-06-30 19:14:407178 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:037179#endif
martijnc0d6b622015-06-30 19:14:407180 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:277181
martijnc0d6b622015-06-30 19:14:407182 EXPECT_TRUE(sts_state.include_subdomains);
7183 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:277184}
7185
estark1614475f2016-03-10 03:46:477186// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
7187// called.
7188class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
7189 public:
7190 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:277191 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:477192
7193 void OnExpectCTFailed(const HostPortPair& host_port_pair,
7194 const GURL& report_uri,
estarkae028b462017-06-20 23:25:017195 base::Time expiration,
estarkbf1b52962017-05-05 17:05:257196 const X509Certificate* validated_certificate_chain,
7197 const X509Certificate* served_certificate_chain,
7198 const SignedCertificateTimestampAndStatusList&
7199 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:477200 num_failures_++;
7201 }
7202
7203 uint32_t num_failures() { return num_failures_; }
7204
7205 private:
7206 uint32_t num_failures_;
7207};
7208
Emily Stark627238f2017-11-29 03:29:547209// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:477210// for every certificate.
7211class MockCTPolicyEnforcer : public CTPolicyEnforcer {
7212 public:
7213 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:547214 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:277215 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:477216
Emily Stark627238f2017-11-29 03:29:547217 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:477218 X509Certificate* cert,
Ryan Sleevi8a9c9c12018-05-09 02:36:237219 const ct::SCTList& verified_scts,
tfarina42834112016-09-22 13:38:207220 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:477221 return default_result_;
7222 }
7223
Emily Stark627238f2017-11-29 03:29:547224 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:477225 default_result_ = default_result;
7226 }
7227
7228 private:
Emily Stark627238f2017-11-29 03:29:547229 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:477230};
7231
Emily Stark4cfecf072017-08-08 01:05:517232// Tests that Expect CT headers for the preload list are processed correctly.
7233TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:357234 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
7235
estark1614475f2016-03-10 03:46:477236 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7237 https_test_server.SetSSLConfig(
7238 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7239 https_test_server.ServeFilesFromSourceDirectory(
7240 base::FilePath(kTestFilePath));
7241 ASSERT_TRUE(https_test_server.Start());
7242
7243 MockExpectCTReporter reporter;
7244 TransportSecurityState transport_security_state;
7245 transport_security_state.enable_static_expect_ct_ = true;
7246 transport_security_state.SetExpectCTReporter(&reporter);
7247
7248 // Set up a MockCertVerifier to accept the certificate that the server sends.
7249 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7250 ASSERT_TRUE(cert);
7251 MockCertVerifier cert_verifier;
7252 CertVerifyResult verify_result;
7253 verify_result.verified_cert = cert;
7254 verify_result.is_issued_by_known_root = true;
7255 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7256
rsleevi22cae1672016-12-28 01:53:367257 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
7258 // CT violation.
7259 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:477260 MockCTPolicyEnforcer ct_policy_enforcer;
7261 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547262 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:477263
7264 TestNetworkDelegate network_delegate;
7265 // Use a MockHostResolver (which by default maps all hosts to
7266 // 127.0.0.1) so that the request can be sent to a site on the Expect
7267 // CT preload list.
7268 MockHostResolver host_resolver;
7269 TestURLRequestContext context(true);
7270 context.set_host_resolver(&host_resolver);
7271 context.set_transport_security_state(&transport_security_state);
7272 context.set_network_delegate(&network_delegate);
7273 context.set_cert_verifier(&cert_verifier);
7274 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:467275 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:477276 context.Init();
7277
7278 // Now send a request to trigger the violation.
7279 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:517280 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:477281 GURL::Replacements replace_host;
7282 replace_host.SetHostStr(kExpectCTStaticHostname);
7283 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:167284 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
7285 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:477286 violating_request->Start();
7287 base::RunLoop().Run();
7288
7289 EXPECT_EQ(1u, reporter.num_failures());
7290}
Emily Stark4cfecf072017-08-08 01:05:517291
7292// Tests that Expect CT HTTP headers are processed correctly.
7293TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
7294 base::test::ScopedFeatureList feature_list;
7295 feature_list.InitAndEnableFeature(
7296 TransportSecurityState::kDynamicExpectCTFeature);
7297
7298 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7299 https_test_server.SetSSLConfig(
7300 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7301 https_test_server.ServeFilesFromSourceDirectory(
7302 base::FilePath(kTestFilePath));
7303 ASSERT_TRUE(https_test_server.Start());
7304
7305 MockExpectCTReporter reporter;
7306 TransportSecurityState transport_security_state;
7307 transport_security_state.SetExpectCTReporter(&reporter);
7308
7309 // Set up a MockCertVerifier to accept the certificate that the server sends.
7310 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7311 ASSERT_TRUE(cert);
7312 MockCertVerifier cert_verifier;
7313 CertVerifyResult verify_result;
7314 verify_result.verified_cert = cert;
7315 verify_result.is_issued_by_known_root = true;
7316 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7317
7318 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7319 // compliance.
7320 DoNothingCTVerifier ct_verifier;
7321 MockCTPolicyEnforcer ct_policy_enforcer;
7322 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547323 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517324
7325 TestNetworkDelegate network_delegate;
7326 // Use a MockHostResolver (which by default maps all hosts to
7327 // 127.0.0.1).
7328 MockHostResolver host_resolver;
7329 TestURLRequestContext context(true);
7330 context.set_host_resolver(&host_resolver);
7331 context.set_transport_security_state(&transport_security_state);
7332 context.set_network_delegate(&network_delegate);
7333 context.set_cert_verifier(&cert_verifier);
7334 context.set_cert_transparency_verifier(&ct_verifier);
7335 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7336 context.Init();
7337
7338 // Now send a request to trigger the header processing.
7339 TestDelegate d;
7340 GURL url = https_test_server.GetURL("/expect-ct-header.html");
7341 std::unique_ptr<URLRequest> request(context.CreateRequest(
7342 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7343 request->Start();
7344 base::RunLoop().Run();
7345
7346 TransportSecurityState::ExpectCTState state;
7347 ASSERT_TRUE(
7348 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7349 EXPECT_TRUE(state.enforce);
7350 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7351}
7352
7353// Tests that if multiple Expect CT HTTP headers are sent, they are all
7354// processed.
7355TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
7356 base::test::ScopedFeatureList feature_list;
7357 feature_list.InitAndEnableFeature(
7358 TransportSecurityState::kDynamicExpectCTFeature);
7359
7360 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7361 https_test_server.SetSSLConfig(
7362 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7363 https_test_server.ServeFilesFromSourceDirectory(
7364 base::FilePath(kTestFilePath));
7365 ASSERT_TRUE(https_test_server.Start());
7366
7367 MockExpectCTReporter reporter;
7368 TransportSecurityState transport_security_state;
7369 transport_security_state.SetExpectCTReporter(&reporter);
7370
7371 // Set up a MockCertVerifier to accept the certificate that the server sends.
7372 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7373 ASSERT_TRUE(cert);
7374 MockCertVerifier cert_verifier;
7375 CertVerifyResult verify_result;
7376 verify_result.verified_cert = cert;
7377 verify_result.is_issued_by_known_root = true;
7378 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7379
7380 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7381 // compliance.
7382 DoNothingCTVerifier ct_verifier;
7383 MockCTPolicyEnforcer ct_policy_enforcer;
7384 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547385 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517386
7387 TestNetworkDelegate network_delegate;
7388 // Use a MockHostResolver (which by default maps all hosts to
7389 // 127.0.0.1).
7390 MockHostResolver host_resolver;
7391 TestURLRequestContext context(true);
7392 context.set_host_resolver(&host_resolver);
7393 context.set_transport_security_state(&transport_security_state);
7394 context.set_network_delegate(&network_delegate);
7395 context.set_cert_verifier(&cert_verifier);
7396 context.set_cert_transparency_verifier(&ct_verifier);
7397 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7398 context.Init();
7399
7400 // Now send a request to trigger the header processing.
7401 TestDelegate d;
7402 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7403 std::unique_ptr<URLRequest> request(context.CreateRequest(
7404 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7405 request->Start();
7406 base::RunLoop().Run();
7407
7408 TransportSecurityState::ExpectCTState state;
7409 ASSERT_TRUE(
7410 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7411 EXPECT_TRUE(state.enforce);
7412 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7413}
7414
mmenkefd9d15c2017-06-29 13:45:547415#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477416
mmenkefd9d15c2017-06-29 13:45:547417#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:417418namespace {
7419
7420class TestReportingService : public ReportingService {
7421 public:
7422 struct Header {
7423 GURL url;
7424 std::string header_value;
7425 };
7426
juliatuttle2b8dd2d12017-04-12 21:27:417427 const std::vector<Header>& headers() { return headers_; }
7428
juliatuttle1d92f0152017-04-28 17:19:217429 // ReportingService implementation:
7430
Chris Watkins7a41d3552017-12-01 02:13:277431 ~TestReportingService() override = default;
juliatuttle1d92f0152017-04-28 17:19:217432
juliatuttle2b8dd2d12017-04-12 21:27:417433 void QueueReport(const GURL& url,
7434 const std::string& group,
7435 const std::string& type,
Julia Tuttle107e30672018-03-29 18:48:427436 std::unique_ptr<const base::Value> body,
7437 int depth) override {
juliatuttle2b8dd2d12017-04-12 21:27:417438 NOTIMPLEMENTED();
7439 }
7440
7441 void ProcessHeader(const GURL& url,
7442 const std::string& header_value) override {
7443 headers_.push_back({url, header_value});
7444 }
7445
Julia Tuttle227a6ff2017-12-19 19:44:247446 void RemoveBrowsingData(int data_type_mask,
7447 const base::RepeatingCallback<bool(const GURL&)>&
7448 origin_filter) override {
juliatuttleaeb1abc2017-05-04 21:14:387449 NOTIMPLEMENTED();
7450 }
7451
Eric Orthb812a442018-05-04 20:26:487452 void RemoveAllBrowsingData(int data_type_mask) override { NOTIMPLEMENTED(); }
7453
Julia Tuttle107e30672018-03-29 18:48:427454 int GetUploadDepth(const URLRequest& request) override {
Julia Tuttle4667c1c2017-12-19 18:27:387455 NOTIMPLEMENTED();
Julia Tuttle107e30672018-03-29 18:48:427456 return 0;
Julia Tuttle4667c1c2017-12-19 18:27:387457 }
7458
Julia Tuttle91a655d2018-01-26 18:03:037459 const ReportingPolicy& GetPolicy() const override {
7460 static ReportingPolicy dummy_policy_;
7461 NOTIMPLEMENTED();
7462 return dummy_policy_;
7463 }
7464
juliatuttle2b8dd2d12017-04-12 21:27:417465 private:
7466 std::vector<Header> headers_;
7467};
7468
7469std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7470 const test_server::HttpRequest& request) {
7471 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7472 new test_server::BasicHttpResponse);
7473 http_response->set_code(HTTP_OK);
7474 http_response->AddCustomHeader("Report-To", "foo");
7475 http_response->AddCustomHeader("Report-To", "bar");
7476 return std::move(http_response);
7477}
7478
7479} // namespace
7480
7481TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
Julia Tuttle7005a2a2017-12-08 21:01:187482 http_test_server()->RegisterRequestHandler(
7483 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417484 ASSERT_TRUE(http_test_server()->Start());
7485 GURL request_url = http_test_server()->GetURL("/");
7486
7487 TestNetworkDelegate network_delegate;
7488 TestURLRequestContext context(true);
7489 context.set_network_delegate(&network_delegate);
7490 context.Init();
7491
7492 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167493 std::unique_ptr<URLRequest> request(context.CreateRequest(
7494 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417495 request->Start();
7496 base::RunLoop().Run();
7497}
7498
7499TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
Julia Tuttle7005a2a2017-12-08 21:01:187500 http_test_server()->RegisterRequestHandler(
7501 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417502 ASSERT_TRUE(http_test_server()->Start());
7503 GURL request_url = http_test_server()->GetURL("/");
7504
7505 TestNetworkDelegate network_delegate;
7506 TestReportingService reporting_service;
7507 TestURLRequestContext context(true);
7508 context.set_network_delegate(&network_delegate);
7509 context.set_reporting_service(&reporting_service);
7510 context.Init();
7511
7512 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167513 std::unique_ptr<URLRequest> request(context.CreateRequest(
7514 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417515 request->Start();
7516 base::RunLoop().Run();
7517
7518 EXPECT_TRUE(reporting_service.headers().empty());
7519}
7520
7521TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7522 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187523 https_test_server.RegisterRequestHandler(
7524 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417525 ASSERT_TRUE(https_test_server.Start());
7526 GURL request_url = https_test_server.GetURL("/");
7527
7528 TestNetworkDelegate network_delegate;
7529 TestReportingService reporting_service;
7530 TestURLRequestContext context(true);
7531 context.set_network_delegate(&network_delegate);
7532 context.set_reporting_service(&reporting_service);
7533 context.Init();
7534
7535 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167536 std::unique_ptr<URLRequest> request(context.CreateRequest(
7537 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417538 request->Start();
7539 base::RunLoop().Run();
7540
7541 ASSERT_EQ(1u, reporting_service.headers().size());
7542 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7543 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7544}
7545
Julia Tuttlef9b74062017-07-27 14:44:057546TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417547 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7548 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187549 https_test_server.RegisterRequestHandler(
7550 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417551 ASSERT_TRUE(https_test_server.Start());
7552 GURL request_url = https_test_server.GetURL("/");
7553
7554 TestNetworkDelegate network_delegate;
7555 TestReportingService reporting_service;
7556 TestURLRequestContext context(true);
7557 context.set_network_delegate(&network_delegate);
7558 context.set_reporting_service(&reporting_service);
7559 context.Init();
7560
7561 TestDelegate d;
7562 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167563 std::unique_ptr<URLRequest> request(context.CreateRequest(
7564 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417565 request->Start();
7566 base::RunLoop().Run();
7567
7568 EXPECT_TRUE(d.have_certificate_errors());
7569 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7570 EXPECT_TRUE(reporting_service.headers().empty());
7571}
Julia Tuttlefadc26d2017-10-13 18:12:297572
7573// Network Error Logging is dependent on the Reporting API, so only run NEL
7574// tests if Reporting is enabled in the build.
tommycli59a63432015-11-06 00:10:557575
Julia Tuttlef9b74062017-07-27 14:44:057576namespace {
7577
Julia Tuttlecba7d222018-02-23 19:37:277578class TestNetworkErrorLoggingService : public NetworkErrorLoggingService {
Julia Tuttlef9b74062017-07-27 14:44:057579 public:
7580 struct Header {
Chris Watkins7a41d3552017-12-01 02:13:277581 Header() = default;
7582 ~Header() = default;
Julia Tuttlef9b74062017-07-27 14:44:057583
7584 url::Origin origin;
7585 std::string value;
7586 };
7587
Julia Tuttlef9b74062017-07-27 14:44:057588 const std::vector<Header>& headers() { return headers_; }
Douglas Creager1f56bbe2018-02-17 03:58:407589 const std::vector<RequestDetails>& errors() { return errors_; }
Julia Tuttlef9b74062017-07-27 14:44:057590
Julia Tuttlecba7d222018-02-23 19:37:277591 // NetworkErrorLoggingService implementation:
Julia Tuttlef9b74062017-07-27 14:44:057592
Julia Tuttlecba7d222018-02-23 19:37:277593 ~TestNetworkErrorLoggingService() override = default;
Julia Tuttlef9b74062017-07-27 14:44:057594
7595 void OnHeader(const url::Origin& origin, const std::string& value) override {
7596 Header header;
7597 header.origin = origin;
7598 header.value = value;
7599 headers_.push_back(header);
7600 }
7601
Douglas Creager1f56bbe2018-02-17 03:58:407602 void OnRequest(const RequestDetails& details) override {
Julia Tuttleb0d45472017-09-25 20:14:437603 errors_.push_back(details);
Julia Tuttlef9b74062017-07-27 14:44:057604 }
7605
Julia Tuttlea059db82018-01-04 18:46:437606 void RemoveBrowsingData(const base::RepeatingCallback<bool(const GURL&)>&
7607 origin_filter) override {
7608 NOTREACHED();
7609 }
7610
Julia Tuttlef9b74062017-07-27 14:44:057611 private:
7612 std::vector<Header> headers_;
Douglas Creager1f56bbe2018-02-17 03:58:407613 std::vector<RequestDetails> errors_;
Julia Tuttlef9b74062017-07-27 14:44:057614};
7615
7616std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7617 const test_server::HttpRequest& request) {
7618 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7619 new test_server::BasicHttpResponse);
7620 http_response->set_code(HTTP_OK);
Julia Tuttlecba7d222018-02-23 19:37:277621 http_response->AddCustomHeader(NetworkErrorLoggingService::kHeaderName,
Julia Tuttlef9b74062017-07-27 14:44:057622 "foo");
7623 return std::move(http_response);
7624}
7625
Julia Tuttle7005a2a2017-12-08 21:01:187626std::unique_ptr<test_server::HttpResponse> SendEmptyResponse(
7627 const test_server::HttpRequest& request) {
Gyuyoung Kimb480aba2018-01-27 07:00:047628 return std::make_unique<test_server::RawHttpResponse>("", "");
Julia Tuttle7005a2a2017-12-08 21:01:187629}
7630
Julia Tuttlef9b74062017-07-27 14:44:057631} // namespace
7632
7633TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
Julia Tuttle7005a2a2017-12-08 21:01:187634 http_test_server()->RegisterRequestHandler(
7635 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057636 ASSERT_TRUE(http_test_server()->Start());
7637 GURL request_url = http_test_server()->GetURL("/");
7638
7639 TestNetworkDelegate network_delegate;
7640 TestURLRequestContext context(true);
7641 context.set_network_delegate(&network_delegate);
7642 context.Init();
7643
7644 TestDelegate d;
7645 std::unique_ptr<URLRequest> request(context.CreateRequest(
7646 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7647 request->Start();
7648 base::RunLoop().Run();
7649}
7650
7651TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
Julia Tuttle7005a2a2017-12-08 21:01:187652 http_test_server()->RegisterRequestHandler(
7653 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057654 ASSERT_TRUE(http_test_server()->Start());
7655 GURL request_url = http_test_server()->GetURL("/");
7656
7657 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277658 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057659 TestURLRequestContext context(true);
7660 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277661 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057662 context.Init();
7663
7664 TestDelegate d;
7665 std::unique_ptr<URLRequest> request(context.CreateRequest(
7666 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7667 request->Start();
7668 base::RunLoop().Run();
7669
Julia Tuttlecba7d222018-02-23 19:37:277670 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057671}
7672
7673TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7674 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187675 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057676 ASSERT_TRUE(https_test_server.Start());
7677 GURL request_url = https_test_server.GetURL("/");
7678
7679 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277680 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057681 TestURLRequestContext context(true);
7682 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277683 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057684 context.Init();
7685
7686 TestDelegate d;
7687 std::unique_ptr<URLRequest> request(context.CreateRequest(
7688 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7689 request->Start();
7690 base::RunLoop().Run();
7691
Julia Tuttlecba7d222018-02-23 19:37:277692 ASSERT_EQ(1u, nel_service.headers().size());
7693 EXPECT_EQ(url::Origin::Create(request_url), nel_service.headers()[0].origin);
7694 EXPECT_EQ("foo", nel_service.headers()[0].value);
Julia Tuttlef9b74062017-07-27 14:44:057695}
7696
7697TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7698 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7699 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187700 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057701 ASSERT_TRUE(https_test_server.Start());
7702 GURL request_url = https_test_server.GetURL("/");
7703
7704 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277705 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057706 TestURLRequestContext context(true);
7707 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277708 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057709 context.Init();
7710
7711 TestDelegate d;
7712 d.set_allow_certificate_errors(true);
7713 std::unique_ptr<URLRequest> request(context.CreateRequest(
7714 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7715 request->Start();
7716 base::RunLoop().Run();
7717
7718 EXPECT_TRUE(d.have_certificate_errors());
7719 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
Julia Tuttlecba7d222018-02-23 19:37:277720 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057721}
7722
Julia Tuttlefadc26d2017-10-13 18:12:297723TEST_F(URLRequestTestHTTP, DontForwardErrorToNelNoDelegate) {
7724 URLRequestFailedJob::AddUrlHandler();
7725
7726 GURL request_url =
7727 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7728
7729 TestNetworkDelegate network_delegate;
7730 TestURLRequestContext context(true);
7731 context.set_network_delegate(&network_delegate);
7732 context.Init();
7733
7734 TestDelegate d;
7735 std::unique_ptr<URLRequest> request(context.CreateRequest(
7736 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7737 request->Start();
7738 base::RunLoop().Run();
7739
7740 URLRequestFilter::GetInstance()->ClearHandlers();
7741}
7742
7743// TODO(juliatuttle): Figure out whether this restriction should be in place,
7744// and either implement it or remove this test.
7745TEST_F(URLRequestTestHTTP, DISABLED_DontForwardErrorToNelHttp) {
7746 URLRequestFailedJob::AddUrlHandler();
7747
7748 GURL request_url =
7749 URLRequestFailedJob::GetMockHttpUrl(ERR_CONNECTION_REFUSED);
7750
7751 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277752 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297753 TestURLRequestContext context(true);
7754 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277755 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297756 context.Init();
7757
7758 TestDelegate d;
7759 std::unique_ptr<URLRequest> request(context.CreateRequest(
7760 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7761 request->Start();
7762 base::RunLoop().Run();
7763
Julia Tuttlecba7d222018-02-23 19:37:277764 EXPECT_TRUE(nel_service.errors().empty());
Julia Tuttlefadc26d2017-10-13 18:12:297765
7766 URLRequestFilter::GetInstance()->ClearHandlers();
7767}
7768
Julia Tuttle7005a2a2017-12-08 21:01:187769TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Mock) {
Julia Tuttlefadc26d2017-10-13 18:12:297770 URLRequestFailedJob::AddUrlHandler();
7771
7772 GURL request_url =
7773 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7774
7775 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277776 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297777 TestURLRequestContext context(true);
7778 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277779 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297780 context.Init();
7781
7782 TestDelegate d;
7783 std::unique_ptr<URLRequest> request(context.CreateRequest(
7784 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7785 request->Start();
7786 base::RunLoop().Run();
7787
Julia Tuttlecba7d222018-02-23 19:37:277788 ASSERT_EQ(1u, nel_service.errors().size());
7789 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7790 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7791 EXPECT_EQ(ERR_CONNECTION_REFUSED, nel_service.errors()[0].type);
Julia Tuttlefadc26d2017-10-13 18:12:297792
7793 URLRequestFilter::GetInstance()->ClearHandlers();
7794}
7795
Julia Tuttle7005a2a2017-12-08 21:01:187796// Also test with a real server, to exercise interactions with
7797// URLRequestHttpJob.
7798TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Real) {
7799 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7800 https_test_server.RegisterRequestHandler(
7801 base::BindRepeating(&SendEmptyResponse));
7802 ASSERT_TRUE(https_test_server.Start());
7803 GURL request_url = https_test_server.GetURL("/");
7804
7805 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277806 TestNetworkErrorLoggingService nel_service;
Julia Tuttle7005a2a2017-12-08 21:01:187807 TestURLRequestContext context(true);
7808 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277809 context.set_network_error_logging_service(&nel_service);
Julia Tuttle7005a2a2017-12-08 21:01:187810 context.Init();
7811
7812 TestDelegate d;
7813 std::unique_ptr<URLRequest> request(context.CreateRequest(
7814 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7815 request->Start();
7816 base::RunLoop().Run();
7817
Julia Tuttlecba7d222018-02-23 19:37:277818 ASSERT_EQ(1u, nel_service.errors().size());
7819 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7820 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7821 EXPECT_EQ(ERR_EMPTY_RESPONSE, nel_service.errors()[0].type);
Julia Tuttle7005a2a2017-12-08 21:01:187822}
7823
Julia Tuttlefadc26d2017-10-13 18:12:297824#endif // BUILDFLAG(ENABLE_REPORTING)
7825
[email protected]316c1e5e2012-09-12 15:17:447826TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557827 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447828
7829 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367830 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557831 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167832 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197833 req->Start();
[email protected]255620da2013-08-19 13:14:297834 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447835
7836 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197837 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447838 EXPECT_EQ("text/html", mime_type);
7839
7840 std::string charset;
[email protected]f7022f32014-08-21 16:32:197841 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447842 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197843 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447844}
7845
[email protected]02494ec2014-05-07 15:05:297846TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347847 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347848 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347849 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027850 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347851
7852 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507853 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347854}
7855
brettwa1228ebb2016-10-28 03:51:347856#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297857TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7858 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7859 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457860 FileProtocolHandler file_protocol_handler(
7861 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297862 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7863
7864 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507865 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297866}
7867
[email protected]588614c22013-08-16 00:09:027868TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557869 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447870
7871 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367872 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557873 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167874 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197875 req->Start();
[email protected]255620da2013-08-19 13:14:297876 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447877
maksim.sisovb53724b52016-09-16 05:30:507878 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307879
7880 // The redirect should have been rejected before reporting it to the caller.
7881 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447882}
brettwa1228ebb2016-10-28 03:51:347883#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447884
[email protected]588614c22013-08-16 00:09:027885TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557886 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027887
7888 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367889 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557890 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167891 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197892 req->Start();
fdoray5eeb7642016-06-22 16:11:287893 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:027894
maksim.sisovb53724b52016-09-16 05:30:507895 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307896
7897 // The redirect should have been rejected before reporting it to the
7898 // caller. See https://crbug.com/723796
7899 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027900}
7901
davidbend894710b2017-06-06 19:28:307902// Test that redirects to invalid URLs are rejected. See
7903// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447904TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557905 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447906
7907 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367908 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557909 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167910 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197911 req->Start();
[email protected]255620da2013-08-19 13:14:297912 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447913
davidbend894710b2017-06-06 19:28:307914 EXPECT_EQ(1, d.response_started_count());
7915 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7916
7917 // The redirect should have been rejected before reporting it to the caller.
7918 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447919}
7920
[email protected]e50efea2014-03-24 18:41:007921// Make sure redirects are cached, despite not reading their bodies.
7922TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557923 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007924 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557925 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007926
7927 {
7928 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167929 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7930 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197931 req->Start();
[email protected]e50efea2014-03-24 18:41:007932 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507933 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007934 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557935 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007936 }
7937
7938 {
7939 TestDelegate d;
7940 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167941 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7942 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197943 req->Start();
[email protected]e50efea2014-03-24 18:41:007944 base::RunLoop().Run();
7945
7946 EXPECT_EQ(1, d.received_redirect_count());
7947 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197948 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007949
[email protected]f7022f32014-08-21 16:32:197950 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:007951 base::RunLoop().Run();
7952 EXPECT_EQ(1, d.received_redirect_count());
7953 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507954 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557955 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007956 }
7957}
7958
7959// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7960// when the headers are read, since the body won't have been read.
7961TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557962 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007963 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557964 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007965
7966 {
7967 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557968 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007969 default_network_delegate_.set_redirect_on_headers_received_url(
7970 redirect_to_url);
7971
7972 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167973 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7974 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197975 req->Start();
[email protected]e50efea2014-03-24 18:41:007976 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507977 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007978 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197979 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007980 }
7981
7982 {
7983 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167984 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7985 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197986 req->Start();
[email protected]e50efea2014-03-24 18:41:007987 base::RunLoop().Run();
7988
maksim.sisovb53724b52016-09-16 05:30:507989 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197990 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007991 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197992 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007993 }
7994}
7995
[email protected]5f714132014-03-26 10:41:167996// Tests that redirection to an unsafe URL is allowed when it has been marked as
7997// safe.
7998TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557999 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168000
8001 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
8002 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8003 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8004
8005 TestDelegate d;
8006 {
danakj8522a25b2016-04-16 00:17:368007 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168008 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8009 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168010
[email protected]f7022f32014-08-21 16:32:198011 r->Start();
[email protected]5f714132014-03-26 10:41:168012 base::RunLoop().Run();
8013
maksim.sisovb53724b52016-09-16 05:30:508014 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198015 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:198016 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:168017 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
8018 }
8019}
8020
8021// Tests that a redirect to a different unsafe URL is blocked, even after adding
8022// some other URL to the whitelist.
8023TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:558024 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168025
8026 GURL unsafe_url("data:text/html,something");
8027 GURL different_unsafe_url("data:text/html,something-else");
8028 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8029 default_network_delegate_.set_allowed_unsafe_redirect_url(
8030 different_unsafe_url);
8031
8032 TestDelegate d;
8033 {
danakj8522a25b2016-04-16 00:17:368034 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168035 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
8036 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168037
[email protected]f7022f32014-08-21 16:32:198038 r->Start();
[email protected]5f714132014-03-26 10:41:168039 base::RunLoop().Run();
8040
maksim.sisovb53724b52016-09-16 05:30:508041 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:308042
8043 // The redirect should have been rejected before reporting it to the caller.
8044 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:168045 }
8046}
8047
[email protected]5f714132014-03-26 10:41:168048// Redirects from an URL with fragment to an unsafe URL with fragment should
8049// be allowed, and the reference fragment of the target URL should be preserved.
8050TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:558051 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168052
tommycli59a63432015-11-06 00:10:558053 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:168054 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8055 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
8056
8057 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
8058 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8059
8060 TestDelegate d;
8061 {
rhalavatib7bd7c792017-04-27 05:25:168062 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8063 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168064
[email protected]f7022f32014-08-21 16:32:198065 r->Start();
[email protected]5f714132014-03-26 10:41:168066 base::RunLoop().Run();
8067
[email protected]f7022f32014-08-21 16:32:198068 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508069 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198070 EXPECT_EQ(original_url, r->original_url());
8071 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:168072 }
8073}
8074
8075// When a delegate has specified a safe redirect URL, but it does not match the
8076// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:148077TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:558078 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:168079
tommycli59a63432015-11-06 00:10:558080 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168081 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:558082 GURL redirect_url(http_test_server()->GetURL("/target"));
8083 GURL expected_redirect_url(
8084 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:168085
8086 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8087 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
8088
8089 TestDelegate d;
8090 {
rhalavatib7bd7c792017-04-27 05:25:168091 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8092 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:168093
[email protected]f7022f32014-08-21 16:32:198094 r->Start();
[email protected]5f714132014-03-26 10:41:168095 base::RunLoop().Run();
8096
[email protected]f7022f32014-08-21 16:32:198097 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508098 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198099 EXPECT_EQ(original_url, r->original_url());
8100 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:168101 }
8102}
8103
[email protected]f878230e2014-04-03 15:36:148104// When a delegate has specified a safe redirect URL, assume that the redirect
8105// URL should not be changed. In particular, the reference fragment should not
8106// be modified.
8107TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558108 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148109
tommycli59a63432015-11-06 00:10:558110 GURL original_url(
8111 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:148112 GURL redirect_url("data:text/html,expect-no-reference-fragment");
8113
8114 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
8115 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
8116
8117 TestDelegate d;
8118 {
rhalavatib7bd7c792017-04-27 05:25:168119 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8120 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148121
[email protected]f7022f32014-08-21 16:32:198122 r->Start();
[email protected]f878230e2014-04-03 15:36:148123 base::RunLoop().Run();
8124
[email protected]f7022f32014-08-21 16:32:198125 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508126 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198127 EXPECT_EQ(original_url, r->original_url());
8128 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148129 }
8130}
8131
8132// When a URLRequestRedirectJob is created, the redirection must be followed and
8133// the reference fragment of the target URL must not be modified.
8134TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:558135 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148136
tommycli59a63432015-11-06 00:10:558137 GURL original_url(
8138 http_test_server()->GetURL("/original#should-not-be-appended"));
8139 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:148140
8141 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:168142 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8143 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148144
danakj8522a25b2016-04-16 00:17:368145 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:198146 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:428147 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8148 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:148149
[email protected]f7022f32014-08-21 16:32:198150 r->Start();
[email protected]f878230e2014-04-03 15:36:148151 base::RunLoop().Run();
8152
maksim.sisovb53724b52016-09-16 05:30:508153 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198154 EXPECT_EQ(original_url, r->original_url());
8155 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:148156}
8157
lizeb5120f6dc2016-02-19 09:29:448158TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
8159 ASSERT_TRUE(http_test_server()->Start());
8160
8161 const std::string referrer("foobar://totally.legit.referrer");
8162 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368163 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168164 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8165 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:448166 req->SetReferrer(referrer);
8167 req->Start();
8168 base::RunLoop().Run();
8169
8170 EXPECT_EQ(std::string("None"), d.data_received());
8171}
8172
[email protected]316c1e5e2012-09-12 15:17:448173TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:558174 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448175
8176 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368177 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168178 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8179 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198180 req->SetReferrer("http://user:[email protected]/");
8181 req->Start();
[email protected]255620da2013-08-19 13:14:298182 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448183
8184 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
8185}
8186
[email protected]99ecf6e2013-04-10 22:46:138187TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:558188 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138189
8190 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368191 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168192 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8193 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198194 req->SetReferrer("http://foo.com/test#fragment");
8195 req->Start();
[email protected]255620da2013-08-19 13:14:298196 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:138197
8198 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
8199}
8200
8201TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:558202 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:138203
8204 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368205 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168206 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
8207 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198208 req->SetReferrer("http://foo.com/test#fragment");
8209 req->SetReferrer("");
8210 req->Start();
[email protected]255620da2013-08-19 13:14:298211 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:138212
8213 EXPECT_EQ(std::string("None"), d.data_received());
8214}
8215
[email protected]316c1e5e2012-09-12 15:17:448216TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:558217 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448218
8219 TestDelegate d;
8220 {
8221 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:368222 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168223 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8224 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198225 req->Start();
[email protected]255620da2013-08-19 13:14:298226 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448227
8228 EXPECT_EQ(1, d.response_started_count());
8229 EXPECT_EQ(0, d.bytes_received());
8230 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508231 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448232 }
8233}
8234
8235TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:558236 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448237
8238 TestDelegate d;
8239 {
8240 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558241 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168242 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8243 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048244
[email protected]f7022f32014-08-21 16:32:198245 req->Start();
[email protected]255620da2013-08-19 13:14:298246 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448247
8248 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:238249 EXPECT_TRUE(d.have_full_request_headers());
8250 CheckFullRequestHeaders(d.full_request_headers(), test_url);
8251 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:448252
[email protected]f7022f32014-08-21 16:32:198253 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:298254 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448255
8256 EXPECT_EQ(1, d.response_started_count());
8257 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508258 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448259
[email protected]6cdfd7f2013-02-08 20:40:158260 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198261 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478262 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:448263 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8264
8265 std::string contents;
[email protected]82f84b92013-08-30 18:23:508266 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:448267 EXPECT_EQ(contents, d.data_received());
8268 }
8269}
8270
[email protected]79e1fd62013-06-20 06:50:048271TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:558272 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:048273
8274 TestDelegate d;
8275 {
8276 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:558277 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:168278 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8279 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:048280
8281 EXPECT_FALSE(d.have_full_request_headers());
8282
[email protected]f7022f32014-08-21 16:32:198283 req->Start();
[email protected]255620da2013-08-19 13:14:298284 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:048285
8286 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:048287
[email protected]f7022f32014-08-21 16:32:198288 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:298289 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:048290
tommycli59a63432015-11-06 00:10:558291 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:048292 EXPECT_EQ(1, d.response_started_count());
8293 EXPECT_TRUE(d.have_full_request_headers());
8294 CheckFullRequestHeaders(d.full_request_headers(), target_url);
8295 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508296 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:048297
8298 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:198299 base::PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:478300 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:048301 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
8302
8303 std::string contents;
[email protected]82f84b92013-08-30 18:23:508304 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:048305 EXPECT_EQ(contents, d.data_received());
8306 }
8307}
8308
[email protected]316c1e5e2012-09-12 15:17:448309TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:558310 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448311
8312 TestDelegate d;
8313 {
8314 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:368315 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168316 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8317 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198318 req->Start();
[email protected]255620da2013-08-19 13:14:298319 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448320
8321 EXPECT_EQ(1, d.received_redirect_count());
8322
[email protected]f7022f32014-08-21 16:32:198323 req->Cancel();
[email protected]255620da2013-08-19 13:14:298324 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448325
8326 EXPECT_EQ(1, d.response_started_count());
8327 EXPECT_EQ(0, d.bytes_received());
8328 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:508329 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:448330 }
8331}
8332
8333TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:558334 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448335
[email protected]3b23a222013-05-15 21:33:258336 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:448337 {
8338 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368339 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558340 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168341 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448342 HttpRequestHeaders headers;
8343 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198344 req->SetExtraRequestHeaders(headers);
8345 req->Start();
[email protected]255620da2013-08-19 13:14:298346 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:258347
8348 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198349 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258350 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448351 }
8352
[email protected]3b23a222013-05-15 21:33:258353 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:448354 {
8355 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368356 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558357 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168358 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448359 HttpRequestHeaders headers;
8360 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198361 req->SetExtraRequestHeaders(headers);
8362 req->Start();
[email protected]255620da2013-08-19 13:14:298363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448364
[email protected]f7022f32014-08-21 16:32:198365 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258366
8367 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198368 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258369 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448370 }
8371
[email protected]3b23a222013-05-15 21:33:258372 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448373 {
8374 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368375 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558376 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168377 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448378 HttpRequestHeaders headers;
8379 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198380 req->SetExtraRequestHeaders(headers);
8381 req->Start();
[email protected]255620da2013-08-19 13:14:298382 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448383
[email protected]f7022f32014-08-21 16:32:198384 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258385
8386 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198387 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258388 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448389 }
8390}
8391
8392TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558393 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448394
8395 // populate the cache
8396 {
8397 TestDelegate d;
8398 d.set_credentials(AuthCredentials(kUser, kSecret));
8399
danakj8522a25b2016-04-16 00:17:368400 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168401 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8402 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198403 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448404
[email protected]255620da2013-08-19 13:14:298405 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448406
8407 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8408 }
8409
8410 // repeat request with end-to-end validation. since auth-basic results in a
8411 // cachable page, we expect this test to result in a 304. in which case, the
8412 // response should be fetched from the cache.
8413 {
8414 TestDelegate d;
8415 d.set_credentials(AuthCredentials(kUser, kSecret));
8416
danakj8522a25b2016-04-16 00:17:368417 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168418 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8419 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198420 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8421 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448422
[email protected]255620da2013-08-19 13:14:298423 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448424
8425 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8426
8427 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198428 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448429 }
8430}
8431
8432// Check that Set-Cookie headers in 401 responses are respected.
8433// http://crbug.com/6450
8434TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558435 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448436
8437 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558438 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448439
8440 // Request a page that will give a 401 containing a Set-Cookie header.
8441 // Verify that when the transaction is restarted, it includes the new cookie.
8442 {
[email protected]ceefd7fd2012-11-29 00:36:248443 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448444 TestURLRequestContext context(true);
8445 context.set_network_delegate(&network_delegate);
8446 context.Init();
8447
8448 TestDelegate d;
8449 d.set_credentials(AuthCredentials(kUser, kSecret));
8450
danakj8522a25b2016-04-16 00:17:368451 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168452 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8453 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198454 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448455
[email protected]255620da2013-08-19 13:14:298456 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448457
8458 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8459
8460 // Make sure we sent the cookie in the restarted transaction.
8461 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8462 != std::string::npos);
8463 }
8464
8465 // Same test as above, except this time the restart is initiated earlier
8466 // (without user intervention since identity is embedded in the URL).
8467 {
[email protected]ceefd7fd2012-11-29 00:36:248468 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448469 TestURLRequestContext context(true);
8470 context.set_network_delegate(&network_delegate);
8471 context.Init();
8472
8473 TestDelegate d;
8474
8475 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188476 replacements.SetUsernameStr("user2");
8477 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448478 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8479
rhalavatib7bd7c792017-04-27 05:25:168480 std::unique_ptr<URLRequest> r(context.CreateRequest(
8481 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198482 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448483
[email protected]255620da2013-08-19 13:14:298484 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448485
8486 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8487
8488 // Make sure we sent the cookie in the restarted transaction.
8489 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8490 != std::string::npos);
8491 }
8492}
8493
[email protected]58e32bb2013-01-21 18:23:258494// Tests that load timing works as expected with auth and the cache.
8495TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558496 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258497
8498 // populate the cache
8499 {
8500 TestDelegate d;
8501 d.set_credentials(AuthCredentials(kUser, kSecret));
8502
danakj8522a25b2016-04-16 00:17:368503 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168504 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8505 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198506 r->Start();
[email protected]58e32bb2013-01-21 18:23:258507
[email protected]255620da2013-08-19 13:14:298508 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258509
8510 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8511
8512 LoadTimingInfo load_timing_info_before_auth;
8513 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8514 &load_timing_info_before_auth));
8515 TestLoadTimingNotReused(load_timing_info_before_auth,
8516 CONNECT_TIMING_HAS_DNS_TIMES);
8517
8518 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198519 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258520 // The test server does not support keep alive sockets, so the second
8521 // request with auth should use a new socket.
8522 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8523 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8524 load_timing_info.socket_log_id);
8525 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8526 load_timing_info.connect_timing.connect_start);
8527 }
8528
[email protected]3b23a222013-05-15 21:33:258529 // Repeat request with end-to-end validation. Since auth-basic results in a
8530 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258531 // response should be fetched from the cache.
8532 {
8533 TestDelegate d;
8534 d.set_credentials(AuthCredentials(kUser, kSecret));
8535
danakj8522a25b2016-04-16 00:17:368536 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168537 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8538 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198539 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8540 r->Start();
[email protected]58e32bb2013-01-21 18:23:258541
[email protected]255620da2013-08-19 13:14:298542 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258543
8544 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8545
8546 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198547 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258548
[email protected]3b23a222013-05-15 21:33:258549 // Since there was a request that went over the wire, the load timing
8550 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258551 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198552 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258553 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258554 }
8555}
8556
[email protected]316c1e5e2012-09-12 15:17:448557// In this test, we do a POST which the server will 302 redirect.
8558// The subsequent transaction should use GET, and should not send the
8559// Content-Type header.
8560// http://code.google.com/p/chromium/issues/detail?id=843
8561TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558562 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448563
8564 const char kData[] = "hello world";
8565
8566 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368567 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168568 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8569 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198570 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078571 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448572
8573 // Set headers (some of which are specific to the POST).
8574 HttpRequestHeaders headers;
8575 headers.AddHeadersFromString(
8576 "Content-Type: multipart/form-data; "
8577 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8578 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8579 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8580 "Accept-Language: en-US,en\r\n"
8581 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8582 "Content-Length: 11\r\n"
8583 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198584 req->SetExtraRequestHeaders(headers);
8585 req->Start();
[email protected]255620da2013-08-19 13:14:298586 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448587
8588 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198589 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448590 EXPECT_EQ("text/html", mime_type);
8591
8592 const std::string& data = d.data_received();
8593
8594 // Check that the post-specific headers were stripped:
8595 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8596 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498597 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448598
8599 // These extra request headers should not have been stripped.
8600 EXPECT_TRUE(ContainsString(data, "Accept:"));
8601 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8602 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8603}
8604
jww5fe460ff2015-03-28 00:22:518605// The following tests check that we handle mutating the request for HTTP
8606// redirects as expected.
8607// See https://crbug.com/56373, https://crbug.com/102130, and
8608// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448609
8610TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558611 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448612
tommycli59a63432015-11-06 00:10:558613 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518614 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558615 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448616
8617 HTTPRedirectMethodTest(url, "POST", "GET", true);
8618 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8619 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518620
8621 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8622 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498623 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8624 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8625 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408626 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8627 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448628}
8629
8630TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558631 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448632
tommycli59a63432015-11-06 00:10:558633 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518634 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558635 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448636
8637 HTTPRedirectMethodTest(url, "POST", "GET", true);
8638 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8639 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518640
8641 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8642 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498643 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8644 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8645 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408646 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8647 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448648}
8649
8650TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558651 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448652
tommycli59a63432015-11-06 00:10:558653 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518654 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558655 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448656
8657 HTTPRedirectMethodTest(url, "POST", "GET", true);
8658 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8659 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518660
Alex Clarke1e08882b32017-10-06 14:22:408661 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8662 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8663 std::string());
8664 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8665 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8666 std::string());
jww5fe460ff2015-03-28 00:22:518667 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8668 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408669 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8670 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8671 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8672 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8673 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498674 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8675 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8676 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408677 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8678 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448679}
8680
8681TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558682 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448683
tommycli59a63432015-11-06 00:10:558684 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518685 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558686 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448687
8688 HTTPRedirectMethodTest(url, "POST", "POST", true);
8689 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8690 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518691
8692 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8693 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8694 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8695 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408696 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8697 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448698}
8699
[email protected]0a17aab32014-04-24 03:32:378700TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558701 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378702
tommycli59a63432015-11-06 00:10:558703 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518704 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558705 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378706
8707 HTTPRedirectMethodTest(url, "POST", "POST", true);
8708 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8709 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518710
8711 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8712 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8713 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8714 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408715 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8716 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378717}
8718
8719// Make sure that 308 responses without bodies are not treated as redirects.
8720// Certain legacy apis that pre-date the response code expect this behavior
8721// (Like Google Drive).
8722TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558723 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378724
8725 TestDelegate d;
tommycli59a63432015-11-06 00:10:558726 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378727
rhalavatib7bd7c792017-04-27 05:25:168728 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8729 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378730
[email protected]f7022f32014-08-21 16:32:198731 request->Start();
[email protected]0a17aab32014-04-24 03:32:378732 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:508733 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378734 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198735 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378736 EXPECT_EQ("This is not a redirect.", d.data_received());
8737}
8738
[email protected]f878230e2014-04-03 15:36:148739TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558740 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148741
tommycli59a63432015-11-06 00:10:558742 GURL original_url(
8743 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8744 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148745
8746 TestDelegate d;
8747 {
rhalavatib7bd7c792017-04-27 05:25:168748 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8749 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148750
[email protected]f7022f32014-08-21 16:32:198751 r->Start();
[email protected]f878230e2014-04-03 15:36:148752 base::RunLoop().Run();
8753
[email protected]f7022f32014-08-21 16:32:198754 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508755 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198756 EXPECT_EQ(original_url, r->original_url());
8757 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148758 }
8759}
8760
[email protected]cba24642014-08-15 20:49:598761TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558762 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598763
tommycli59a63432015-11-06 00:10:558764 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598765 GURL first_party_url("http://example.com");
8766
8767 TestDelegate d;
8768 {
rhalavatib7bd7c792017-04-27 05:25:168769 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8770 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468771 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598772
[email protected]f7022f32014-08-21 16:32:198773 r->Start();
[email protected]cba24642014-08-15 20:49:598774 base::RunLoop().Run();
8775
[email protected]f7022f32014-08-21 16:32:198776 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508777 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468778 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598779 }
8780}
8781
8782TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558783 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598784
tommycli59a63432015-11-06 00:10:558785 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598786 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558787 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598788
8789 TestDelegate d;
8790 {
rhalavatib7bd7c792017-04-27 05:25:168791 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8792 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468793 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198794 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598795 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8796
[email protected]f7022f32014-08-21 16:32:198797 r->Start();
[email protected]cba24642014-08-15 20:49:598798 base::RunLoop().Run();
8799
[email protected]f7022f32014-08-21 16:32:198800 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508801 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468802 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598803 }
8804}
8805
[email protected]316c1e5e2012-09-12 15:17:448806TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558807 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448808
8809 const char kData[] = "hello world";
8810
8811 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368812 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168813 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8814 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198815 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078816 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448817 HttpRequestHeaders headers;
8818 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328819 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198820 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448821
danakj8522a25b2016-04-16 00:17:368822 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558823 req.get(), &default_network_delegate_,
8824 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428825 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8826 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448827
[email protected]f7022f32014-08-21 16:32:198828 req->Start();
[email protected]255620da2013-08-19 13:14:298829 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198830 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448831}
8832
8833TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558834 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448835
8836 const char kData[] = "hello world";
8837
8838 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368839 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168840 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8841 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198842 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078843 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448844 HttpRequestHeaders headers;
8845 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328846 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198847 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448848
danakj8522a25b2016-04-16 00:17:368849 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558850 req.get(), &default_network_delegate_,
8851 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098852 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428853 "Very Good Reason"));
8854 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448855
[email protected]f7022f32014-08-21 16:32:198856 req->Start();
[email protected]255620da2013-08-19 13:14:298857 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198858 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448859 EXPECT_EQ(kData, d.data_received());
8860}
8861
8862// Check that default A-L header is sent.
8863TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558864 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448865
[email protected]8790210c2013-12-02 05:29:538866 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248867 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448868 TestURLRequestContext context(true);
8869 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438870 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448871 context.Init();
8872
8873 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368874 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558875 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168876 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198877 req->Start();
[email protected]255620da2013-08-19 13:14:298878 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448879 EXPECT_EQ("en", d.data_received());
8880}
8881
8882// Check that an empty A-L header is not sent. http://crbug.com/77365.
8883TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558884 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448885
[email protected]8790210c2013-12-02 05:29:538886 std::string empty_string; // Avoid most vexing parse on line below.
8887 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248888 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448889 TestURLRequestContext context(true);
8890 context.set_network_delegate(&network_delegate);
8891 context.Init();
8892 // We override the language after initialization because empty entries
8893 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438894 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448895
8896 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368897 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558898 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168899 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198900 req->Start();
[email protected]255620da2013-08-19 13:14:298901 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448902 EXPECT_EQ("None", d.data_received());
8903}
8904
8905// Check that if request overrides the A-L header, the default is not appended.
8906// See http://crbug.com/20894
8907TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558908 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448909
8910 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368911 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558912 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168913 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448914 HttpRequestHeaders headers;
8915 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198916 req->SetExtraRequestHeaders(headers);
8917 req->Start();
[email protected]255620da2013-08-19 13:14:298918 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448919 EXPECT_EQ(std::string("ru"), d.data_received());
8920}
8921
8922// Check that default A-E header is sent.
8923TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558924 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448925
8926 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368927 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558928 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168929 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448930 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198931 req->SetExtraRequestHeaders(headers);
8932 req->Start();
[email protected]255620da2013-08-19 13:14:298933 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448934 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8935}
8936
8937// Check that if request overrides the A-E header, the default is not appended.
8938// See http://crbug.com/47381
8939TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558940 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448941
8942 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368943 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558944 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168945 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448946 HttpRequestHeaders headers;
8947 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198948 req->SetExtraRequestHeaders(headers);
8949 req->Start();
[email protected]255620da2013-08-19 13:14:298950 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448951 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8952 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8953}
8954
[email protected]84f05432013-03-15 01:00:128955// Check that setting the A-C header sends the proper header.
8956TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558957 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448958
8959 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368960 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558961 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168962 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448963 HttpRequestHeaders headers;
8964 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198965 req->SetExtraRequestHeaders(headers);
8966 req->Start();
[email protected]255620da2013-08-19 13:14:298967 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448968 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8969}
8970
8971// Check that default User-Agent header is sent.
8972TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558973 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448974
8975 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368976 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558977 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168978 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198979 req->Start();
[email protected]255620da2013-08-19 13:14:298980 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198981 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378982 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448983}
8984
8985// Check that if request overrides the User-Agent header,
8986// the default is not appended.
marqf14fff8d2015-12-02 15:52:298987// TODO(crbug.com/564656) This test is flaky on iOS.
8988#if defined(OS_IOS)
8989#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8990#else
8991#define MAYBE_OverrideUserAgent OverrideUserAgent
8992#endif
8993TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558994 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448995
8996 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368997 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558998 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168999 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449000 HttpRequestHeaders headers;
9001 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:199002 req->SetExtraRequestHeaders(headers);
9003 req->Start();
[email protected]255620da2013-08-19 13:14:299004 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:359005 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449006}
9007
[email protected]ee4c30d2012-11-07 15:08:439008// Check that a NULL HttpUserAgentSettings causes the corresponding empty
9009// User-Agent header to be sent but does not send the Accept-Language and
9010// Accept-Charset headers.
9011TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:559012 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:439013
[email protected]ceefd7fd2012-11-29 00:36:249014 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:439015 TestURLRequestContext context(true);
9016 context.set_network_delegate(&network_delegate);
9017 context.Init();
9018 // We override the HttpUserAgentSettings after initialization because empty
9019 // entries get overridden by Init().
9020 context.set_http_user_agent_settings(NULL);
9021
9022 struct {
9023 const char* request;
9024 const char* expected_response;
tommycli59a63432015-11-06 00:10:559025 } tests[] = {{"/echoheader?Accept-Language", "None"},
9026 {"/echoheader?Accept-Charset", "None"},
9027 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:439028
viettrungluue4a8b882014-10-16 06:17:389029 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:439030 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369031 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169032 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
9033 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199034 req->Start();
[email protected]255620da2013-08-19 13:14:299035 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:439036 EXPECT_EQ(tests[i].expected_response, d.data_received())
9037 << " Request = \"" << tests[i].request << "\"";
9038 }
9039}
9040
[email protected]5033ab82013-03-22 20:17:469041// Make sure that URLRequest passes on its priority updates to
9042// newly-created jobs after the first one.
9043TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:559044 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:469045
9046 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369047 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169048 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9049 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199050 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:469051
danakj8522a25b2016-04-16 00:17:369052 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:559053 req.get(), &default_network_delegate_,
9054 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:429055 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
9056 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:469057
[email protected]f7022f32014-08-21 16:32:199058 req->SetPriority(LOW);
9059 req->Start();
9060 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:469061
mmenkeed0498b2015-12-08 23:20:429062 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:369063 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:429064 req.get(), &default_network_delegate_, &job_priority));
9065 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:469066
9067 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:299068 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:429069 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:469070}
9071
[email protected]80abdad2014-03-15 00:20:549072// Check that creating a network request while entering/exiting suspend mode
9073// fails as it should. This is the only case where an HttpTransactionFactory
9074// does not return an HttpTransaction.
9075TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
9076 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:369077 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:179078 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:549079 network_layer->OnSuspend();
9080
dchengc7eeda422015-12-26 03:56:489081 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:039082 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:279083 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:549084
9085 TestURLRequestContext context(true);
9086 context.set_http_transaction_factory(&http_cache);
9087 context.Init();
9088
9089 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369090 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169091 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9092 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199093 req->Start();
[email protected]80abdad2014-03-15 00:20:549094 base::RunLoop().Run();
9095
9096 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:509097 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:549098}
9099
mmenke2281f3762015-11-02 20:38:179100namespace {
[email protected]80abdad2014-03-15 00:20:549101
mmenke2281f3762015-11-02 20:38:179102// HttpTransactionFactory that synchronously fails to create transactions.
9103class FailingHttpTransactionFactory : public HttpTransactionFactory {
9104 public:
9105 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
9106 : network_session_(network_session) {}
9107
Chris Watkins7a41d3552017-12-01 02:13:279108 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:179109
9110 // HttpTransactionFactory methods:
9111 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:369112 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:179113 return ERR_FAILED;
9114 }
9115
9116 HttpCache* GetCache() override { return nullptr; }
9117
9118 HttpNetworkSession* GetSession() override { return network_session_; }
9119
9120 private:
9121 HttpNetworkSession* network_session_;
9122
9123 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
9124};
9125
9126} // namespace
9127
9128// Check that when a request that fails to create an HttpTransaction can be
9129// cancelled while the failure notification is pending, and doesn't send two
9130// failure notifications.
9131//
9132// This currently only happens when in suspend mode and there's no cache, but
9133// just use a special HttpTransactionFactory, to avoid depending on those
9134// behaviors.
9135TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
9136 FailingHttpTransactionFactory http_transaction_factory(
9137 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:549138 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:179139 context.set_http_transaction_factory(&http_transaction_factory);
9140 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:549141 context.Init();
9142
9143 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369144 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:169145 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
9146 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:179147 // Don't send cookies (Collecting cookies is asynchronous, and need request to
9148 // try to create an HttpNetworkTransaction synchronously on start).
9149 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:199150 req->Start();
mmenke2281f3762015-11-02 20:38:179151 req->Cancel();
[email protected]80abdad2014-03-15 00:20:549152 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:179153 // Run pending error task, if there is one.
9154 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:549155
9156 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:179157 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509158 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:179159
9160 // NetworkDelegate should see the cancellation, but not the error.
9161 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
9162 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:549163}
9164
ttuttlec0c828492015-05-15 01:25:559165TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:559166 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559167
9168 TestDelegate d;
tommycli59a63432015-11-06 00:10:559169 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169170 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9171 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559172
9173 req->Start();
9174 base::RunLoop().Run();
9175
9176 EXPECT_TRUE(req->response_info().network_accessed);
9177}
9178
9179TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:559180 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559181
9182 // Populate the cache.
9183 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369184 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169185 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
9186 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:559187 req->Start();
9188 base::RunLoop().Run();
9189
maksim.sisovb53724b52016-09-16 05:30:509190 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559191 EXPECT_TRUE(req->response_info().network_accessed);
9192 EXPECT_FALSE(req->response_info().was_cached);
9193
tommycli59a63432015-11-06 00:10:559194 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:169195 DEFAULT_PRIORITY, &d,
9196 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:559197 req->Start();
9198 base::RunLoop().Run();
9199
maksim.sisovb53724b52016-09-16 05:30:509200 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:559201 EXPECT_FALSE(req->response_info().network_accessed);
9202 EXPECT_TRUE(req->response_info().was_cached);
9203}
9204
9205TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:559206 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:559207
9208 TestDelegate d;
tommycli59a63432015-11-06 00:10:559209 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169210 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9211 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:339212 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:559213
9214 req->Start();
9215 base::RunLoop().Run();
9216
9217 EXPECT_FALSE(req->response_info().network_accessed);
9218}
9219
rdsmithbf8c3c12016-11-18 18:16:249220// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:089221// correctly in the absence of contention.
9222TEST_F(URLRequestTestHTTP, ThrottledPriority) {
9223 ASSERT_TRUE(http_test_server()->Start());
9224
9225 TestDelegate d;
9226 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:169227 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9228 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:089229 req->Start();
9230 base::RunLoop().Run();
9231
9232 EXPECT_TRUE(req->status().is_success());
9233}
9234
ricea3a1c71f2016-06-17 10:05:269235TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
9236 ASSERT_TRUE(http_test_server()->Start());
9237
9238 TestDelegate d;
9239 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169240 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9241 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269242 req->Start();
9243 base::RunLoop().Run();
9244
9245 EXPECT_EQ(5, req->GetRawBodyBytes());
9246}
9247
9248TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
9249 ASSERT_TRUE(http_test_server()->Start());
9250
9251 TestDelegate d;
9252 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169253 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
9254 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:269255 req->Start();
9256 base::RunLoop().Run();
9257
9258 EXPECT_EQ(30, req->GetRawBodyBytes());
9259}
9260
jamd3f5a3c2016-10-27 18:52:029261// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
9262// the delegate isn't called back synchronously.
9263TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
9264 ASSERT_TRUE(http_test_server()->Start());
9265 default_network_delegate_.set_before_start_transaction_fails();
9266
9267 TestDelegate d;
9268 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169269 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
9270 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:029271 req->Start();
9272 DCHECK(!d.response_completed());
9273 base::RunLoop().Run();
9274 DCHECK(d.response_completed());
9275 EXPECT_EQ(ERR_FAILED, d.request_status());
9276}
9277
bengr1bf8e942014-11-07 01:36:509278class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
9279 public:
9280 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
9281 // ideally remove the dependency on URLRequestTestJob, and maybe move these
9282 // tests into the factory tests.
9283 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
9284 }
9285
9286 void SetUpFactory() override {
9287 interceptor_ = new MockURLRequestInterceptor();
9288 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:369289 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:509290 }
9291
9292 MockURLRequestInterceptor* interceptor() const {
9293 return interceptor_;
9294 }
9295
9296 private:
9297 MockURLRequestInterceptor* interceptor_;
9298};
9299
9300TEST_F(URLRequestInterceptorTestHTTP,
9301 NetworkDelegateNotificationOnRedirectIntercept) {
9302 interceptor()->set_intercept_redirect(true);
9303 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
9304 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
9305
tommycli59a63432015-11-06 00:10:559306 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509307
9308 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369309 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169310 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
9311 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509312 req->Start();
9313 base::RunLoop().Run();
9314
9315 EXPECT_TRUE(interceptor()->did_intercept_redirect());
9316 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:509317 int status = d.request_status();
9318 EXPECT_EQ(OK, status);
9319 if (status == OK)
bengr1bf8e942014-11-07 01:36:509320 EXPECT_EQ(200, req->response_headers()->response_code());
9321
9322 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9323 EXPECT_EQ(1, d.response_started_count());
9324 EXPECT_EQ(0, d.received_redirect_count());
9325
9326 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009327 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509328 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
9329}
9330
9331TEST_F(URLRequestInterceptorTestHTTP,
9332 NetworkDelegateNotificationOnErrorIntercept) {
9333 // Intercept that error and respond with an OK response.
9334 interceptor()->set_intercept_final_response(true);
9335 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
9336 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
9337 default_network_delegate()->set_can_be_intercepted_on_error(true);
9338
tommycli59a63432015-11-06 00:10:559339 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509340
9341 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369342 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:559343 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:169344 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509345 req->set_method("GET");
9346 req->Start();
9347 base::RunLoop().Run();
9348
9349 EXPECT_TRUE(interceptor()->did_intercept_final());
9350
9351 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509352 int status = d.request_status();
9353 EXPECT_EQ(OK, status);
9354 if (status == OK)
bengr1bf8e942014-11-07 01:36:509355 EXPECT_EQ(200, req->response_headers()->response_code());
9356 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
9357 EXPECT_EQ(1, d.response_started_count());
9358 EXPECT_EQ(0, d.received_redirect_count());
9359
9360 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009361 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509362 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9363}
9364
9365TEST_F(URLRequestInterceptorTestHTTP,
9366 NetworkDelegateNotificationOnResponseIntercept) {
9367 // Intercept that error and respond with an OK response.
9368 interceptor()->set_intercept_final_response(true);
9369
9370 // Intercept with a real URLRequestHttpJob.
9371 interceptor()->set_use_url_request_http_job(true);
9372
tommycli59a63432015-11-06 00:10:559373 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509374
9375 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369376 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169377 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9378 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509379 req->set_method("GET");
9380 req->Start();
9381 base::RunLoop().Run();
9382
9383 EXPECT_TRUE(interceptor()->did_intercept_final());
9384
9385 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509386 int status = d.request_status();
9387 EXPECT_EQ(OK, status);
9388 if (status == OK)
bengr1bf8e942014-11-07 01:36:509389 EXPECT_EQ(200, req->response_headers()->response_code());
9390 EXPECT_EQ("hello", d.data_received());
9391 EXPECT_EQ(1, d.response_started_count());
9392 EXPECT_EQ(0, d.received_redirect_count());
9393
9394 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009395 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509396 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9397}
9398
mkwst0c5eab872014-11-21 14:18:549399class URLRequestTestReferrerPolicy : public URLRequestTest {
9400 public:
Chris Watkins7a41d3552017-12-01 02:13:279401 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549402
tommycli59a63432015-11-06 00:10:559403 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9404 origin_server_.reset(new EmbeddedTestServer(type));
9405 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9406 origin_server_->AddDefaultHandlers(
9407 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9408 } else {
9409 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9410 }
mkwst0c5eab872014-11-21 14:18:549411 ASSERT_TRUE(origin_server_->Start());
9412 }
9413
tommycli59a63432015-11-06 00:10:559414 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9415 net::EmbeddedTestServer::Type dest_type) {
9416 origin_server_.reset(new EmbeddedTestServer(origin_type));
9417 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9418 origin_server_->AddDefaultHandlers(
9419 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9420 } else {
9421 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9422 }
mkwst0c5eab872014-11-21 14:18:549423 ASSERT_TRUE(origin_server_->Start());
9424
tommycli59a63432015-11-06 00:10:559425 destination_server_.reset(new EmbeddedTestServer(dest_type));
9426 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9427 destination_server_->AddDefaultHandlers(
9428 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9429 } else {
9430 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9431 }
mkwst0c5eab872014-11-21 14:18:549432 ASSERT_TRUE(destination_server_->Start());
9433 }
9434
9435 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9436 const GURL& referrer,
9437 const GURL& expected) {
9438 // Create and execute the request: we'll only have a |destination_server_|
9439 // if the origins are meant to be distinct. Otherwise, we'll use the
9440 // |origin_server_| for both endpoints.
9441 GURL destination_url =
tommycli59a63432015-11-06 00:10:559442 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9443 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549444 GURL origin_url =
tommycli59a63432015-11-06 00:10:559445 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549446
9447 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169448 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9449 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549450 req->set_referrer_policy(policy);
9451 req->SetReferrer(referrer.spec());
9452 req->Start();
9453 base::RunLoop().Run();
9454
9455 EXPECT_EQ(1, d.response_started_count());
9456 EXPECT_EQ(1, d.received_redirect_count());
9457 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509458 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549459 EXPECT_EQ(200, req->response_headers()->response_code());
9460
9461 EXPECT_EQ(expected.spec(), req->referrer());
9462 if (expected.is_empty())
9463 EXPECT_EQ("None", d.data_received());
9464 else
9465 EXPECT_EQ(expected.spec(), d.data_received());
9466 }
9467
tommycli59a63432015-11-06 00:10:559468 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549469
9470 private:
danakj8522a25b2016-04-16 00:17:369471 std::unique_ptr<EmbeddedTestServer> origin_server_;
9472 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549473};
9474
9475TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559476 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549477
estarkc8ccba82017-06-13 22:37:409478 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549479 VerifyReferrerAfterRedirect(
9480 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409481 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549482
9483 VerifyReferrerAfterRedirect(
9484 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409485 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549486
9487 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409488 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549489
estarkc8ccba82017-06-13 22:37:409490 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9491 referrer);
9492
9493 // The original referrer set on the request is expected to obey the referrer
9494 // policy and already be stripped to the origin; thus this test case just
9495 // checks that this policy doesn't cause the referrer to change when following
9496 // a redirect.
9497 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9498 referrer.GetOrigin());
9499
9500 VerifyReferrerAfterRedirect(
9501 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9502 referrer);
9503
9504 // The original referrer set on the request is expected to obey the referrer
9505 // policy and already be stripped to the origin; thus this test case just
9506 // checks that this policy doesn't cause the referrer to change when following
9507 // a redirect.
9508 VerifyReferrerAfterRedirect(
9509 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9510 referrer.GetOrigin(), referrer.GetOrigin());
9511
9512 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549513}
9514
tommycli59a63432015-11-06 00:10:559515TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9516 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9517 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409518 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549519
9520 VerifyReferrerAfterRedirect(
9521 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409522 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549523
9524 VerifyReferrerAfterRedirect(
9525 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409526 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549527
9528 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409529 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9530 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549531
estarkc8ccba82017-06-13 22:37:409532 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9533 referrer);
9534
9535 // The original referrer set on the request is expected to obey the referrer
9536 // policy and already be stripped to the origin; thus this test case just
9537 // checks that this policy doesn't cause the referrer to change when following
9538 // a redirect.
9539 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9540 referrer.GetOrigin());
9541
9542 VerifyReferrerAfterRedirect(
9543 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9544
9545 // The original referrer set on the request is expected to obey the referrer
9546 // policy and already be stripped to the origin; thus this test case just
9547 // checks that this policy doesn't cause the referrer to change when following
9548 // a redirect.
9549 VerifyReferrerAfterRedirect(
9550 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9551 referrer.GetOrigin(), referrer.GetOrigin());
9552
9553 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549554}
9555
9556TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559557 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409558 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549559
9560 VerifyReferrerAfterRedirect(
9561 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409562 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549563
9564 VerifyReferrerAfterRedirect(
9565 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409566 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549567
9568 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409569 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549570
estarkc8ccba82017-06-13 22:37:409571 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9572 referrer);
9573
9574 // The original referrer set on the request is expected to obey the referrer
9575 // policy and already be stripped to the origin; thus this test case just
9576 // checks that this policy doesn't cause the referrer to change when following
9577 // a redirect.
9578 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9579 referrer.GetOrigin());
9580
9581 VerifyReferrerAfterRedirect(
9582 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9583 referrer);
9584
9585 // The original referrer set on the request is expected to obey the referrer
9586 // policy and already be stripped to the origin; thus this test case just
9587 // checks that this policy doesn't cause the referrer to change when following
9588 // a redirect.
9589 VerifyReferrerAfterRedirect(
9590 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9591 referrer.GetOrigin(), referrer.GetOrigin());
9592
9593 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549594}
9595
tommycli59a63432015-11-06 00:10:559596TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9597 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9598 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409599 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549600
9601 VerifyReferrerAfterRedirect(
9602 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409603 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549604
9605 VerifyReferrerAfterRedirect(
9606 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409607 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549608
9609 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409610 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559611 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549612
estarkc8ccba82017-06-13 22:37:409613 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9614 referrer);
9615
9616 // The original referrer set on the request is expected to obey the referrer
9617 // policy and already be stripped to the origin; thus this test case just
9618 // checks that this policy doesn't cause the referrer to change when following
9619 // a redirect.
9620 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9621 referrer.GetOrigin());
9622
9623 VerifyReferrerAfterRedirect(
9624 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9625
9626 // The original referrer set on the request is expected to obey the referrer
9627 // policy and already be stripped to the origin; thus this test case just
9628 // checks that this policy doesn't cause the referrer to change when following
9629 // a redirect.
9630 VerifyReferrerAfterRedirect(
9631 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9632 referrer.GetOrigin(), referrer.GetOrigin());
9633
9634 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549635}
9636
tommycli59a63432015-11-06 00:10:559637TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9638 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9639 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409640 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549641
9642 VerifyReferrerAfterRedirect(
9643 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409644 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549645
9646 VerifyReferrerAfterRedirect(
9647 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409648 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549649
9650 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409651 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559652 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549653
estarkc8ccba82017-06-13 22:37:409654 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9655 referrer);
9656
9657 // The original referrer set on the request is expected to obey the referrer
9658 // policy and already be stripped to the origin; thus this test case just
9659 // checks that this policy doesn't cause the referrer to change when following
9660 // a redirect.
9661 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9662 referrer.GetOrigin());
9663
9664 VerifyReferrerAfterRedirect(
9665 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9666
9667 // The original referrer set on the request is expected to obey the referrer
9668 // policy and already be stripped to the origin; thus this test case just
9669 // checks that this policy doesn't cause the referrer to change when following
9670 // a redirect.
9671 VerifyReferrerAfterRedirect(
9672 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9673 referrer.GetOrigin(), referrer.GetOrigin());
9674
9675 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549676}
9677
tommycli59a63432015-11-06 00:10:559678TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9679 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9680 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409681 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549682
9683 VerifyReferrerAfterRedirect(
9684 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409685 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549686
9687 VerifyReferrerAfterRedirect(
9688 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409689 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549690
9691 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409692 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559693 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549694
estarkc8ccba82017-06-13 22:37:409695 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9696 referrer);
9697
9698 // The original referrer set on the request is expected to obey the referrer
9699 // policy and already be stripped to the origin; thus this test case just
9700 // checks that this policy doesn't cause the referrer to change when following
9701 // a redirect.
9702 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9703 referrer.GetOrigin());
9704
9705 VerifyReferrerAfterRedirect(
9706 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9707
9708 // The original referrer set on the request is expected to obey the referrer
9709 // policy and already be stripped to the origin, though it should be
9710 // subsequently cleared during the downgrading redirect.
9711 VerifyReferrerAfterRedirect(
9712 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9713 referrer.GetOrigin(), GURL());
9714
9715 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549716}
9717
Bence Béky98447b12018-05-08 03:14:019718class HTTPSRequestTest : public TestWithScopedTaskEnvironment {
[email protected]87a09a92011-07-14 15:50:509719 public:
fdorayf33fede2017-05-11 21:18:109720 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099721 default_context_.set_network_delegate(&default_network_delegate_);
9722 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509723 }
Martijn Croonenb1383da2017-10-11 11:56:359724 ~HTTPSRequestTest() override {
9725 SetTransportSecurityStateSourceForTesting(nullptr);
9726 }
[email protected]87a09a92011-07-14 15:50:509727
9728 protected:
[email protected]ceefd7fd2012-11-29 00:36:249729 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099730 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469731};
9732
[email protected]c044616e2013-02-20 02:01:269733TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559734 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9735 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229736 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119737 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469738
[email protected]ea224582008-12-07 20:25:469739 TestDelegate d;
9740 {
danakj8522a25b2016-04-16 00:17:369741 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169742 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9743 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199744 r->Start();
9745 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469746
[email protected]255620da2013-08-19 13:14:299747 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:469748
9749 EXPECT_EQ(1, d.response_started_count());
9750 EXPECT_FALSE(d.received_data_before_response());
9751 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199752 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199753 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199754 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199755 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199756 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469757 }
[email protected]ea224582008-12-07 20:25:469758}
9759
[email protected]5774ada2010-07-15 06:30:549760TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559761 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9762 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9763 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229764 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119765 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339766
9767 bool err_allowed = true;
9768 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9769 TestDelegate d;
9770 {
9771 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369772 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169773 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9774 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339775
[email protected]f7022f32014-08-21 16:32:199776 r->Start();
9777 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339778
[email protected]255620da2013-08-19 13:14:299779 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339780
9781 EXPECT_EQ(1, d.response_started_count());
9782 EXPECT_FALSE(d.received_data_before_response());
9783 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179784 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339785 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199786 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179787 } else {
[email protected]bacff652009-03-31 17:50:339788 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179789 }
[email protected]bacff652009-03-31 17:50:339790 }
9791 }
9792}
9793
[email protected]5774ada2010-07-15 06:30:549794TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559795 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9796 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9797 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229798 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119799 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339800
9801 // Iterate from false to true, just so that we do the opposite of the
9802 // previous test in order to increase test coverage.
9803 bool err_allowed = false;
9804 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9805 TestDelegate d;
9806 {
9807 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369808 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169809 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9810 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339811
[email protected]f7022f32014-08-21 16:32:199812 r->Start();
9813 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339814
[email protected]255620da2013-08-19 13:14:299815 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339816
9817 EXPECT_EQ(1, d.response_started_count());
9818 EXPECT_FALSE(d.received_data_before_response());
9819 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179820 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339821 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199822 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179823 } else {
[email protected]bacff652009-03-31 17:50:339824 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179825 }
[email protected]bacff652009-03-31 17:50:339826 }
9827 }
9828}
[email protected]73e0bba2009-02-19 22:57:099829
tommycli59a63432015-11-06 00:10:559830// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9831// security state. (see http://crbug.com/550977).
9832#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359833// This tests that a load of a domain with preloaded HSTS and HPKP with a
9834// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9835// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449836TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359837 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9838
tommycli59a63432015-11-06 00:10:559839 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9840 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9841 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449842 ASSERT_TRUE(test_server.Start());
9843
Martijn Croonenb1383da2017-10-11 11:56:359844 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9845 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9846 // means that we have to use a MockHostResolver in order to direct
9847 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9848 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449849
9850 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249851 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449852 TestURLRequestContext context(true);
9853 context.set_network_delegate(&network_delegate);
9854 context.set_host_resolver(&host_resolver);
9855 TransportSecurityState transport_security_state;
9856 context.set_transport_security_state(&transport_security_state);
9857 context.Init();
9858
9859 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369860 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359861 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369862 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169863 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449864
[email protected]f7022f32014-08-21 16:32:199865 r->Start();
9866 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449867
[email protected]255620da2013-08-19 13:14:299868 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449869
9870 EXPECT_EQ(1, d.response_started_count());
9871 EXPECT_FALSE(d.received_data_before_response());
9872 EXPECT_TRUE(d.have_certificate_errors());
9873 EXPECT_TRUE(d.certificate_errors_are_fatal());
9874}
9875
9876// This tests that cached HTTPS page loads do not cause any updates to the
9877// TransportSecurityState.
9878TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359879 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9880
[email protected]316c1e5e2012-09-12 15:17:449881 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9882 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559883 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9884 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9885 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449886 ASSERT_TRUE(test_server.Start());
9887
Martijn Croonenb1383da2017-10-11 11:56:359888 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9889 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9890 // means that we have to use a MockHostResolver in order to direct
9891 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9892 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449893
9894 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249895 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449896 TestURLRequestContext context(true);
9897 context.set_network_delegate(&network_delegate);
9898 context.set_host_resolver(&host_resolver);
9899 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269900
martijnc0d6b622015-06-30 19:14:409901 TransportSecurityState::STSState static_sts_state;
9902 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269903 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359904 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449905 context.set_transport_security_state(&transport_security_state);
9906 context.Init();
9907
martijnc0d6b622015-06-30 19:14:409908 TransportSecurityState::STSState dynamic_sts_state;
9909 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359910 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9911 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9912 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9913 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269914
[email protected]316c1e5e2012-09-12 15:17:449915 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369916 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359917 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369918 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169919 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449920
[email protected]f7022f32014-08-21 16:32:199921 r->Start();
9922 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449923
[email protected]255620da2013-08-19 13:14:299924 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449925
9926 EXPECT_EQ(1, d.response_started_count());
9927 EXPECT_FALSE(d.received_data_before_response());
9928 EXPECT_TRUE(d.have_certificate_errors());
9929 EXPECT_TRUE(d.certificate_errors_are_fatal());
9930
[email protected]9e6968d2014-05-07 21:46:269931 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409932 TransportSecurityState::STSState new_static_sts_state;
9933 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269934 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359935 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9936 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409937 TransportSecurityState::STSState new_dynamic_sts_state;
9938 TransportSecurityState::PKPState new_dynamic_pkp_state;
9939 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359940 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409941 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359942 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269943
martijnc0d6b622015-06-30 19:14:409944 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9945 EXPECT_EQ(new_static_sts_state.include_subdomains,
9946 static_sts_state.include_subdomains);
9947 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9948 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489949 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9950 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9951 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449952}
9953
[email protected]8ccc69f2012-11-28 19:52:149954// Make sure HSTS preserves a POST request's method and body.
9955TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9956 static const char kData[] = "hello world";
9957
tommycli59a63432015-11-06 00:10:559958 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9959 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229960 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149961 ASSERT_TRUE(test_server.Start());
9962
9963
9964 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9965 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559966 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229967 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149968 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149969
9970 // Force https for www.somewhere.com.
9971 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209972 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9973 bool include_subdomains = false;
9974 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9975 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149976
9977 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9978
9979 TestURLRequestContext context(true);
9980 context.set_host_resolver(&host_resolver);
9981 context.set_transport_security_state(&transport_security_state);
9982 context.set_network_delegate(&network_delegate);
9983 context.Init();
9984
9985 TestDelegate d;
9986 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9987 // cause a certificate error. Ignore the error.
9988 d.set_allow_certificate_errors(true);
9989
danakj8522a25b2016-04-16 00:17:369990 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199991 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369992 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169993 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199994 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079995 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149996
[email protected]f7022f32014-08-21 16:32:199997 req->Start();
[email protected]255620da2013-08-19 13:14:299998 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:149999
[email protected]f7022f32014-08-21 16:32:1910000 EXPECT_EQ("https", req->url().scheme());
10001 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:1410002 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:4010003
10004 LoadTimingInfo load_timing_info;
10005 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
10006 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
10007 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:1410008}
10009
rob4e0be1f2014-09-11 23:40:2210010// Make sure that the CORS headers are added to cross-origin HSTS redirects.
10011TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
10012 static const char kOriginHeaderValue[] = "http://www.example.com";
10013
tommycli59a63432015-11-06 00:10:5510014 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10015 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:2210016 ASSERT_TRUE(test_server.Start());
10017
10018 // Per spec, TransportSecurityState expects a domain name, rather than an IP
10019 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:5510020 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
10021 // default.
rob4e0be1f2014-09-11 23:40:2210022 MockHostResolver host_resolver;
10023
10024 TransportSecurityState transport_security_state;
10025 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
10026 bool include_subdomains = false;
10027 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
10028
10029 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10030
10031 MockCertVerifier cert_verifier;
10032 cert_verifier.set_default_result(OK);
10033
10034 TestURLRequestContext context(true);
10035 context.set_host_resolver(&host_resolver);
10036 context.set_transport_security_state(&transport_security_state);
10037 context.set_network_delegate(&network_delegate);
10038 context.set_cert_verifier(&cert_verifier);
10039 context.Init();
10040
10041 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
10042 test_server.host_port_pair().port()));
10043 url::Replacements<char> replacements;
10044 const char kNewScheme[] = "https";
10045 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
10046 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
10047
10048 TestDelegate d;
10049 // Quit on redirect to allow response header inspection upon redirect.
10050 d.set_quit_on_redirect(true);
10051
rhalavatib7bd7c792017-04-27 05:25:1610052 std::unique_ptr<URLRequest> req(context.CreateRequest(
10053 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:2210054 // Set Origin header to simulate a cross-origin request.
10055 HttpRequestHeaders request_headers;
10056 request_headers.SetHeader("Origin", kOriginHeaderValue);
10057 req->SetExtraRequestHeaders(request_headers);
10058
10059 req->Start();
10060 base::RunLoop().Run();
10061
10062 EXPECT_EQ(1, d.received_redirect_count());
10063
10064 const HttpResponseHeaders* headers = req->response_headers();
10065 std::string redirect_location;
10066 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
10067 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
10068
10069 std::string received_cors_header;
10070 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
10071 &received_cors_header));
10072 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
10073}
10074
[email protected]316c1e5e2012-09-12 15:17:4410075namespace {
10076
10077class SSLClientAuthTestDelegate : public TestDelegate {
10078 public:
10079 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
10080 }
dchengb03027d2014-10-21 12:00:2010081 void OnCertificateRequested(URLRequest* request,
10082 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:4410083 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:2310084 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:4410085 }
10086 int on_certificate_requested_count() {
10087 return on_certificate_requested_count_;
10088 }
10089 private:
10090 int on_certificate_requested_count_;
10091};
10092
David Benjamin76a40ad2018-02-24 22:22:0810093class TestSSLPrivateKey : public SSLPrivateKey {
10094 public:
10095 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
10096 : key_(std::move(key)) {}
10097
10098 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
10099 int sign_count() const { return sign_count_; }
10100
10101 std::vector<uint16_t> GetAlgorithmPreferences() override {
10102 return key_->GetAlgorithmPreferences();
10103 }
10104 void Sign(uint16_t algorithm,
10105 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:2610106 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:0810107 sign_count_++;
10108 if (fail_signing_) {
10109 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:2610110 FROM_HERE, base::BindOnce(std::move(callback),
10111 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
10112 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:0810113 } else {
David Benjamin8f2d2c12018-02-27 00:08:2610114 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:0810115 }
10116 }
10117
10118 private:
10119 ~TestSSLPrivateKey() override = default;
10120
10121 scoped_refptr<SSLPrivateKey> key_;
10122 bool fail_signing_ = false;
10123 int sign_count_ = 0;
10124};
10125
[email protected]316c1e5e2012-09-12 15:17:4410126} // namespace
10127
10128// TODO(davidben): Test the rest of the code. Specifically,
10129// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:4410130// - Getting a certificate request in an SSL renegotiation sending the
10131// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:0810132TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:5510133 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10134 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:1210135 ssl_config.client_cert_type =
10136 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:0810137 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:5510138 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:2210139 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410140 ASSERT_TRUE(test_server.Start());
10141
10142 SSLClientAuthTestDelegate d;
10143 {
danakj8522a25b2016-04-16 00:17:3610144 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610145 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10146 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410147
[email protected]f7022f32014-08-21 16:32:1910148 r->Start();
10149 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410150
[email protected]255620da2013-08-19 13:14:2910151 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410152
10153 EXPECT_EQ(1, d.on_certificate_requested_count());
10154 EXPECT_FALSE(d.received_data_before_response());
10155 EXPECT_EQ(0, d.bytes_received());
10156
10157 // Send no certificate.
10158 // TODO(davidben): Get temporary client cert import (with keys) working on
10159 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:5410160 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:4410161
[email protected]255620da2013-08-19 13:14:2910162 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410163
David Benjamin76a40ad2018-02-24 22:22:0810164 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:4410165 EXPECT_EQ(1, d.response_started_count());
10166 EXPECT_FALSE(d.received_data_before_response());
10167 EXPECT_NE(0, d.bytes_received());
10168 }
10169}
10170
David Benjamin76a40ad2018-02-24 22:22:0810171TEST_F(HTTPSRequestTest, ClientAuth) {
10172 std::unique_ptr<FakeClientCertIdentity> identity =
10173 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10174 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10175 ASSERT_TRUE(identity);
10176 scoped_refptr<TestSSLPrivateKey> private_key =
10177 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10178
10179 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10180 net::SSLServerConfig ssl_config;
10181 ssl_config.client_cert_type =
10182 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10183 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10184 test_server.AddDefaultHandlers(
10185 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10186 ASSERT_TRUE(test_server.Start());
10187
10188 {
10189 SSLClientAuthTestDelegate d;
10190 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10191 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10192 TRAFFIC_ANNOTATION_FOR_TESTS));
10193
10194 r->Start();
10195 EXPECT_TRUE(r->is_pending());
10196
10197 base::RunLoop().Run();
10198
10199 EXPECT_EQ(1, d.on_certificate_requested_count());
10200 EXPECT_FALSE(d.received_data_before_response());
10201 EXPECT_EQ(0, d.bytes_received());
10202
10203 // Send a certificate.
10204 r->ContinueWithCertificate(identity->certificate(), private_key);
10205
10206 base::RunLoop().Run();
10207
10208 EXPECT_EQ(OK, d.request_status());
10209 EXPECT_EQ(1, d.response_started_count());
10210 EXPECT_FALSE(d.received_data_before_response());
10211 EXPECT_NE(0, d.bytes_received());
10212
10213 // The private key should have been used.
10214 EXPECT_EQ(1, private_key->sign_count());
10215 }
10216
10217 // Close all connections and clear the session cache to force a new handshake.
10218 default_context_.http_transaction_factory()
10219 ->GetSession()
10220 ->CloseAllConnections();
10221 SSLClientSocket::ClearSessionCache();
10222
10223 // Connecting again should not call OnCertificateRequested. The identity is
10224 // taken from the client auth cache.
10225 {
10226 SSLClientAuthTestDelegate d;
10227 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10228 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10229 TRAFFIC_ANNOTATION_FOR_TESTS));
10230
10231 r->Start();
10232 EXPECT_TRUE(r->is_pending());
10233
10234 base::RunLoop().Run();
10235
10236 EXPECT_EQ(OK, d.request_status());
10237 EXPECT_EQ(0, d.on_certificate_requested_count());
10238 EXPECT_FALSE(d.received_data_before_response());
10239 EXPECT_EQ(1, d.response_started_count());
10240 EXPECT_FALSE(d.received_data_before_response());
10241 EXPECT_NE(0, d.bytes_received());
10242
10243 // The private key should have been used.
10244 EXPECT_EQ(2, private_key->sign_count());
10245 }
10246}
10247
10248// Test that private keys that fail to sign anything get evicted from the cache.
10249TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
10250 std::unique_ptr<FakeClientCertIdentity> identity =
10251 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10252 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10253 ASSERT_TRUE(identity);
10254 scoped_refptr<TestSSLPrivateKey> private_key =
10255 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10256 private_key->set_fail_signing(true);
10257
10258 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10259 net::SSLServerConfig ssl_config;
10260 ssl_config.client_cert_type =
10261 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10262 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10263 test_server.AddDefaultHandlers(
10264 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10265 ASSERT_TRUE(test_server.Start());
10266
10267 {
10268 SSLClientAuthTestDelegate d;
10269 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10270 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10271 TRAFFIC_ANNOTATION_FOR_TESTS));
10272
10273 r->Start();
10274 EXPECT_TRUE(r->is_pending());
10275 base::RunLoop().Run();
10276
10277 EXPECT_EQ(1, d.on_certificate_requested_count());
10278 EXPECT_FALSE(d.received_data_before_response());
10279 EXPECT_EQ(0, d.bytes_received());
10280
10281 // Send a certificate.
10282 r->ContinueWithCertificate(identity->certificate(), private_key);
10283 base::RunLoop().Run();
10284
10285 // The private key cannot sign anything, so we report an error.
10286 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
10287 EXPECT_EQ(1, d.response_started_count());
10288 EXPECT_FALSE(d.received_data_before_response());
10289 EXPECT_EQ(0, d.bytes_received());
10290
10291 // The private key should have been used.
10292 EXPECT_EQ(1, private_key->sign_count());
10293 }
10294
10295 // Close all connections and clear the session cache to force a new handshake.
10296 default_context_.http_transaction_factory()
10297 ->GetSession()
10298 ->CloseAllConnections();
10299 SSLClientSocket::ClearSessionCache();
10300
10301 // The bad identity should have been evicted from the cache, so connecting
10302 // again should call OnCertificateRequested again.
10303 {
10304 SSLClientAuthTestDelegate d;
10305 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10306 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10307 TRAFFIC_ANNOTATION_FOR_TESTS));
10308
10309 r->Start();
10310 EXPECT_TRUE(r->is_pending());
10311
10312 base::RunLoop().Run();
10313
10314 EXPECT_EQ(1, d.on_certificate_requested_count());
10315 EXPECT_FALSE(d.received_data_before_response());
10316 EXPECT_EQ(0, d.bytes_received());
10317
10318 // There should have been no additional uses of the private key.
10319 EXPECT_EQ(1, private_key->sign_count());
10320 }
10321}
10322
10323// Test that cached private keys that fail to sign anything trigger a
10324// retry. This is so we handle unplugged smartcards
10325// gracefully. https://crbug.com/813022.
10326TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
10327 std::unique_ptr<FakeClientCertIdentity> identity =
10328 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
10329 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
10330 ASSERT_TRUE(identity);
10331 scoped_refptr<TestSSLPrivateKey> private_key =
10332 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
10333
10334 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10335 net::SSLServerConfig ssl_config;
10336 ssl_config.client_cert_type =
10337 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
10338 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
10339 test_server.AddDefaultHandlers(
10340 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10341 ASSERT_TRUE(test_server.Start());
10342
10343 // Connect with a client certificate to put it in the client auth cache.
10344 {
10345 SSLClientAuthTestDelegate d;
10346 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10347 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10348 TRAFFIC_ANNOTATION_FOR_TESTS));
10349
10350 r->Start();
10351 EXPECT_TRUE(r->is_pending());
10352
10353 base::RunLoop().Run();
10354
10355 EXPECT_EQ(1, d.on_certificate_requested_count());
10356 EXPECT_FALSE(d.received_data_before_response());
10357 EXPECT_EQ(0, d.bytes_received());
10358
10359 r->ContinueWithCertificate(identity->certificate(), private_key);
10360 base::RunLoop().Run();
10361
10362 EXPECT_EQ(OK, d.request_status());
10363 EXPECT_EQ(1, d.response_started_count());
10364 EXPECT_FALSE(d.received_data_before_response());
10365 EXPECT_NE(0, d.bytes_received());
10366
10367 // The private key should have been used.
10368 EXPECT_EQ(1, private_key->sign_count());
10369 }
10370
10371 // Close all connections and clear the session cache to force a new handshake.
10372 default_context_.http_transaction_factory()
10373 ->GetSession()
10374 ->CloseAllConnections();
10375 SSLClientSocket::ClearSessionCache();
10376
10377 // Cause the private key to fail. Connecting again should attempt to use it,
10378 // notice the failure, and then request a new identity via
10379 // OnCertificateRequested.
10380 private_key->set_fail_signing(true);
10381
10382 {
10383 SSLClientAuthTestDelegate d;
10384 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10385 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10386 TRAFFIC_ANNOTATION_FOR_TESTS));
10387
10388 r->Start();
10389 EXPECT_TRUE(r->is_pending());
10390
10391 base::RunLoop().Run();
10392
10393 // There was an additional signing call on the private key (the one which
10394 // failed).
10395 EXPECT_EQ(2, private_key->sign_count());
10396
10397 // That caused another OnCertificateRequested call.
10398 EXPECT_EQ(1, d.on_certificate_requested_count());
10399 EXPECT_FALSE(d.received_data_before_response());
10400 EXPECT_EQ(0, d.bytes_received());
10401 }
10402}
10403
[email protected]316c1e5e2012-09-12 15:17:4410404TEST_F(HTTPSRequestTest, ResumeTest) {
10405 // Test that we attempt a session resume when making two connections to the
10406 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210407 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410408 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210409 SpawnedTestServer test_server(
10410 SpawnedTestServer::TYPE_HTTPS,
10411 ssl_options,
10412 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410413 ASSERT_TRUE(test_server.Start());
10414
10415 SSLClientSocket::ClearSessionCache();
10416
10417 {
10418 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610419 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610420 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10421 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410422
[email protected]f7022f32014-08-21 16:32:1910423 r->Start();
10424 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410425
[email protected]255620da2013-08-19 13:14:2910426 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410427
10428 EXPECT_EQ(1, d.response_started_count());
10429 }
10430
10431 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10432 CloseAllConnections();
10433
10434 {
10435 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610436 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610437 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10438 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410439
[email protected]f7022f32014-08-21 16:32:1910440 r->Start();
10441 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410442
[email protected]255620da2013-08-19 13:14:2910443 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410444
10445 // The response will look like;
10446 // insert abc
10447 // lookup abc
10448 // insert xyz
10449 //
10450 // With a newline at the end which makes the split think that there are
10451 // four lines.
10452
10453 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910454 std::vector<std::string> lines = base::SplitString(
10455 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410456 ASSERT_EQ(4u, lines.size()) << d.data_received();
10457
10458 std::string session_id;
10459
10460 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910461 std::vector<std::string> parts = base::SplitString(
10462 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410463 ASSERT_EQ(2u, parts.size());
10464 if (i == 0) {
10465 EXPECT_EQ("insert", parts[0]);
10466 session_id = parts[1];
10467 } else {
10468 EXPECT_EQ("lookup", parts[0]);
10469 EXPECT_EQ(session_id, parts[1]);
10470 }
10471 }
10472 }
10473}
10474
Adam Langley32352ad2014-10-14 22:31:0010475// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
10476// the result of fetching "ssl-session-cache" from the test server, indicates
10477// that exactly two different sessions were inserted, with no lookups etc.
10478static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:2910479 std::vector<std::string> lines = base::SplitString(
10480 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010481 ASSERT_EQ(3u, lines.size()) << session_info;
10482
10483 std::string session_id;
10484 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910485 std::vector<std::string> parts = base::SplitString(
10486 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010487 ASSERT_EQ(2u, parts.size());
10488 EXPECT_EQ("insert", parts[0]);
10489 if (i == 0) {
10490 session_id = parts[1];
10491 } else {
10492 EXPECT_NE(session_id, parts[1]);
10493 }
10494 }
10495}
10496
[email protected]316c1e5e2012-09-12 15:17:4410497TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10498 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10499 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210500 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410501 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210502 SpawnedTestServer test_server(
10503 SpawnedTestServer::TYPE_HTTPS,
10504 ssl_options,
10505 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410506 ASSERT_TRUE(test_server.Start());
10507
10508 SSLClientSocket::ClearSessionCache();
10509
10510 {
10511 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610512 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610513 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10514 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410515
[email protected]f7022f32014-08-21 16:32:1910516 r->Start();
10517 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410518
[email protected]255620da2013-08-19 13:14:2910519 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410520
10521 EXPECT_EQ(1, d.response_started_count());
10522 }
10523
10524 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110525 HttpNetworkSession::Context session_context;
10526 session_context.host_resolver = default_context_.host_resolver();
10527 session_context.cert_verifier = default_context_.cert_verifier();
10528 session_context.transport_security_state =
10529 default_context_.transport_security_state();
10530 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010531 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110532 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910533 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110534 session_context.ssl_config_service = default_context_.ssl_config_service();
10535 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410536 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110537 session_context.http_server_properties =
10538 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410539
mmenke6ddfbea2017-05-31 21:48:4110540 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10541 session_context);
zhongyi4928bd52017-02-08 02:16:2710542 std::unique_ptr<HttpCache> cache(
10543 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10544 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410545
10546 default_context_.set_http_transaction_factory(cache.get());
10547
10548 {
10549 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610550 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610551 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10552 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410553
[email protected]f7022f32014-08-21 16:32:1910554 r->Start();
10555 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410556
[email protected]255620da2013-08-19 13:14:2910557 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410558
10559 // The response will look like;
10560 // insert abc
10561 // insert xyz
10562 //
10563 // With a newline at the end which makes the split think that there are
10564 // three lines.
10565
10566 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010567 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410568 }
10569}
10570
Bence Béky98447b12018-05-08 03:14:0110571class HTTPSFallbackTest : public TestWithScopedTaskEnvironment {
[email protected]48d2b7c52014-06-27 01:16:5510572 public:
fdorayf33fede2017-05-11 21:18:1010573 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410574 ssl_config_service_ = new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5610575 false /* online revocation checking */,
davidben095ebb52017-04-12 22:23:3410576 false /* require rev. checking for local anchors */,
10577 false /* token binding enabled */);
10578 context_.set_ssl_config_service(ssl_config_service_.get());
10579 }
Chris Watkins7a41d3552017-12-01 02:13:2710580 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510581
10582 protected:
davidben095ebb52017-04-12 22:23:3410583 TestSSLConfigService* ssl_config_service() {
10584 return ssl_config_service_.get();
10585 }
10586
[email protected]48d2b7c52014-06-27 01:16:5510587 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10588 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010589 context_.Init();
10590 delegate_.set_allow_certificate_errors(true);
10591
[email protected]48d2b7c52014-06-27 01:16:5510592 SpawnedTestServer test_server(
10593 SpawnedTestServer::TYPE_HTTPS,
10594 ssl_options,
10595 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10596 ASSERT_TRUE(test_server.Start());
10597
tommycli59a63432015-11-06 00:10:5510598 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610599 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510600 request_->Start();
10601
10602 base::RunLoop().Run();
10603 }
10604
davidben095ebb52017-04-12 22:23:3410605 void ExpectConnection(int version) {
10606 EXPECT_EQ(1, delegate_.response_started_count());
10607 EXPECT_NE(0, delegate_.bytes_received());
10608 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10609 request_->ssl_info().connection_status));
10610 }
10611
[email protected]48d2b7c52014-06-27 01:16:5510612 void ExpectFailure(int error) {
10613 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010614 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510615 }
10616
10617 private:
10618 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710619 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610620 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410621 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510622};
10623
davidbenb127ca82015-06-15 19:05:4210624// Tests the TLS 1.0 fallback doesn't happen.
10625TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510626 SpawnedTestServer::SSLOptions ssl_options(
10627 SpawnedTestServer::SSLOptions::CERT_OK);
10628 ssl_options.tls_intolerant =
10629 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10630
10631 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510632 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210633}
10634
davidben5a312152016-06-27 22:11:4710635// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510636TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210637 SpawnedTestServer::SSLOptions ssl_options(
10638 SpawnedTestServer::SSLOptions::CERT_OK);
10639 ssl_options.tls_intolerant =
10640 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10641
10642 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510643 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10644}
10645
davidben095ebb52017-04-12 22:23:3410646// Tests that TLS 1.3 interference results in a dedicated error code.
10647TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10648 SpawnedTestServer::SSLOptions ssl_options(
10649 SpawnedTestServer::SSLOptions::CERT_OK);
10650 ssl_options.tls_intolerant =
10651 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10652 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10653
10654 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10655 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10656}
10657
10658// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10659TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10660 SpawnedTestServer::SSLOptions ssl_options(
10661 SpawnedTestServer::SSLOptions::CERT_OK);
10662 ssl_options.tls_intolerant =
10663 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10664 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10665
10666 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10667 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10668}
10669
Bence Béky98447b12018-05-08 03:14:0110670class HTTPSSessionTest : public TestWithScopedTaskEnvironment {
[email protected]a8fed1742013-12-27 02:14:2410671 public:
fdorayf33fede2017-05-11 21:18:1010672 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910673 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410674
10675 default_context_.set_network_delegate(&default_network_delegate_);
10676 default_context_.set_cert_verifier(&cert_verifier_);
10677 default_context_.Init();
10678 }
Chris Watkins7a41d3552017-12-01 02:13:2710679 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410680
10681 protected:
10682 MockCertVerifier cert_verifier_;
10683 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10684 TestURLRequestContext default_context_;
10685};
10686
10687// Tests that session resumption is not attempted if an invalid certificate
10688// is presented.
10689TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10690 SpawnedTestServer::SSLOptions ssl_options;
10691 ssl_options.record_resume = true;
10692 SpawnedTestServer test_server(
10693 SpawnedTestServer::TYPE_HTTPS,
10694 ssl_options,
10695 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10696 ASSERT_TRUE(test_server.Start());
10697
10698 SSLClientSocket::ClearSessionCache();
10699
10700 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910701 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410702 {
10703 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610704 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610705 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10706 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410707
[email protected]f7022f32014-08-21 16:32:1910708 r->Start();
10709 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410710
10711 base::RunLoop().Run();
10712
10713 EXPECT_EQ(1, d.response_started_count());
10714 }
10715
10716 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10717 CloseAllConnections();
10718
10719 // Now change the certificate to be acceptable (so that the response is
10720 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910721 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410722 {
10723 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610724 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610725 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10726 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410727
[email protected]f7022f32014-08-21 16:32:1910728 r->Start();
10729 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410730
10731 base::RunLoop().Run();
10732
10733 // The response will look like;
10734 // insert abc
10735 // insert xyz
10736 //
10737 // With a newline at the end which makes the split think that there are
10738 // three lines.
10739 //
10740 // If a session was presented (eg: a bug), then the response would look
10741 // like;
10742 // insert abc
10743 // lookup abc
10744 // insert xyz
10745
10746 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010747 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410748 }
10749}
10750
[email protected]dffe8242012-03-20 15:14:2710751// This the fingerprint of the "Testing CA" certificate used by the testserver.
10752// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810753static const SHA256HashValue kOCSPTestCertFingerprint = {{
10754 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10755 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10756 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510757}};
[email protected]dffe8242012-03-20 15:14:2710758
[email protected]51523f52013-07-31 21:57:2810759// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10760// testserver.
mattm0b12a6f2016-11-29 19:57:1610761static const SHA256HashValue kOCSPTestCertSPKI = {{
10762 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10763 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10764 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10765}};
[email protected]51523f52013-07-31 21:57:2810766
[email protected]dffe8242012-03-20 15:14:2710767// This is the policy OID contained in the certificates that testserver
10768// generates.
10769static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10770
10771class HTTPSOCSPTest : public HTTPSRequestTest {
10772 public:
10773 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910774 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810775 ev_test_policy_(
10776 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10777 kOCSPTestCertFingerprint,
10778 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210779 }
10780
dcheng67be2b1f2014-10-27 21:47:2910781 void SetUp() override {
Ryan Sleevi8a9c9c12018-05-09 02:36:2310782 context_.SetCTPolicyEnforcer(std::make_unique<DefaultCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010783 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910784 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710785
[email protected]cba24642014-08-15 20:49:5910786 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010787 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210788 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010789 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710790
Matt Muellerfb271992018-01-30 18:10:4810791#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510792 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10793#endif
10794
svaldez2135be52016-04-20 16:34:5310795#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910796 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710797#endif
10798 }
10799
dadrian612337a2016-07-20 22:36:5810800 void DoConnectionWithDelegate(
10801 const SpawnedTestServer::SSLOptions& ssl_options,
10802 TestDelegate* delegate,
10803 SSLInfo* out_ssl_info) {
10804 // Always overwrite |out_ssl_info|.
10805 out_ssl_info->Reset();
10806
[email protected]ce7d0cbc2013-05-03 18:57:2210807 SpawnedTestServer test_server(
10808 SpawnedTestServer::TYPE_HTTPS,
10809 ssl_options,
10810 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710811 ASSERT_TRUE(test_server.Start());
10812
dadrian612337a2016-07-20 22:36:5810813 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610814 std::unique_ptr<URLRequest> r(
10815 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10816 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910817 r->Start();
[email protected]dffe8242012-03-20 15:14:2710818
[email protected]255620da2013-08-19 13:14:2910819 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:5810820 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710821
dadrian612337a2016-07-20 22:36:5810822 *out_ssl_info = r->ssl_info();
10823 }
10824
10825 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10826 CertStatus* out_cert_status) {
10827 // Always overwrite |out_cert_status|.
10828 *out_cert_status = 0;
10829
10830 TestDelegate d;
10831 SSLInfo ssl_info;
10832 ASSERT_NO_FATAL_FAILURE(
10833 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10834
10835 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710836 }
10837
dcheng67be2b1f2014-10-27 21:47:2910838 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810839#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510840 ShutdownGlobalCertNetFetcher();
10841#endif
10842
svaldez2135be52016-04-20 16:34:5310843#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810844 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710845#endif
10846 }
10847
[email protected]a13234c2012-03-20 21:45:0210848 protected:
10849 // SetupContext configures the URLRequestContext that will be used for making
10850 // connetions to testserver. This can be overridden in test subclasses for
10851 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010852 virtual void SetupContext() {
Ryan Sleevi5b4702a2018-04-06 22:23:5610853 context_.set_ssl_config_service(
10854 new TestSSLConfigService(true /* online revocation checking */,
10855 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1410856 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5610857 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210858 }
10859
danakj8522a25b2016-04-16 00:17:3610860 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910861 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610862 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710863};
10864
[email protected]a13234c2012-03-20 21:45:0210865static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010866#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210867 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10868 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410869 // TODO(eroman): Should this also be the return value for
10870 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210871 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10872#else
10873 return 0;
10874#endif
10875}
10876
[email protected]3a86a712013-07-30 07:16:2010877// SystemSupportsHardFailRevocationChecking returns true iff the current
10878// operating system supports revocation checking and can distinguish between
10879// situations where a given certificate lacks any revocation information (eg:
10880// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10881// revocation information cannot be obtained (eg: the CRL was unreachable).
10882// If it does not, then tests which rely on 'hard fail' behaviour should be
10883// skipped.
10884static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410885#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10886 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010887 return true;
10888#else
10889 return false;
10890#endif
10891}
10892
[email protected]a13234c2012-03-20 21:45:0210893// SystemUsesChromiumEVMetadata returns true iff the current operating system
10894// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10895// several tests are effected because our testing EV certificate won't be
10896// recognised as EV.
10897static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210898#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110899 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210900#else
10901 return false;
[email protected]05454a432012-03-20 20:04:0110902#endif
10903}
10904
mattmaf868e72016-09-23 23:25:2010905// Returns the expected CertStatus for tests that expect an online revocation
10906// check failure as a result of checking a test EV cert, which will not
10907// actually trigger an online revocation check on some platforms.
10908static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10909 if (SystemUsesChromiumEVMetadata()) {
10910 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10911 } else {
10912 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10913 // be enabled, and thus there will not be a revocation check to fail.
10914 return 0u;
10915 }
10916}
10917
[email protected]b6f2de32012-08-17 04:35:0810918static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910919#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210920 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10921 return false;
10922#else
10923 return true;
10924#endif
10925}
10926
davidbend1fb2f12014-11-08 02:51:0010927static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410928#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10929 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310930 return true;
mathpc992e602015-10-21 20:34:0310931#else
10932 return false;
10933#endif
davidbend1fb2f12014-11-08 02:51:0010934}
10935
[email protected]dffe8242012-03-20 15:14:2710936TEST_F(HTTPSOCSPTest, Valid) {
10937 if (!SystemSupportsOCSP()) {
10938 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10939 return;
10940 }
10941
[email protected]ce7d0cbc2013-05-03 18:57:2210942 SpawnedTestServer::SSLOptions ssl_options(
10943 SpawnedTestServer::SSLOptions::CERT_AUTO);
10944 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710945
[email protected]924e9f92012-12-16 22:00:5310946 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210947 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710948
10949 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10950
[email protected]a13234c2012-03-20 21:45:0210951 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10952 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710953
10954 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10955}
10956
10957TEST_F(HTTPSOCSPTest, Revoked) {
10958 if (!SystemSupportsOCSP()) {
10959 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10960 return;
10961 }
10962
[email protected]ce7d0cbc2013-05-03 18:57:2210963 SpawnedTestServer::SSLOptions ssl_options(
10964 SpawnedTestServer::SSLOptions::CERT_AUTO);
10965 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710966
10967 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210968 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710969
[email protected]dffe8242012-03-20 15:14:2710970 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710971 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10972 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10973}
10974
10975TEST_F(HTTPSOCSPTest, Invalid) {
10976 if (!SystemSupportsOCSP()) {
10977 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10978 return;
10979 }
10980
[email protected]ce7d0cbc2013-05-03 18:57:2210981 SpawnedTestServer::SSLOptions ssl_options(
10982 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810983 ssl_options.ocsp_status =
10984 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710985
[email protected]924e9f92012-12-16 22:00:5310986 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210987 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710988
Eric Roman1b628daa2017-10-19 19:52:0410989#if defined(USE_BUILTIN_CERT_VERIFIER)
10990 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10991 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10992 // doesn't consider this a candidate for soft-fail (only considers
10993 // network-level failures as skippable).
10994 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10995 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10996#else
[email protected]a13234c2012-03-20 21:45:0210997 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710998 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410999#endif
[email protected]dffe8242012-03-20 15:14:2711000
11001 // Without a positive OCSP response, we shouldn't show the EV status.
11002 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11003 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11004}
[email protected]a13234c2012-03-20 21:45:0211005
Matt Mueller5339d862018-05-02 18:53:5711006TEST_F(HTTPSOCSPTest, IntermediateValid) {
11007 if (!SystemSupportsOCSP()) {
11008 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11009 return;
11010 }
11011
11012 SpawnedTestServer::SSLOptions ssl_options(
11013 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11014 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11015 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11016
11017 CertStatus cert_status;
11018 DoConnection(ssl_options, &cert_status);
11019
11020 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11021
11022 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11023 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11024
11025 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11026}
11027
11028TEST_F(HTTPSOCSPTest, IntermediateResponseOldButStillValid) {
11029 if (!SystemSupportsOCSP()) {
11030 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11031 return;
11032 }
11033
11034 SpawnedTestServer::SSLOptions ssl_options(
11035 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11036 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11037 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11038 // Use an OCSP response for the intermediate that would be too old for a leaf
11039 // cert, but is still valid for an intermediate.
11040 ssl_options.ocsp_intermediate_date =
11041 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG;
11042
11043 CertStatus cert_status;
11044 DoConnection(ssl_options, &cert_status);
11045
11046 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11047
11048 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11049 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11050
11051 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11052}
11053
11054TEST_F(HTTPSOCSPTest, IntermediateResponseTooOld) {
11055 if (!SystemSupportsOCSP()) {
11056 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11057 return;
11058 }
11059
11060 SpawnedTestServer::SSLOptions ssl_options(
11061 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11062 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11063 ssl_options.ocsp_intermediate_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11064 ssl_options.ocsp_intermediate_date =
11065 SpawnedTestServer::SSLOptions::OCSP_DATE_LONGER;
11066
11067 CertStatus cert_status;
11068 DoConnection(ssl_options, &cert_status);
11069
11070#if defined(USE_BUILTIN_CERT_VERIFIER)
11071 // The builtin verifier enforces the baseline requirements for max age of an
11072 // intermediate's OCSP response.
11073 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11074 cert_status & CERT_STATUS_ALL_ERRORS);
11075 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11076#else
11077 // The platform verifiers are more lenient.
11078 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11079 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11080 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11081#endif
11082 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11083}
11084
11085TEST_F(HTTPSOCSPTest, IntermediateRevoked) {
11086 if (!SystemSupportsOCSP()) {
11087 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11088 return;
11089 }
11090
11091 SpawnedTestServer::SSLOptions ssl_options(
11092 SpawnedTestServer::SSLOptions::CERT_AUTO_WITH_INTERMEDIATE);
11093 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11094 ssl_options.ocsp_intermediate_status =
11095 SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11096
11097 CertStatus cert_status;
11098 DoConnection(ssl_options, &cert_status);
11099
11100#if defined(OS_WIN)
11101 // TODO(mattm): why does CertVerifyProcWin accept this?
11102 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11103#else
11104 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11105#endif
11106 EXPECT_EQ(0u, cert_status & CERT_STATUS_IS_EV);
11107 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11108}
11109
davidbend1fb2f12014-11-08 02:51:0011110TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0311111 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011112 LOG(WARNING)
11113 << "Skipping test because system doesn't support OCSP stapling";
11114 return;
11115 }
11116
11117 SpawnedTestServer::SSLOptions ssl_options(
11118 SpawnedTestServer::SSLOptions::CERT_AUTO);
11119 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11120 ssl_options.staple_ocsp_response = true;
11121 ssl_options.ocsp_server_unavailable = true;
11122
11123 CertStatus cert_status;
11124 DoConnection(ssl_options, &cert_status);
11125
11126 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11127
11128 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11129 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11130
11131 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11132}
11133
davidben6c3191b2014-11-21 22:38:0411134// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4811135#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0411136#define MAYBE_RevokedStapled DISABLED_RevokedStapled
11137#else
11138#define MAYBE_RevokedStapled RevokedStapled
11139#endif
11140TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0311141 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0011142 LOG(WARNING)
11143 << "Skipping test because system doesn't support OCSP stapling";
11144 return;
11145 }
11146
11147 SpawnedTestServer::SSLOptions ssl_options(
11148 SpawnedTestServer::SSLOptions::CERT_AUTO);
11149 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11150 ssl_options.staple_ocsp_response = true;
11151 ssl_options.ocsp_server_unavailable = true;
11152
11153 CertStatus cert_status;
11154 DoConnection(ssl_options, &cert_status);
11155
11156 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11157 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11158 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11159}
11160
dadriand476e652016-07-26 21:33:2411161TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
Martijn Croonenb1383da2017-10-11 11:56:3511162 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
11163
dadriand476e652016-07-26 21:33:2411164 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11165 https_test_server.SetSSLConfig(
11166 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11167 https_test_server.ServeFilesFromSourceDirectory(
11168 base::FilePath(kTestFilePath));
11169 ASSERT_TRUE(https_test_server.Start());
11170
11171 // Set up a MockCertVerifier to accept the certificate that the server sends,
11172 // but not provide any OCSP information.
11173 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11174 ASSERT_TRUE(cert);
11175 MockCertVerifier cert_verifier;
11176 CertVerifyResult verify_result;
11177 verify_result.verified_cert = cert;
11178 verify_result.is_issued_by_known_root = true;
11179 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11180 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11181
11182 // Catch the Expect-Staple report.
11183 TransportSecurityState transport_security_state;
11184 MockCertificateReportSender mock_report_sender;
11185 transport_security_state.SetReportSender(&mock_report_sender);
11186
11187 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11188 // that the request can be sent to a site on the Expect-Staple preload list.
11189 MockHostResolver host_resolver;
11190 TestNetworkDelegate network_delegate;
11191 TestURLRequestContext context(true);
11192 context.set_host_resolver(&host_resolver);
11193 context.set_transport_security_state(&transport_security_state);
11194 context.set_network_delegate(&network_delegate);
11195 context.set_cert_verifier(&cert_verifier);
11196 context.Init();
11197
11198 // Now send a request to trigger the violation.
11199 TestDelegate d;
11200 GURL url = https_test_server.GetURL("/");
11201 GURL::Replacements replace_host;
11202 replace_host.SetHostStr(kExpectStapleStaticHostname);
11203 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611204 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11205 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411206 violating_request->Start();
11207 base::RunLoop().Run();
11208
11209 // Confirm a report was sent.
11210 EXPECT_FALSE(mock_report_sender.latest_report().empty());
11211 EXPECT_EQ(GURL(kExpectStapleReportURI),
11212 mock_report_sender.latest_report_uri());
11213}
11214
estark13e0b312016-12-22 23:52:3211215// Tests that Expect-Staple reports are not sent for connections on which there
11216// is a certificate error.
11217TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
11218 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11219 https_test_server.SetSSLConfig(
11220 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11221 https_test_server.ServeFilesFromSourceDirectory(
11222 base::FilePath(kTestFilePath));
11223 ASSERT_TRUE(https_test_server.Start());
11224
11225 // Set up a MockCertVerifier to report an error for the certificate
11226 // and indicate that there was no stapled OCSP response.
11227 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11228 ASSERT_TRUE(cert);
11229 MockCertVerifier cert_verifier;
11230 CertVerifyResult verify_result;
11231 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
11232 verify_result.verified_cert = cert;
11233 verify_result.is_issued_by_known_root = true;
11234 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
11235 cert_verifier.AddResultForCert(cert.get(), verify_result,
11236 ERR_CERT_DATE_INVALID);
11237
11238 // Set up a mock report sender so that the test can check that an
11239 // Expect-Staple report is not sent.
11240 TransportSecurityState transport_security_state;
11241 MockCertificateReportSender mock_report_sender;
11242 transport_security_state.SetReportSender(&mock_report_sender);
11243
11244 TestNetworkDelegate network_delegate;
11245 TestURLRequestContext context(true);
11246
11247 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11248 MockHostResolver host_resolver;
11249 context.set_host_resolver(&host_resolver);
11250
11251 context.set_transport_security_state(&transport_security_state);
11252 context.set_network_delegate(&network_delegate);
11253 context.set_cert_verifier(&cert_verifier);
11254 context.Init();
11255
11256 // Make a connection to |kExpectStapleStaticHostname|. Because the
11257 // |verify_result| used with the |cert_verifier| will indicate a certificate
11258 // error, an Expect-Staple report should not be sent.
11259 TestDelegate d;
11260 GURL url = https_test_server.GetURL("/");
11261 GURL::Replacements replace_host;
11262 replace_host.SetHostStr(kExpectStapleStaticHostname);
11263 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611264 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
11265 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211266 violating_request->Start();
11267 base::RunLoop().Run();
11268
11269 // Confirm a report was not sent.
11270 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11271 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11272}
11273
dadriand476e652016-07-26 21:33:2411274TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
11275 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11276 https_test_server.SetSSLConfig(
11277 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11278 https_test_server.ServeFilesFromSourceDirectory(
11279 base::FilePath(kTestFilePath));
11280 ASSERT_TRUE(https_test_server.Start());
11281
11282 // Set up a MockCertVerifier to accept the certificate that the server sends,
11283 // and provide GOOD revocation status.
11284 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11285 ASSERT_TRUE(cert);
11286 MockCertVerifier cert_verifier;
11287 CertVerifyResult verify_result;
11288 verify_result.verified_cert = cert;
11289 verify_result.is_issued_by_known_root = true;
11290 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
11291 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
11292 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11293
11294 // Catch the Expect-Staple report.
11295 TransportSecurityState transport_security_state;
11296 MockCertificateReportSender mock_report_sender;
11297 transport_security_state.SetReportSender(&mock_report_sender);
11298
11299 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
11300 // that the request can be sent to a site on the Expect-Staple preload list.
11301 MockHostResolver host_resolver;
11302 TestNetworkDelegate network_delegate;
11303 TestURLRequestContext context(true);
11304 context.set_host_resolver(&host_resolver);
11305 context.set_transport_security_state(&transport_security_state);
11306 context.set_network_delegate(&network_delegate);
11307 context.set_cert_verifier(&cert_verifier);
11308 context.Init();
11309
11310 // This request should not not trigger an Expect-Staple violation.
11311 TestDelegate d;
11312 GURL url = https_test_server.GetURL("/");
11313 GURL::Replacements replace_host;
11314 replace_host.SetHostStr(kExpectStapleStaticHostname);
11315 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611316 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11317 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2411318 ok_request->Start();
11319 base::RunLoop().Run();
11320
11321 // Check that no report was sent.
11322 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11323 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11324}
11325
estark13e0b312016-12-22 23:52:3211326// Tests that an Expect-Staple report is not sent when OCSP details are not
11327// checked on the connection.
11328TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
11329 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
11330 https_test_server.SetSSLConfig(
11331 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
11332 https_test_server.ServeFilesFromSourceDirectory(
11333 base::FilePath(kTestFilePath));
11334 ASSERT_TRUE(https_test_server.Start());
11335
11336 // Set up a MockCertVerifier to accept the certificate that the server sends,
11337 // and set |ocsp_result| to indicate that OCSP stapling details were not
11338 // checked on the connection.
11339 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
11340 ASSERT_TRUE(cert);
11341 MockCertVerifier cert_verifier;
11342 CertVerifyResult verify_result;
11343 verify_result.verified_cert = cert;
11344 verify_result.is_issued_by_known_root = true;
11345 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
11346 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
11347
11348 // Set up a mock report sender so that the test can check that an
11349 // Expect-Staple report is not sent.
11350 TransportSecurityState transport_security_state;
11351 MockCertificateReportSender mock_report_sender;
11352 transport_security_state.SetReportSender(&mock_report_sender);
11353
11354 TestNetworkDelegate network_delegate;
11355 TestURLRequestContext context(true);
11356
11357 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
11358 MockHostResolver host_resolver;
11359 context.set_host_resolver(&host_resolver);
11360
11361 context.set_transport_security_state(&transport_security_state);
11362 context.set_network_delegate(&network_delegate);
11363 context.set_cert_verifier(&cert_verifier);
11364 context.Init();
11365
11366 // Make a connection to |kExpectStapleStaticHostname|. Because the
11367 // |verify_result| used with the |cert_verifier| will indicate that OCSP
11368 // stapling details were not checked on the connection, an Expect-Staple
11369 // report should not be sent.
11370 TestDelegate d;
11371 GURL url = https_test_server.GetURL("/");
11372 GURL::Replacements replace_host;
11373 replace_host.SetHostStr(kExpectStapleStaticHostname);
11374 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1611375 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
11376 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3211377 ok_request->Start();
11378 base::RunLoop().Run();
11379
11380 // Check that no report was sent.
11381 EXPECT_TRUE(mock_report_sender.latest_report().empty());
11382 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
11383}
11384
dadrian612337a2016-07-20 22:36:5811385static const struct OCSPVerifyTestData {
11386 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
11387 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
11388 OCSPVerifyResult::ResponseStatus response_status;
11389 bool has_revocation_status;
11390 OCSPRevocationStatus cert_status;
11391} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3111392 // 0
dadrian612337a2016-07-20 22:36:5811393 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11394 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11395 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11396 OCSPVerifyResult::PROVIDED,
11397 true,
11398 OCSPRevocationStatus::GOOD},
11399
Eric Roman8673b812017-09-20 18:57:3111400 // 1
dadrian612337a2016-07-20 22:36:5811401 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11402 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11403 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11404 OCSPVerifyResult::INVALID_DATE,
11405 false,
11406 OCSPRevocationStatus::UNKNOWN},
11407
Eric Roman8673b812017-09-20 18:57:3111408 // 2
dadrian612337a2016-07-20 22:36:5811409 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11410 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11411 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11412 OCSPVerifyResult::INVALID_DATE,
11413 false,
11414 OCSPRevocationStatus::UNKNOWN},
11415
Eric Roman8673b812017-09-20 18:57:3111416 // 3
dadrian612337a2016-07-20 22:36:5811417 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11418 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11419 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11420 OCSPVerifyResult::INVALID_DATE,
11421 false,
11422 OCSPRevocationStatus::UNKNOWN},
11423
Eric Roman8673b812017-09-20 18:57:3111424 // 4
dadrian612337a2016-07-20 22:36:5811425 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11426 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11427 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11428 OCSPVerifyResult::INVALID_DATE,
11429 false,
11430 OCSPRevocationStatus::UNKNOWN},
11431
Eric Roman8673b812017-09-20 18:57:3111432 // 5
dadrian612337a2016-07-20 22:36:5811433 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
11434 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11435 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11436 OCSPVerifyResult::ERROR_RESPONSE,
11437 false,
11438 OCSPRevocationStatus::UNKNOWN},
11439
Eric Roman8673b812017-09-20 18:57:3111440 // 6
dadrian612337a2016-07-20 22:36:5811441 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
11442 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11443 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11444 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
11445 false,
11446 OCSPRevocationStatus::UNKNOWN},
11447
Eric Roman8673b812017-09-20 18:57:3111448 // 7
dadrian612337a2016-07-20 22:36:5811449 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
11450 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11451 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11452 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11453 false,
11454 OCSPRevocationStatus::UNKNOWN},
11455
Eric Roman8673b812017-09-20 18:57:3111456 // 8
dadrian612337a2016-07-20 22:36:5811457 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11458 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11459 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11460 OCSPVerifyResult::INVALID_DATE,
11461 false,
11462 OCSPRevocationStatus::UNKNOWN},
11463
Eric Roman8673b812017-09-20 18:57:3111464 // 9
dadrian612337a2016-07-20 22:36:5811465 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11466 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11467 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11468 OCSPVerifyResult::PROVIDED,
11469 true,
11470 OCSPRevocationStatus::UNKNOWN},
11471
Eric Roman8673b812017-09-20 18:57:3111472 // 10
dadrian612337a2016-07-20 22:36:5811473 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11474 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11475 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11476 OCSPVerifyResult::INVALID_DATE,
11477 false,
11478 OCSPRevocationStatus::UNKNOWN},
11479
Eric Roman8673b812017-09-20 18:57:3111480 // 11
dadrian612337a2016-07-20 22:36:5811481 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11482 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11483 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11484 OCSPVerifyResult::INVALID_DATE,
11485 false,
11486 OCSPRevocationStatus::UNKNOWN},
11487
Eric Roman8673b812017-09-20 18:57:3111488 // 12
dadrian612337a2016-07-20 22:36:5811489 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11490 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11491 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11492 OCSPVerifyResult::BAD_PRODUCED_AT,
11493 false,
11494 OCSPRevocationStatus::UNKNOWN},
11495
Eric Roman8673b812017-09-20 18:57:3111496 // 13
dadrian612337a2016-07-20 22:36:5811497 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11498 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11499 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11500 OCSPVerifyResult::BAD_PRODUCED_AT,
11501 false,
11502 OCSPRevocationStatus::UNKNOWN},
11503
Eric Roman8673b812017-09-20 18:57:3111504 // 14
dadrian612337a2016-07-20 22:36:5811505 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11506 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11507 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11508 OCSPVerifyResult::BAD_PRODUCED_AT,
11509 false,
11510 OCSPRevocationStatus::UNKNOWN},
11511
Eric Roman8673b812017-09-20 18:57:3111512 // 15
dadrian612337a2016-07-20 22:36:5811513 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11514 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11515 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11516 OCSPVerifyResult::PROVIDED,
11517 true,
11518 OCSPRevocationStatus::GOOD},
11519
Eric Roman8673b812017-09-20 18:57:3111520 // 16
dadrian612337a2016-07-20 22:36:5811521 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11522 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11523 {SpawnedTestServer::SSLOptions::OCSP_OK,
11524 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11525 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11526 OCSPVerifyResult::PROVIDED,
11527 true,
11528 OCSPRevocationStatus::GOOD},
11529
Eric Roman8673b812017-09-20 18:57:3111530 // 17
dadrian612337a2016-07-20 22:36:5811531 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11532 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11533 {SpawnedTestServer::SSLOptions::OCSP_OK,
11534 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11535 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11536 OCSPVerifyResult::PROVIDED,
11537 true,
11538 OCSPRevocationStatus::GOOD},
11539
Eric Roman8673b812017-09-20 18:57:3111540 // 18
dadrian612337a2016-07-20 22:36:5811541 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11542 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11543 {SpawnedTestServer::SSLOptions::OCSP_OK,
11544 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11545 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11546 OCSPVerifyResult::PROVIDED,
11547 true,
11548 OCSPRevocationStatus::GOOD},
11549
Eric Roman8673b812017-09-20 18:57:3111550 // 19
dadrian612337a2016-07-20 22:36:5811551 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11552 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11553 {SpawnedTestServer::SSLOptions::OCSP_OK,
11554 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11555 {SpawnedTestServer::SSLOptions::OCSP_OK,
11556 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11557 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11558 OCSPVerifyResult::INVALID_DATE,
11559 false,
11560 OCSPRevocationStatus::UNKNOWN},
11561
Eric Roman8673b812017-09-20 18:57:3111562 // 20
dadrian612337a2016-07-20 22:36:5811563 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11564 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11565 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11566 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11567 {SpawnedTestServer::SSLOptions::OCSP_OK,
11568 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11569 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11570 OCSPVerifyResult::PROVIDED,
11571 true,
11572 OCSPRevocationStatus::REVOKED},
11573
Eric Roman8673b812017-09-20 18:57:3111574 // 21
dadrian612337a2016-07-20 22:36:5811575 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11576 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11577 {SpawnedTestServer::SSLOptions::OCSP_OK,
11578 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11579 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11580 OCSPVerifyResult::PROVIDED,
11581 true,
11582 OCSPRevocationStatus::UNKNOWN},
11583
Eric Roman8673b812017-09-20 18:57:3111584 // 22
dadrian612337a2016-07-20 22:36:5811585 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11586 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11587 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11588 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11589 {SpawnedTestServer::SSLOptions::OCSP_OK,
11590 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11591 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11592 OCSPVerifyResult::PROVIDED,
11593 true,
11594 OCSPRevocationStatus::UNKNOWN},
11595
Eric Roman8673b812017-09-20 18:57:3111596 // 23
dadrian612337a2016-07-20 22:36:5811597 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11598 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11599 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11600 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11601 false,
11602 OCSPRevocationStatus::UNKNOWN},
11603
Eric Roman8673b812017-09-20 18:57:3111604 // 24
dadrian612337a2016-07-20 22:36:5811605 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11606 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11607 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11608 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11609 false,
11610 OCSPRevocationStatus::UNKNOWN},
11611
Eric Roman8673b812017-09-20 18:57:3111612// These tests fail when using NSS for certificate verification, as NSS fails
11613// and doesn't return the partial path. As a result the OCSP checks being done
11614// at the CertVerifyProc layer cannot access the issuer certificate.
11615#if !defined(USE_NSS_CERTS)
11616 // 25
11617 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11618 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11619 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11620 OCSPVerifyResult::PROVIDED,
11621 true,
11622 OCSPRevocationStatus::REVOKED},
11623
11624 // 26
11625 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11626 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11627 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11628 OCSPVerifyResult::INVALID_DATE,
11629 false,
11630 OCSPRevocationStatus::UNKNOWN},
11631
11632 // 27
11633 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11634 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11635 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11636 OCSPVerifyResult::INVALID_DATE,
11637 false,
11638 OCSPRevocationStatus::UNKNOWN},
11639#endif
dadrian612337a2016-07-20 22:36:5811640};
11641
11642class HTTPSOCSPVerifyTest
11643 : public HTTPSOCSPTest,
11644 public testing::WithParamInterface<OCSPVerifyTestData> {};
11645
11646TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11647 SpawnedTestServer::SSLOptions ssl_options(
11648 SpawnedTestServer::SSLOptions::CERT_AUTO);
11649 OCSPVerifyTestData test = GetParam();
11650
11651 ssl_options.ocsp_responses = test.ocsp_responses;
11652 ssl_options.ocsp_produced = test.ocsp_produced;
11653 ssl_options.staple_ocsp_response = true;
11654
11655 SSLInfo ssl_info;
11656 OCSPErrorTestDelegate delegate;
11657 ASSERT_NO_FATAL_FAILURE(
11658 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11659
11660 // The SSLInfo must be extracted from |delegate| on error, due to how
11661 // URLRequest caches certificate errors.
11662 if (delegate.have_certificate_errors()) {
11663 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11664 ssl_info = delegate.ssl_info();
11665 }
11666
11667 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11668
11669 if (test.has_revocation_status)
11670 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11671}
11672
11673INSTANTIATE_TEST_CASE_P(OCSPVerify,
11674 HTTPSOCSPVerifyTest,
11675 testing::ValuesIn(kOCSPVerifyData));
11676
mattm0b12a6f2016-11-29 19:57:1611677class HTTPSAIATest : public HTTPSOCSPTest {
11678 public:
11679 void SetupContext() override {
11680 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611681 false /* online revocation checking */,
mattm0b12a6f2016-11-29 19:57:1611682 false /* require rev. checking for local anchors */,
11683 false /* token binding enabled */));
11684 }
11685};
11686
11687TEST_F(HTTPSAIATest, AIAFetching) {
11688 SpawnedTestServer::SSLOptions ssl_options(
11689 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11690 SpawnedTestServer test_server(
11691 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11692 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11693 ASSERT_TRUE(test_server.Start());
11694
Ryan Sleevi5b4702a2018-04-06 22:23:5611695 // Unmark the certificate's OID as EV, which will disable revocation
11696 // checking.
11697 ev_test_policy_.reset();
11698
mattm0b12a6f2016-11-29 19:57:1611699 TestDelegate d;
11700 d.set_allow_certificate_errors(true);
11701 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611702 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11703 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611704
11705 r->Start();
11706 EXPECT_TRUE(r->is_pending());
11707
11708 base::RunLoop().Run();
11709
11710 EXPECT_EQ(1, d.response_started_count());
11711
11712 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811713 EXPECT_EQ(OK, d.request_status());
11714 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11715 ASSERT_TRUE(r->ssl_info().cert);
11716 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611717 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411718 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611719}
11720
[email protected]3a86a712013-07-30 07:16:2011721class HTTPSHardFailTest : public HTTPSOCSPTest {
11722 protected:
rsleevid6de8302016-06-21 01:33:2011723 void SetupContext() override {
11724 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611725 false /* online revocation checking */,
11726 true /* require rev. checking for local anchors */,
nharperb7441ef2016-01-25 23:54:1411727 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011728 }
11729};
11730
[email protected]3a86a712013-07-30 07:16:2011731TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11732 if (!SystemSupportsOCSP()) {
11733 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11734 return;
11735 }
11736
11737 if (!SystemSupportsHardFailRevocationChecking()) {
11738 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11739 << "revocation checking";
11740 return;
11741 }
11742
11743 SpawnedTestServer::SSLOptions ssl_options(
11744 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811745 ssl_options.ocsp_status =
11746 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011747
11748 CertStatus cert_status;
11749 DoConnection(ssl_options, &cert_status);
11750
Eric Roman1b628daa2017-10-19 19:52:0411751#if defined(USE_BUILTIN_CERT_VERIFIER)
11752 // TODO(crbug.com/649017): Should we consider invalid response as
11753 // affirmatively revoked?
11754 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11755 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11756#else
11757 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11758#endif
[email protected]3a86a712013-07-30 07:16:2011759
11760 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411761 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011762 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11763}
11764
[email protected]a13234c2012-03-20 21:45:0211765class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11766 protected:
rsleevid6de8302016-06-21 01:33:2011767 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611768 context_.set_ssl_config_service(
11769 new TestSSLConfigService(false /* online revocation checking */,
11770 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411771 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611772 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211773 }
11774};
11775
Eric Romane2243cc62017-10-17 03:59:1311776// Helper class to set the global CRLSet, and on destruction restore the
11777// previously set one.
11778class ScopedSetCRLSet {
11779 public:
11780 ScopedSetCRLSet(scoped_refptr<CRLSet> crl_set) {
11781 prev_crl_set_ = SSLConfigService::GetCRLSet();
11782 SSLConfigService::SetCRLSetForTesting(std::move(crl_set));
11783 }
11784
11785 ~ScopedSetCRLSet() {
11786 SSLConfigService::SetCRLSetForTesting(std::move(prev_crl_set_));
11787 }
11788
11789 private:
11790 scoped_refptr<CRLSet> prev_crl_set_;
11791};
11792
[email protected]a13234c2012-03-20 21:45:0211793TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11794 if (!SystemSupportsOCSP()) {
11795 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11796 return;
11797 }
11798
[email protected]ce7d0cbc2013-05-03 18:57:2211799 SpawnedTestServer::SSLOptions ssl_options(
11800 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811801 ssl_options.ocsp_status =
11802 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311803 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211804
[email protected]924e9f92012-12-16 22:00:5311805 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211806 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211807
mattmaf868e72016-09-23 23:25:2011808 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211809 cert_status & CERT_STATUS_ALL_ERRORS);
11810
11811 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811812 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11813 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211814}
11815
[email protected]be0fff62013-08-29 23:37:4811816TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11817 if (!SystemSupportsOCSP()) {
11818 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11819 return;
11820 }
11821
11822 SpawnedTestServer::SSLOptions ssl_options(
11823 SpawnedTestServer::SSLOptions::CERT_AUTO);
11824 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Eric Romane2243cc62017-10-17 03:59:1311825 ScopedSetCRLSet set_crlset(nullptr);
[email protected]be0fff62013-08-29 23:37:4811826
11827 CertStatus cert_status;
11828 DoConnection(ssl_options, &cert_status);
11829
mattm1a282f52016-11-10 21:49:4211830// Currently only works for Windows and OS X. When using NSS, it's not
11831// possible to determine whether the check failed because of actual
11832// revocation or because there was an OCSP failure.
11833#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811834 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11835#else
11836 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11837#endif
11838
11839 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11840 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11841 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11842}
11843
[email protected]a13234c2012-03-20 21:45:0211844TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11845 if (!SystemSupportsOCSP()) {
11846 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11847 return;
11848 }
11849
[email protected]ce7d0cbc2013-05-03 18:57:2211850 SpawnedTestServer::SSLOptions ssl_options(
11851 SpawnedTestServer::SSLOptions::CERT_AUTO);
11852 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
Eric Romane2243cc62017-10-17 03:59:1311853 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211854
11855 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211856 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211857
11858 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11859
11860 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11861 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811862 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11863 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211864}
11865
11866TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11867 if (!SystemSupportsOCSP()) {
11868 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11869 return;
11870 }
11871
[email protected]ce7d0cbc2013-05-03 18:57:2211872 SpawnedTestServer::SSLOptions ssl_options(
11873 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811874 ssl_options.ocsp_status =
11875 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311876 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211877
11878 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211879 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211880
mattmaf868e72016-09-23 23:25:2011881 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211882 cert_status & CERT_STATUS_ALL_ERRORS);
11883
11884 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811885 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11886 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211887}
11888
[email protected]51523f52013-07-31 21:57:2811889TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11890 if (!SystemSupportsOCSP()) {
11891 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11892 return;
11893 }
11894
11895 SpawnedTestServer::SSLOptions ssl_options(
11896 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811897 ssl_options.ocsp_status =
11898 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Adam Langleyea6d6782017-12-05 23:57:3311899 ScopedSetCRLSet set_crlset(
11900 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {}));
[email protected]51523f52013-07-31 21:57:2811901
11902 CertStatus cert_status;
11903 DoConnection(ssl_options, &cert_status);
11904
11905 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11906 // revocation check for EV.
11907 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11908 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11909 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11910 EXPECT_FALSE(
11911 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11912}
11913
11914TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11915 if (!SystemSupportsOCSP()) {
11916 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11917 return;
11918 }
11919
[email protected]ce7d0cbc2013-05-03 18:57:2211920 SpawnedTestServer::SSLOptions ssl_options(
11921 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811922 ssl_options.ocsp_status =
11923 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311924 ScopedSetCRLSet set_crlset(CRLSet::EmptyCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211925
[email protected]51523f52013-07-31 21:57:2811926 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211927 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211928
[email protected]51523f52013-07-31 21:57:2811929 // Even with a fresh CRLSet, we should still do online revocation checks when
11930 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11931 // test.
mattmaf868e72016-09-23 23:25:2011932 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811933 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211934
[email protected]51523f52013-07-31 21:57:2811935 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211936 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811937 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211938}
11939
11940class HTTPSCRLSetTest : public HTTPSOCSPTest {
11941 protected:
rsleevid6de8302016-06-21 01:33:2011942 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611943 context_.set_ssl_config_service(
11944 new TestSSLConfigService(false /* online revocation checking */,
11945 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411946 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611947 false /* token binding enabled */));
11948 }
11949
11950 void SetUp() override {
11951 HTTPSOCSPTest::SetUp();
11952
11953 // Unmark the certificate's OID as EV, which should disable revocation
11954 // checking (as per the user preference).
11955 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211956 }
11957};
11958
11959TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211960 SpawnedTestServer::SSLOptions ssl_options(
11961 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811962 ssl_options.ocsp_status =
11963 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311964 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211965
[email protected]924e9f92012-12-16 22:00:5311966 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211967 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211968
11969 // If we're not trying EV verification then, even if the CRLSet has expired,
11970 // we don't fall back to online revocation checks.
11971 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11972 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11973 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11974}
[email protected]51523f52013-07-31 21:57:2811975
Ryan Sleevi5b4702a2018-04-06 22:23:5611976TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11977 // Test that when online revocation checking is disabled, and the leaf
11978 // certificate is not EV, that no revocation checking actually happens.
11979 if (!SystemSupportsOCSP()) {
11980 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11981 return;
11982 }
11983
11984 SpawnedTestServer::SSLOptions ssl_options(
11985 SpawnedTestServer::SSLOptions::CERT_AUTO);
11986 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11987 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
11988
11989 CertStatus cert_status;
11990 DoConnection(ssl_options, &cert_status);
11991
11992 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11993
11994 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11995 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11996}
11997
[email protected]51523f52013-07-31 21:57:2811998TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511999#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2812000 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12001 return;
12002#endif
12003
12004 SpawnedTestServer::SSLOptions ssl_options(
12005 SpawnedTestServer::SSLOptions::CERT_AUTO);
12006 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12007 ssl_options.cert_serial = 10;
Eric Romane2243cc62017-10-17 03:59:1312008 ScopedSetCRLSet set_crlset(
Adam Langleyea6d6782017-12-05 23:57:3312009 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {}));
[email protected]51523f52013-07-31 21:57:2812010
12011 CertStatus cert_status = 0;
12012 DoConnection(ssl_options, &cert_status);
12013
12014 // If the certificate is recorded as revoked in the CRLSet, that should be
12015 // reflected without online revocation checking.
12016 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12017 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612018 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2812019}
Adam Langleyea6d6782017-12-05 23:57:3312020
12021TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
12022#if defined(OS_ANDROID)
12023 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
12024 return;
12025#endif
12026
12027 SpawnedTestServer::SSLOptions ssl_options(
12028 SpawnedTestServer::SSLOptions::CERT_AUTO);
12029 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
12030 static const char kCommonName[] = "Test CN";
12031 ssl_options.cert_common_name = kCommonName;
12032
12033 {
12034 ScopedSetCRLSet set_crlset(
12035 CRLSet::ForTesting(false, nullptr, "", kCommonName, {}));
12036
12037 CertStatus cert_status = 0;
12038 DoConnection(ssl_options, &cert_status);
12039
12040 // If the certificate is recorded as revoked in the CRLSet, that should be
12041 // reflected without online revocation checking.
12042 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
12043 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5612044 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3312045 }
12046
12047 const uint8_t kTestServerSPKISHA256[32] = {
12048 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
12049 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
12050 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
12051 };
12052 const std::string spki_hash(
12053 reinterpret_cast<const char*>(kTestServerSPKISHA256),
12054 sizeof(kTestServerSPKISHA256));
12055
12056 {
12057 ScopedSetCRLSet set_crlset(
12058 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash}));
12059
12060 CertStatus cert_status = 0;
12061 DoConnection(ssl_options, &cert_status);
12062
12063 // When the correct SPKI hash is specified, the connection should succeed
12064 // even though the subject is listed in the CRLSet.
12065 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
12066 }
12067}
[email protected]316c1e5e2012-09-12 15:17:4412068#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2712069
Sergey Ulanovc4580e72017-09-13 23:30:1112070#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
12071 !defined(OS_FUCHSIA)
12072// FTP uses a second TCP connection with the port number allocated dynamically
12073// on the server side, so it would be hard to make RemoteTestServer proxy FTP
12074// connections reliably. FTP tests are disabled on platforms that use
12075// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3112076class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1112077 public:
[email protected]d9fca99a2012-02-24 16:16:2012078 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0512079 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5512080 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4712081 // Can't use |default_context_|'s HostResolver to set up the
12082 // FTPTransactionFactory because it hasn't been created yet.
12083 default_context_.set_host_resolver(&host_resolver_);
12084 }
12085
12086 // URLRequestTest interface:
12087 void SetUpFactory() override {
12088 // Add FTP support to the default URLRequestContext.
12089 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0512090 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4712091 }
12092
12093 std::string GetTestFileContents() {
12094 base::FilePath path;
Avi Drissman5c80d832018-05-01 17:01:1912095 EXPECT_TRUE(base::PathService::Get(base::DIR_SOURCE_ROOT, &path));
mmenke9f2ec60c2015-06-01 20:59:4712096 path = path.Append(kTestFilePath);
12097 path = path.AppendASCII(kFtpTestFile);
12098 std::string contents;
12099 EXPECT_TRUE(base::ReadFileToString(path, &contents));
12100 return contents;
[email protected]95409e12010-08-17 20:07:1112101 }
12102
[email protected]b89ca032009-08-31 21:41:3112103 protected:
mmenkecd4c7532016-10-19 18:36:0512104 // Note that this is destroyed before the FtpProtocolHandler that references
12105 // it, which is owned by the parent class. Since no requests are made during
12106 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4712107 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4712108
tommycli59a63432015-11-06 00:10:5512109 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3112110};
12111
[email protected]d2a133182012-08-05 16:44:0812112// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0912113TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0812114 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0812115
12116 TestDelegate d;
12117 {
rhalavatib7bd7c792017-04-27 05:25:1612118 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12119 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912120 r->Start();
12121 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0812122
[email protected]255620da2013-08-19 13:14:2912123 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0812124
[email protected]f7022f32014-08-21 16:32:1912125 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5012126 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0812127 }
12128}
12129
mmenke9f2ec60c2015-06-01 20:59:4712130TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5512131 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112132
[email protected]a25e90e2009-09-09 17:05:3712133 TestDelegate d;
12134 {
danakj8522a25b2016-04-16 00:17:3612135 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612136 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
12137 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912138 r->Start();
12139 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712140
[email protected]255620da2013-08-19 13:14:2912141 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3712142
[email protected]f7022f32014-08-21 16:32:1912143 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3712144 EXPECT_EQ(1, d.response_started_count());
12145 EXPECT_FALSE(d.received_data_before_response());
12146 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5512147 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912148 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512149 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912150 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3712151 }
12152}
12153
mmenke9f2ec60c2015-06-01 20:59:4712154TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5512155 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112156
[email protected]dd265012009-01-08 20:45:2712157 TestDelegate d;
12158 {
danakj8522a25b2016-04-16 00:17:3612159 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612160 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
12161 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912162 r->Start();
12163 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712164
[email protected]255620da2013-08-19 13:14:2912165 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2712166
[email protected]f7022f32014-08-21 16:32:1912167 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712168 EXPECT_EQ(1, d.response_started_count());
12169 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712170 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512171 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912172 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512173 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912174 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2712175 }
12176}
12177
mmenke9f2ec60c2015-06-01 20:59:4712178TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5512179 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112180
[email protected]dd265012009-01-08 20:45:2712181 TestDelegate d;
12182 {
danakj8522a25b2016-04-16 00:17:3612183 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512184 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12185 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612186 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912187 r->Start();
12188 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712189
[email protected]255620da2013-08-19 13:14:2912190 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2712191
[email protected]f7022f32014-08-21 16:32:1912192 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4712193 EXPECT_EQ(1, d.response_started_count());
12194 EXPECT_FALSE(d.received_data_before_response());
12195 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5512196 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1912197 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5512198 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1912199 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2512200
12201 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1912202 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2512203 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2712204 }
12205}
12206
mmenke9f2ec60c2015-06-01 20:59:4712207TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5512208 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112209
[email protected]dd265012009-01-08 20:45:2712210 TestDelegate d;
12211 {
danakj8522a25b2016-04-16 00:17:3612212 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512213 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12214 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612215 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912216 r->Start();
12217 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712218
[email protected]255620da2013-08-19 13:14:2912219 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2712220
[email protected]f7022f32014-08-21 16:32:1912221 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712222 EXPECT_EQ(1, d.response_started_count());
12223 EXPECT_FALSE(d.received_data_before_response());
12224 EXPECT_EQ(d.bytes_received(), 0);
12225 }
12226}
12227
mmenke9f2ec60c2015-06-01 20:59:4712228TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5512229 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112230
[email protected]8b8a197d2009-08-26 15:57:5812231 TestDelegate d;
12232 // Set correct login credentials. The delegate will be asked for them when
12233 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812234 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812235 {
danakj8522a25b2016-04-16 00:17:3612236 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512237 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12238 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612239 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912240 r->Start();
12241 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812242
[email protected]255620da2013-08-19 13:14:2912243 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5812244
[email protected]f7022f32014-08-21 16:32:1912245 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812246 EXPECT_EQ(1, d.response_started_count());
12247 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712248 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812249 }
12250}
12251
mmenke9f2ec60c2015-06-01 20:59:4712252TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5512253 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112254
[email protected]dd265012009-01-08 20:45:2712255 TestDelegate d;
12256 {
danakj8522a25b2016-04-16 00:17:3612257 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512258 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12259 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612260 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912261 r->Start();
12262 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712263
[email protected]255620da2013-08-19 13:14:2912264 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2712265
[email protected]f7022f32014-08-21 16:32:1912266 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2712267 EXPECT_EQ(1, d.response_started_count());
12268 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712269 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2712270 }
12271}
[email protected]8b8a197d2009-08-26 15:57:5812272
mmenke9f2ec60c2015-06-01 20:59:4712273TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5512274 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112275
[email protected]8b8a197d2009-08-26 15:57:5812276 TestDelegate d;
12277 // Set correct login credentials. The delegate will be asked for them when
12278 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812279 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5812280 {
danakj8522a25b2016-04-16 00:17:3612281 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512282 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
12283 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612284 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912285 r->Start();
12286 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812287
[email protected]255620da2013-08-19 13:14:2912288 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5812289
[email protected]f7022f32014-08-21 16:32:1912290 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5812291 EXPECT_EQ(1, d.response_started_count());
12292 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712293 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5812294 }
12295}
[email protected]60a3df52009-09-22 16:13:2412296
mmenke9f2ec60c2015-06-01 20:59:4712297TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5512298 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112299
danakj8522a25b2016-04-16 00:17:3612300 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412301 {
12302 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3612303 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512304 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12305 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1612306 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912307 r->Start();
12308 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412309
[email protected]255620da2013-08-19 13:14:2912310 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2412311
[email protected]f7022f32014-08-21 16:32:1912312 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412313 EXPECT_EQ(1, d->response_started_count());
12314 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712315 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412316 }
12317
12318 d.reset(new TestDelegate);
12319 {
12320 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3612321 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612322 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12323 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912324 r->Start();
12325 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412326
[email protected]255620da2013-08-19 13:14:2912327 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2412328
[email protected]f7022f32014-08-21 16:32:1912329 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412330 EXPECT_EQ(1, d->response_started_count());
12331 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712332 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412333 }
12334}
12335
mmenke9f2ec60c2015-06-01 20:59:4712336TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5512337 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1112338
danakj8522a25b2016-04-16 00:17:3612339 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2412340 // Set correct login credentials. The delegate will be asked for them when
12341 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5812342 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2412343 {
danakj8522a25b2016-04-16 00:17:3612344 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5512345 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
12346 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1612347 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912348 r->Start();
12349 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412350
[email protected]255620da2013-08-19 13:14:2912351 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2412352
[email protected]f7022f32014-08-21 16:32:1912353 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412354 EXPECT_EQ(1, d->response_started_count());
12355 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712356 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412357 }
12358
12359 // Use a new delegate without explicit credentials. The cached ones should be
12360 // used.
12361 d.reset(new TestDelegate);
12362 {
12363 // Don't pass wrong credentials in the URL, they would override valid cached
12364 // ones.
danakj8522a25b2016-04-16 00:17:3612365 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612366 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
12367 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1912368 r->Start();
12369 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412370
[email protected]255620da2013-08-19 13:14:2912371 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2412372
[email protected]f7022f32014-08-21 16:32:1912373 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2412374 EXPECT_EQ(1, d->response_started_count());
12375 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4712376 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2412377 }
12378}
ricea3a1c71f2016-06-17 10:05:2612379
12380TEST_F(URLRequestTestFTP, RawBodyBytes) {
12381 ASSERT_TRUE(ftp_test_server_.Start());
12382
12383 TestDelegate d;
12384 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612385 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
12386 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2612387 req->Start();
12388 base::RunLoop().Run();
12389
12390 EXPECT_EQ(6, req->GetRawBodyBytes());
12391}
12392
brettwa1228ebb2016-10-28 03:51:3412393#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5112394
ttuttlec0c828492015-05-15 01:25:5512395TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
12396 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612397 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12398 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512399
12400 EXPECT_FALSE(req->response_info().network_accessed);
12401
12402 req->Start();
12403 base::RunLoop().Run();
12404
12405 EXPECT_EQ(1, default_network_delegate_.completed_requests());
12406 EXPECT_FALSE(req->response_info().network_accessed);
12407}
12408
12409TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
12410 MockHostResolver host_resolver;
12411 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
12412 TestURLRequestContext context(true);
12413 context.set_network_delegate(&network_delegate);
12414 context.set_host_resolver(&host_resolver);
12415 host_resolver.rules()->AddSimulatedFailure("*");
12416 context.Init();
12417
12418 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1612419 std::unique_ptr<URLRequest> req(
12420 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
12421 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5512422
12423 EXPECT_FALSE(req->response_info().network_accessed);
12424
12425 req->Start();
12426 base::RunLoop().Run();
12427 EXPECT_TRUE(req->response_info().network_accessed);
12428}
12429
mmenkeed0498b2015-12-08 23:20:4212430// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2212431// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4212432TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2212433 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3612434 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1612435 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
12436 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2212437
danakj8522a25b2016-04-16 00:17:3612438 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2212439 req.get(), &default_network_delegate_,
12440 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4212441 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
12442 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2212443
12444 req->Start();
12445 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2212446 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5012447 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2212448 EXPECT_EQ(0, d.received_redirect_count());
12449}
12450
Andrey Kosyakov2e893e62017-08-31 17:00:5212451TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412452 ASSERT_TRUE(http_test_server()->Start());
12453 TestURLRequestContext context;
12454 GURL url(http_test_server()->GetURL("/cachetime"));
12455 TestDelegate delegate;
12456 HttpRequestHeaders extra_headers;
12457 extra_headers.SetHeader("X-Foo", "bar");
12458
12459 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212460 HttpRawRequestHeaders raw_req_headers;
12461 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12462
Andrey Kosyakov83a6eee2017-08-14 19:20:0412463 std::unique_ptr<URLRequest> r(context.CreateRequest(
12464 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12465 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212466 r->SetRequestHeadersCallback(base::Bind(
12467 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12468 r->SetResponseHeadersCallback(base::Bind(
12469 [](scoped_refptr<const HttpResponseHeaders>* left,
12470 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12471 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412472 r->Start();
12473 while (!delegate.response_started_count())
12474 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212475 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412476 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212477 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412478 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212479 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412480 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212481 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12482 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12483 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12484 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412485 }
12486 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412487 std::unique_ptr<URLRequest> r(context.CreateRequest(
12488 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12489 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212490 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412491 FAIL() << "Callback should not be called unless request is sent";
12492 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212493 r->SetResponseHeadersCallback(
12494 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12495 FAIL() << "Callback should not be called unless request is sent";
12496 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412497 r->Start();
12498 base::RunLoop().Run();
12499 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412500 }
12501}
12502
Andrey Kosyakov2e893e62017-08-31 17:00:5212503TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412504 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212505 HttpRawRequestHeaders raw_req_headers;
12506 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12507
Andrey Kosyakov83a6eee2017-08-14 19:20:0412508 TestURLRequestContext context;
12509 TestDelegate delegate;
12510 HttpRequestHeaders extra_headers;
12511 extra_headers.SetHeader("X-Foo", "bar");
12512 delegate.set_quit_on_redirect(true);
12513 GURL url(http_test_server()->GetURL("/redirect-test.html"));
12514 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12515 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12516 r->SetExtraRequestHeaders(extra_headers);
12517 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212518 base::Unretained(&raw_req_headers)));
12519 r->SetResponseHeadersCallback(base::Bind(
12520 [](scoped_refptr<const HttpResponseHeaders>* left,
12521 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12522 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412523 r->Start();
12524 base::RunLoop().Run();
12525
12526 ASSERT_EQ(1, delegate.received_redirect_count());
12527 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212528 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412529 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212530 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412531 EXPECT_EQ("gzip, deflate", value);
12532 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212533 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12534 raw_req_headers.request_line());
12535 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12536 EXPECT_EQ(302, raw_resp_headers->response_code());
12537 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412538
Andrey Kosyakov2e893e62017-08-31 17:00:5212539 raw_req_headers = HttpRawRequestHeaders();
12540 raw_resp_headers = nullptr;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412541 r->FollowDeferredRedirect();
12542 base::RunLoop().Run();
Andrey Kosyakov2e893e62017-08-31 17:00:5212543 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412544 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212545 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412546 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212547 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12548 raw_req_headers.request_line());
12549 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412550}
12551
Andrey Kosyakov2e893e62017-08-31 17:00:5212552TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412553 TestDelegate request_delegate;
12554
12555 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12556 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12557 TRAFFIC_ANNOTATION_FOR_TESTS));
12558 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12559 FAIL() << "Callback should not be called unless request is sent";
12560 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212561 r->SetResponseHeadersCallback(
12562 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12563 FAIL() << "Callback should not be called unless request is sent";
12564 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412565 r->Start();
12566 base::RunLoop().Run();
12567 EXPECT_FALSE(r->is_pending());
12568}
12569
Andrey Kosyakov2e893e62017-08-31 17:00:5212570TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412571 ASSERT_TRUE(http_test_server()->Start());
12572 GURL url(http_test_server()->GetURL("/auth-basic"));
12573
12574 TestURLRequestContext context;
12575 TestDelegate delegate;
12576
12577 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12578 HttpRequestHeaders extra_headers;
12579 extra_headers.SetHeader("X-Foo", "bar");
12580
Andrey Kosyakov2e893e62017-08-31 17:00:5212581 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12582 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412583
Andrey Kosyakov2e893e62017-08-31 17:00:5212584 using RespHeadersVector =
12585 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12586 RespHeadersVector raw_resp_headers;
12587
12588 auto req_headers_callback = base::Bind(
12589 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12590 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12591 },
12592 &raw_req_headers);
12593 auto resp_headers_callback = base::Bind(
12594 [](RespHeadersVector* vec,
12595 scoped_refptr<const HttpResponseHeaders> headers) {
12596 vec->push_back(headers);
12597 },
12598 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412599 std::unique_ptr<URLRequest> r(context.CreateRequest(
12600 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12601 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212602 r->SetRequestHeadersCallback(req_headers_callback);
12603 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412604 r->Start();
12605 base::RunLoop().Run();
12606 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212607 ASSERT_EQ(raw_req_headers.size(), 2u);
12608 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412609 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212610 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12611 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412612 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212613 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12614 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412615 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212616 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12617 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12618 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12619 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12620
12621 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12622 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12623 r2->SetExtraRequestHeaders(extra_headers);
12624 r2->SetRequestHeadersCallback(req_headers_callback);
12625 r2->SetResponseHeadersCallback(resp_headers_callback);
12626 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12627 r2->Start();
12628 base::RunLoop().Run();
12629 EXPECT_FALSE(r2->is_pending());
12630 ASSERT_EQ(raw_req_headers.size(), 3u);
12631 ASSERT_EQ(raw_resp_headers.size(), 3u);
12632 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12633 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12634 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12635 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412636}
12637
Andrey Kosyakov2e893e62017-08-31 17:00:5212638TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412639 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12640 TestDelegate d;
12641 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12642 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12643 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212644 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412645 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212646 r->SetResponseHeadersCallback(
12647 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12648 FAIL() << "Callback should not be called for non-HTTP schemes";
12649 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412650 r->Start();
12651 base::RunLoop().Run();
12652 EXPECT_FALSE(r->is_pending());
12653}
12654
Paul Jensen60e45532018-02-19 16:04:1812655// Test that URLRequests get properly tagged.
12656#if defined(OS_ANDROID)
12657TEST_F(URLRequestTestHTTP, TestTagging) {
12658 ASSERT_TRUE(http_test_server()->Start());
12659
12660 // The tag under which the system reports untagged traffic.
12661 static const int32_t UNTAGGED_TAG = 0;
12662
12663 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12664
12665 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12666 TestDelegate delegate;
12667 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12668 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12669 TRAFFIC_ANNOTATION_FOR_TESTS));
12670 EXPECT_EQ(SocketTag(), req->socket_tag());
12671 req->Start();
12672 base::RunLoop().Run();
12673
12674 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12675
12676 int32_t tag_val1 = 0x12345678;
12677 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12678 old_traffic = GetTaggedBytes(tag_val1);
12679
12680 // Test specific tag value.
12681 req = default_context_.CreateRequest(http_test_server()->GetURL("/"),
12682 DEFAULT_PRIORITY, &delegate,
12683 TRAFFIC_ANNOTATION_FOR_TESTS);
12684 req->set_socket_tag(tag1);
12685 EXPECT_EQ(tag1, req->socket_tag());
12686 req->Start();
12687 base::RunLoop().Run();
12688
12689 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12690}
12691#endif
12692
[email protected]7461a402011-03-24 23:19:5112693} // namespace net