blob: 4756d558f7c5c42c599e6f6ab66676eaae926810 [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"
mmenkefb18c772015-09-30 22:22:50111#include "net/test/url_request/url_request_failed_job.h"
rhalavatib7bd7c792017-04-27 05:25:16112#include "net/traffic_annotation/network_traffic_annotation_test_helper.h"
[email protected]e0f35c92013-05-08 16:04:34113#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43114#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52115#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50116#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14117#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50118#include "net/url_request/url_request_intercepting_job_factory.h"
119#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49120#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51121#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47122#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44123#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01124#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52125#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15126#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52127
Eric Romanefddd0a2017-10-10 02:14:25128#if defined(OS_FUCHSIA)
129#define USE_BUILTIN_CERT_VERIFIER
130#endif
131
brettwa1228ebb2016-10-28 03:51:34132#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55133#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29134#include "net/url_request/file_protocol_handler.h"
135#include "net/url_request/url_request_file_dir_job.h"
136#endif
137
brettwa1228ebb2016-10-28 03:51:34138#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47139#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29140#include "net/url_request/ftp_protocol_handler.h"
141#endif
142
[email protected]dffe8242012-03-20 15:14:27143#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48144#include "base/win/scoped_com_initializer.h"
[email protected]dffe8242012-03-20 15:14:27145#endif
146
mmenkefd9d15c2017-06-29 13:45:54147#if BUILDFLAG(ENABLE_REPORTING)
Julia Tuttlecba7d222018-02-23 19:37:27148#include "net/network_error_logging/network_error_logging_service.h"
Julia Tuttle91a655d2018-01-26 18:03:03149#include "net/reporting/reporting_policy.h"
mmenkefd9d15c2017-06-29 13:45:54150#include "net/reporting/reporting_service.h"
151#endif // BUILDFLAG(ENABLE_REPORTING)
152
Matt Muellerfb271992018-01-30 18:10:48153#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:25154#include "net/cert/cert_net_fetcher.h"
155#include "net/cert_net/cert_net_fetcher_impl.h"
156#endif
157
158#if defined(USE_NSS_CERTS)
159#include "net/cert_net/nss_ocsp.h"
160#endif
161
robpercival214763f2016-07-01 23:27:01162using net::test::IsError;
163using net::test::IsOk;
164
[email protected]ad65a3e2013-12-25 18:18:01165using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33166using base::Time;
halton.huoe4e45742014-12-08 07:55:46167using std::string;
[email protected]e1acf6f2008-10-27 20:43:33168
[email protected]7461a402011-03-24 23:19:51169namespace net {
170
initial.commit586acc5fe2008-07-26 22:42:52171namespace {
172
Martijn Croonenb1383da2017-10-11 11:56:35173namespace test_default {
174#include "net/http/transport_security_state_static_unittest_default.h"
xunjieli815ad5b2017-07-18 15:51:35175}
176
[email protected]42cba2fb2013-03-29 19:58:57177const base::string16 kChrome(ASCIIToUTF16("chrome"));
178const base::string16 kSecret(ASCIIToUTF16("secret"));
179const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44180
mmenke9f2ec60c2015-06-01 20:59:47181const base::FilePath::CharType kTestFilePath[] =
182 FILE_PATH_LITERAL("net/data/url_request_unittest");
183
Sergey Ulanovc4580e72017-09-13 23:30:11184#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
185 !defined(OS_FUCHSIA)
mmenke9f2ec60c2015-06-01 20:59:47186// Test file used in most FTP tests.
187const char kFtpTestFile[] = "BullRunSpeech.txt";
188#endif
189
[email protected]2bba3252013-04-08 19:50:59190// Tests load timing information in the case a fresh connection was used, with
191// no proxy.
[email protected]cba24642014-08-15 20:49:59192void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25193 int connect_timing_flags) {
194 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19195 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25196
197 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
198 EXPECT_FALSE(load_timing_info.request_start.is_null());
199
200 EXPECT_LE(load_timing_info.request_start,
201 load_timing_info.connect_timing.connect_start);
202 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
203 connect_timing_flags);
204 EXPECT_LE(load_timing_info.connect_timing.connect_end,
205 load_timing_info.send_start);
206 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
207 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
208
[email protected]58e32bb2013-01-21 18:23:25209 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
210 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
211}
212
[email protected]2bba3252013-04-08 19:50:59213// Same as above, but with proxy times.
214void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59215 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59216 int connect_timing_flags) {
217 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19218 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59219
220 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
221 EXPECT_FALSE(load_timing_info.request_start.is_null());
222
223 EXPECT_LE(load_timing_info.request_start,
224 load_timing_info.proxy_resolve_start);
225 EXPECT_LE(load_timing_info.proxy_resolve_start,
226 load_timing_info.proxy_resolve_end);
227 EXPECT_LE(load_timing_info.proxy_resolve_end,
228 load_timing_info.connect_timing.connect_start);
229 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
230 connect_timing_flags);
231 EXPECT_LE(load_timing_info.connect_timing.connect_end,
232 load_timing_info.send_start);
233 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
234 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
235}
236
237// Same as above, but with a reused socket and proxy times.
238void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59239 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59240 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19241 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59242
243 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
244 EXPECT_FALSE(load_timing_info.request_start.is_null());
245
246 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
247
248 EXPECT_LE(load_timing_info.request_start,
249 load_timing_info.proxy_resolve_start);
250 EXPECT_LE(load_timing_info.proxy_resolve_start,
251 load_timing_info.proxy_resolve_end);
252 EXPECT_LE(load_timing_info.proxy_resolve_end,
253 load_timing_info.send_start);
254 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
255 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
256}
257
brettwa1228ebb2016-10-28 03:51:34258#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25259// Tests load timing information in the case of a cache hit, when no cache
260// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17261base::StringPiece TestNetResourceProvider(int key) {
262 return "header";
263}
264
265void FillBuffer(char* buffer, size_t len) {
266 static bool called = false;
267 if (!called) {
268 called = true;
269 int seed = static_cast<int>(Time::Now().ToInternalValue());
270 srand(seed);
271 }
272
273 for (size_t i = 0; i < len; i++) {
274 buffer[i] = static_cast<char>(rand());
275 if (!buffer[i])
276 buffer[i] = 'g';
277 }
278}
xunjielia6888202015-04-14 21:34:25279#endif
[email protected]e3a85452013-11-14 01:46:17280
[email protected]3b23a222013-05-15 21:33:25281void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59282 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25283 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19284 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25285
286 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
287 EXPECT_FALSE(load_timing_info.request_start.is_null());
288
289 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
290 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
291 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
292 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
293
294 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
295 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
296}
297
Sergey Ulanovc4580e72017-09-13 23:30:11298#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
299 !defined(OS_FUCHSIA)
[email protected]3b23a222013-05-15 21:33:25300// Tests load timing in the case that there is no HTTP response. This can be
301// used to test in the case of errors or non-HTTP requests.
302void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59303 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25304 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19305 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25306
307 // Only the request times should be non-null.
308 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
309 EXPECT_FALSE(load_timing_info.request_start.is_null());
310
311 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
312
313 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
314 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
315 EXPECT_TRUE(load_timing_info.send_start.is_null());
316 EXPECT_TRUE(load_timing_info.send_end.is_null());
317 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
318}
xunjielia6888202015-04-14 21:34:25319#endif
[email protected]58e32bb2013-01-21 18:23:25320
mmenkefb18c772015-09-30 22:22:50321// Test power monitor source that can simulate entering suspend mode. Can't use
322// the one in base/ because it insists on bringing its own MessageLoop.
323class TestPowerMonitorSource : public base::PowerMonitorSource {
324 public:
Chris Watkins7a41d3552017-12-01 02:13:27325 TestPowerMonitorSource() = default;
326 ~TestPowerMonitorSource() override = default;
mmenkefb18c772015-09-30 22:22:50327
328 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
329
330 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
331
332 bool IsOnBatteryPowerImpl() override { return false; }
333
334 private:
335 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
336};
337
mmenkeed0498b2015-12-08 23:20:42338// Job that allows monitoring of its priority.
339class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
340 public:
341 // The latest priority of the job is always written to |request_priority_|.
342 PriorityMonitoringURLRequestJob(URLRequest* request,
343 NetworkDelegate* network_delegate,
344 RequestPriority* request_priority)
345 : URLRequestTestJob(request, network_delegate),
346 request_priority_(request_priority) {
347 *request_priority_ = DEFAULT_PRIORITY;
348 }
349
350 void SetPriority(RequestPriority priority) override {
351 *request_priority_ = priority;
352 URLRequestTestJob::SetPriority(priority);
353 }
354
355 private:
356 RequestPriority* const request_priority_;
357};
358
[email protected]71c64f62008-11-15 04:36:51359// Do a case-insensitive search through |haystack| for |needle|.
360bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50361 std::string::const_iterator it = std::search(
362 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
363 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51364 return it != haystack.end();
365}
366
danakj8522a25b2016-04-16 00:17:36367std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
368 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28369 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48370 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23371}
372
[email protected]96adadb2010-08-28 01:16:17373// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51374void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17375 // -1 means unknown. 0 means no encryption.
376 EXPECT_GT(ssl_info.security_bits, 0);
377
378 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14379 uint16_t cipher_suite =
380 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29381 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17382}
383
[email protected]79e1fd62013-06-20 06:50:04384void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
385 const GURL& host_url) {
386 std::string sent_value;
387
388 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
389 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
390
391 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
392 EXPECT_EQ("keep-alive", sent_value);
393}
394
[email protected]dc5a5cf2012-09-26 02:49:30395// A network delegate that allows the user to choose a subset of request stages
396// to block in. When blocking, the delegate can do one of the following:
397// * synchronously return a pre-specified error code, or
398// * asynchronously return that value via an automatically called callback,
399// or
400// * block and wait for the user to do a callback.
401// Additionally, the user may also specify a redirect URL -- then each request
402// with the current URL different from the redirect target will be redirected
403// to that target, in the on-before-URL-request stage, independent of whether
404// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12405class BlockingNetworkDelegate : public TestNetworkDelegate {
406 public:
[email protected]dc5a5cf2012-09-26 02:49:30407 // Stages in which the delegate can block.
408 enum Stage {
[email protected]9045b8822012-01-13 20:35:35409 NOT_BLOCKED = 0,
410 ON_BEFORE_URL_REQUEST = 1 << 0,
411 ON_BEFORE_SEND_HEADERS = 1 << 1,
412 ON_HEADERS_RECEIVED = 1 << 2,
413 ON_AUTH_REQUIRED = 1 << 3
414 };
415
[email protected]dc5a5cf2012-09-26 02:49:30416 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59417 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30418 enum BlockMode {
419 SYNCHRONOUS, // No callback, returns specified return values.
420 AUTO_CALLBACK, // |this| posts a task to run the callback using the
421 // specified return codes.
422 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
423 // |auth_retval_| are ignored. In every blocking stage the
424 // message loop is quit.
[email protected]dc5a5cf2012-09-26 02:49:30425 };
426
[email protected]dc5a5cf2012-09-26 02:49:30427 // Creates a delegate which does not block at all.
428 explicit BlockingNetworkDelegate(BlockMode block_mode);
429
430 // For users to trigger a callback returning |response|.
431 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
432 // Only call if |block_mode_| == USER_CALLBACK.
433 void DoCallback(int response);
434 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
435
436 // Setters.
437 void set_retval(int retval) {
438 ASSERT_NE(USER_CALLBACK, block_mode_);
439 ASSERT_NE(ERR_IO_PENDING, retval);
440 ASSERT_NE(OK, retval);
441 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35442 }
443
[email protected]dc5a5cf2012-09-26 02:49:30444 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
445 // |auth_credentials_| will be passed with the response.
446 void set_auth_retval(AuthRequiredResponse auth_retval) {
447 ASSERT_NE(USER_CALLBACK, block_mode_);
448 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
449 auth_retval_ = auth_retval;
450 }
451 void set_auth_credentials(const AuthCredentials& auth_credentials) {
452 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35453 }
454
[email protected]dc5a5cf2012-09-26 02:49:30455 void set_redirect_url(const GURL& url) {
456 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35457 }
458
[email protected]dc5a5cf2012-09-26 02:49:30459 void set_block_on(int block_on) {
460 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35461 }
462
[email protected]dc5a5cf2012-09-26 02:49:30463 // Allows the user to check in which state did we block.
464 Stage stage_blocked_for_callback() const {
465 EXPECT_EQ(USER_CALLBACK, block_mode_);
466 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35467 }
468
469 private:
[email protected]dc5a5cf2012-09-26 02:49:30470 void RunCallback(int response, const CompletionCallback& callback);
471 void RunAuthCallback(AuthRequiredResponse response,
472 const AuthCallback& callback);
473
[email protected]9045b8822012-01-13 20:35:35474 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20475 int OnBeforeURLRequest(URLRequest* request,
476 const CompletionCallback& callback,
477 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35478
ryansturm2343cb62016-06-15 01:09:00479 int OnBeforeStartTransaction(URLRequest* request,
480 const CompletionCallback& callback,
481 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35482
dchengb03027d2014-10-21 12:00:20483 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35484 URLRequest* request,
485 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32486 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16487 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13488 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35489
dchengb03027d2014-10-21 12:00:20490 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35491 URLRequest* request,
492 const AuthChallengeInfo& auth_info,
493 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13494 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35495
[email protected]dc5a5cf2012-09-26 02:49:30496 // Resets the callbacks and |stage_blocked_for_callback_|.
497 void Reset();
[email protected]9045b8822012-01-13 20:35:35498
[email protected]dc5a5cf2012-09-26 02:49:30499 // Checks whether we should block in |stage|. If yes, returns an error code
500 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24501 int MaybeBlockStage(Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24502 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30503
504 // Configuration parameters, can be adjusted by public methods:
505 const BlockMode block_mode_;
506
507 // Values returned on blocking stages when mode is SYNCHRONOUS or
508 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
509 int retval_; // To be returned in non-auth stages.
510 AuthRequiredResponse auth_retval_;
511
[email protected]5f714132014-03-26 10:41:16512 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30513 int block_on_; // Bit mask: in which stages to block.
514
515 // |auth_credentials_| will be copied to |*target_auth_credential_| on
516 // callback.
517 AuthCredentials auth_credentials_;
518 AuthCredentials* target_auth_credentials_;
519
520 // Internal variables, not set by not the user:
521 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
522 // USER_CALLBACK).
523 Stage stage_blocked_for_callback_;
524
525 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35526 CompletionCallback callback_;
527 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30528
[email protected]dc5a5cf2012-09-26 02:49:30529 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
530
531 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35532};
533
[email protected]dc5a5cf2012-09-26 02:49:30534BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
535 : block_mode_(block_mode),
536 retval_(OK),
537 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
538 block_on_(0),
539 target_auth_credentials_(NULL),
540 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32541 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30542}
543
544void BlockingNetworkDelegate::DoCallback(int response) {
545 ASSERT_EQ(USER_CALLBACK, block_mode_);
546 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
547 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
548 CompletionCallback callback = callback_;
549 Reset();
550 RunCallback(response, callback);
551}
552
553void BlockingNetworkDelegate::DoAuthCallback(
554 NetworkDelegate::AuthRequiredResponse response) {
555 ASSERT_EQ(USER_CALLBACK, block_mode_);
556 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
557 AuthCallback auth_callback = auth_callback_;
558 Reset();
559 RunAuthCallback(response, auth_callback);
560}
561
562void BlockingNetworkDelegate::RunCallback(int response,
563 const CompletionCallback& callback) {
564 callback.Run(response);
565}
566
567void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
568 const AuthCallback& callback) {
569 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
570 ASSERT_TRUE(target_auth_credentials_ != NULL);
571 *target_auth_credentials_ = auth_credentials_;
572 }
573 callback.Run(response);
574}
575
576int BlockingNetworkDelegate::OnBeforeURLRequest(
577 URLRequest* request,
578 const CompletionCallback& callback,
579 GURL* new_url) {
580 if (redirect_url_ == request->url())
581 return OK; // We've already seen this request and redirected elsewhere.
582
583 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
584
585 if (!redirect_url_.is_empty())
586 *new_url = redirect_url_;
587
Helen Lib495c3802018-03-30 13:46:09588 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
[email protected]dc5a5cf2012-09-26 02:49:30589}
590
ryansturm2343cb62016-06-15 01:09:00591int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30592 URLRequest* request,
593 const CompletionCallback& callback,
594 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00595 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30596
Helen Lib495c3802018-03-30 13:46:09597 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
[email protected]dc5a5cf2012-09-26 02:49:30598}
599
600int BlockingNetworkDelegate::OnHeadersReceived(
601 URLRequest* request,
602 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32603 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16604 scoped_refptr<HttpResponseHeaders>* override_response_headers,
605 GURL* allowed_unsafe_redirect_url) {
606 TestNetworkDelegate::OnHeadersReceived(request,
607 callback,
608 original_response_headers,
609 override_response_headers,
610 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30611
Helen Lib495c3802018-03-30 13:46:09612 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
[email protected]dc5a5cf2012-09-26 02:49:30613}
614
615NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
616 URLRequest* request,
617 const AuthChallengeInfo& auth_info,
618 const AuthCallback& callback,
619 AuthCredentials* credentials) {
620 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
621 credentials);
622 // Check that the user has provided callback for the previous blocked stage.
623 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
624
625 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
626 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
627 }
628
629 target_auth_credentials_ = credentials;
630
631 switch (block_mode_) {
632 case SYNCHRONOUS:
633 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
634 *target_auth_credentials_ = auth_credentials_;
635 return auth_retval_;
636
637 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45638 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30639 FROM_HERE,
640 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
641 weak_factory_.GetWeakPtr(), auth_retval_, callback));
642 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
643
644 case USER_CALLBACK:
645 auth_callback_ = callback;
646 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45647 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17648 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30649 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
[email protected]dc5a5cf2012-09-26 02:49:30650 }
651 NOTREACHED();
652 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
653}
654
655void BlockingNetworkDelegate::Reset() {
656 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
657 stage_blocked_for_callback_ = NOT_BLOCKED;
658 callback_.Reset();
659 auth_callback_.Reset();
660}
661
662int BlockingNetworkDelegate::MaybeBlockStage(
663 BlockingNetworkDelegate::Stage stage,
[email protected]dc5a5cf2012-09-26 02:49:30664 const CompletionCallback& callback) {
665 // Check that the user has provided callback for the previous blocked stage.
666 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
667
668 if ((block_on_ & stage) == 0) {
669 return OK;
670 }
671
672 switch (block_mode_) {
673 case SYNCHRONOUS:
674 EXPECT_NE(OK, retval_);
675 return retval_;
676
677 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45678 base::ThreadTaskRunnerHandle::Get()->PostTask(
679 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
680 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30681 return ERR_IO_PENDING;
682
683 case USER_CALLBACK:
684 callback_ = callback;
685 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45686 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17687 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30688 return ERR_IO_PENDING;
[email protected]dc5a5cf2012-09-26 02:49:30689 }
690 NOTREACHED();
691 return 0;
692}
693
[email protected]d5a4dd62012-05-23 01:41:04694class TestURLRequestContextWithProxy : public TestURLRequestContext {
695 public:
696 // Does not own |delegate|.
697 TestURLRequestContextWithProxy(const std::string& proxy,
698 NetworkDelegate* delegate)
699 : TestURLRequestContext(true) {
Lily Houghton8c2f97d2018-01-22 05:06:59700 context_storage_.set_proxy_resolution_service(
Ramin Halavatica8d5252018-03-12 05:33:49701 ProxyResolutionService::CreateFixed(proxy,
702 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]d5a4dd62012-05-23 01:41:04703 set_network_delegate(delegate);
704 Init();
705 }
Chris Watkins7a41d3552017-12-01 02:13:27706 ~TestURLRequestContextWithProxy() override = default;
[email protected]d5a4dd62012-05-23 01:41:04707};
708
stefanocsbd5be5202016-06-10 03:37:55709// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01710// URI and report to be sent.
711class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55712 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01713 public:
Chris Watkins7a41d3552017-12-01 02:13:27714 MockCertificateReportSender() = default;
715 ~MockCertificateReportSender() override = default;
estark06e0dac2015-08-07 21:56:01716
meacer5d4dc5a2017-04-27 20:37:48717 void Send(const GURL& report_uri,
718 base::StringPiece content_type,
719 base::StringPiece report,
720 const base::Callback<void()>& success_callback,
721 const base::Callback<void(const GURL&, int, int)>& error_callback)
722 override {
estark06e0dac2015-08-07 21:56:01723 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44724 report.CopyToString(&latest_report_);
725 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01726 }
estark06e0dac2015-08-07 21:56:01727 const GURL& latest_report_uri() { return latest_report_uri_; }
728 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44729 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01730
731 private:
732 GURL latest_report_uri_;
733 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44734 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01735};
736
estarkcd39c11f2015-10-19 19:46:36737class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
738 public:
739 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
740};
741
dadrian612337a2016-07-20 22:36:58742// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
743// This is needed because after the certificate failure, the URLRequest will
744// retry the connection, and return a partial SSLInfo with a cached cert status.
745// The partial SSLInfo does not have the OCSP information filled out.
746class OCSPErrorTestDelegate : public TestDelegate {
747 public:
748 void OnSSLCertificateError(URLRequest* request,
749 const SSLInfo& ssl_info,
750 bool fatal) override {
751 ssl_info_ = ssl_info;
752 on_ssl_certificate_error_called_ = true;
753 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
754 }
755
756 bool on_ssl_certificate_error_called() {
757 return on_ssl_certificate_error_called_;
758 }
759
760 SSLInfo ssl_info() { return ssl_info_; }
761
762 private:
763 bool on_ssl_certificate_error_called_ = false;
764 SSLInfo ssl_info_;
765};
766
[email protected]d5a4dd62012-05-23 01:41:04767} // namespace
768
[email protected]a592c0432012-12-01 18:10:29769// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48770class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00771 public:
fdorayf33fede2017-05-11 21:18:10772 URLRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:09773 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25774 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50775 job_factory_impl_ = new URLRequestJobFactoryImpl();
776 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50777 }
bengr1bf8e942014-11-07 01:36:50778
dcheng67be2b1f2014-10-27 21:47:29779 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18780 // URLRequestJobs may post clean-up tasks on destruction.
781 base::RunLoop().RunUntilIdle();
Martijn Croonenb1383da2017-10-11 11:56:35782
783 SetTransportSecurityStateSourceForTesting(nullptr);
[email protected]e4034ad2013-09-20 08:36:18784 }
[email protected]87a09a92011-07-14 15:50:50785
dcheng2339883c2014-12-23 00:23:05786 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50787 SetUpFactory();
788 default_context_.set_job_factory(job_factory_.get());
789 default_context_.Init();
790 PlatformTest::SetUp();
791 }
792
793 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20794 job_factory_impl_->SetProtocolHandler(
Bence Béky8f9d7d3952017-10-09 19:58:04795 "data", std::make_unique<DataProtocolHandler>());
brettwa1228ebb2016-10-28 03:51:34796#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50797 job_factory_impl_->SetProtocolHandler(
Jeremy Roman0579ed62017-08-29 15:56:19798 "file", std::make_unique<FileProtocolHandler>(
ricea2deef682016-09-09 08:04:07799 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50800#endif
801 }
802
803 TestNetworkDelegate* default_network_delegate() {
804 return &default_network_delegate_;
805 }
806
807 const TestURLRequestContext& default_context() const {
808 return default_context_;
809 }
810
811
[email protected]3c5ca8c2011-09-29 01:14:51812 // Adds the TestJobInterceptor to the default context.
813 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23814 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20815 job_factory_impl_->SetProtocolHandler("http", nullptr);
816 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36817 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23818 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51819 }
820
Sergey Ulanov2e49f492017-09-14 19:37:51821 // Creates a temp test file and writes |data| to the file. The file will be
822 // deleted after the test completes.
823 void CreateTestFile(const char* data,
824 size_t data_size,
825 base::FilePath* test_file) {
826 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
827 // Get an absolute path since |temp_dir| can contain a symbolic link. As of
828 // now, Mac and Android bots return a path with a symbolic link.
829 base::FilePath absolute_temp_dir =
830 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
831
832 ASSERT_TRUE(base::CreateTemporaryFileInDir(absolute_temp_dir, test_file));
833 ASSERT_EQ(static_cast<int>(data_size),
834 base::WriteFile(*test_file, data, data_size));
835 }
836
[email protected]87a09a92011-07-14 15:50:50837 protected:
vishal.b62985ca92015-04-17 08:45:51838 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24839 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50840 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36841 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09842 TestURLRequestContext default_context_;
Sergey Ulanov2e49f492017-09-14 19:37:51843 base::ScopedTempDir temp_dir_;
[email protected]7a0bb4bf2008-11-19 21:41:48844};
845
satoruxddac0442017-05-29 06:06:18846// This NetworkDelegate is picky about what files are accessible. Only
847// whitelisted files are allowed.
848class CookieBlockingNetworkDelegate : public TestNetworkDelegate {
849 public:
Chris Watkins7a41d3552017-12-01 02:13:27850 CookieBlockingNetworkDelegate() = default;
851 ;
satoruxddac0442017-05-29 06:06:18852
853 // Adds |directory| to the access white list.
854 void AddToWhitelist(const base::FilePath& directory) {
855 whitelist_.insert(directory);
856 }
857
858 private:
859 // Returns true if |path| matches the white list.
860 bool OnCanAccessFileInternal(const base::FilePath& path) const {
861 for (const auto& directory : whitelist_) {
862 if (directory == path || directory.IsParent(path))
863 return true;
864 }
865 return false;
866 }
867
868 // Returns true only if both |original_path| and |absolute_path| match the
869 // white list.
870 bool OnCanAccessFile(const URLRequest& request,
871 const base::FilePath& original_path,
872 const base::FilePath& absolute_path) const override {
873 return (OnCanAccessFileInternal(original_path) &&
874 OnCanAccessFileInternal(absolute_path));
875 }
876
877 std::set<base::FilePath> whitelist_;
878
879 DISALLOW_COPY_AND_ASSIGN(CookieBlockingNetworkDelegate);
880};
881
[email protected]316c1e5e2012-09-12 15:17:44882TEST_F(URLRequestTest, AboutBlankTest) {
883 TestDelegate d;
884 {
rhalavatib7bd7c792017-04-27 05:25:16885 std::unique_ptr<URLRequest> r(
886 default_context_.CreateRequest(GURL("about:blank"), DEFAULT_PRIORITY,
887 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44888
[email protected]f7022f32014-08-21 16:32:19889 r->Start();
890 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44891
[email protected]255620da2013-08-19 13:14:29892 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44893
[email protected]f7022f32014-08-21 16:32:19894 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44895 EXPECT_FALSE(d.received_data_before_response());
896 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19897 EXPECT_EQ("", r->GetSocketAddress().host());
898 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04899
900 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19901 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44902 }
903}
904
905TEST_F(URLRequestTest, DataURLImageTest) {
906 TestDelegate d;
907 {
908 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36909 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
910 GURL("data:image/png;base64,"
911 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
912 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
913 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
914 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
915 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
916 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
917 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
918 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
919 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
920 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
921 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
922 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
923 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
924 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
925 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
926 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
927 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
928 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
929 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
rhalavatib7bd7c792017-04-27 05:25:16930 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44931
[email protected]f7022f32014-08-21 16:32:19932 r->Start();
933 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44934
[email protected]255620da2013-08-19 13:14:29935 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44936
[email protected]f7022f32014-08-21 16:32:19937 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44938 EXPECT_FALSE(d.received_data_before_response());
939 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19940 EXPECT_EQ("", r->GetSocketAddress().host());
941 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04942
943 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19944 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44945 }
946}
947
brettwa1228ebb2016-10-28 03:51:34948#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44949TEST_F(URLRequestTest, FileTest) {
Sergey Ulanov2e49f492017-09-14 19:37:51950 const char kTestFileContent[] = "Hello";
951 base::FilePath test_file;
952 ASSERT_NO_FATAL_FAILURE(
953 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
kraush5a645822016-04-07 18:35:04954
Sergey Ulanov2e49f492017-09-14 19:37:51955 GURL test_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:44956
957 TestDelegate d;
958 {
rhalavatib7bd7c792017-04-27 05:25:16959 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51960 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:44961
[email protected]f7022f32014-08-21 16:32:19962 r->Start();
963 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44964
[email protected]255620da2013-08-19 13:14:29965 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44966
[email protected]f7022f32014-08-21 16:32:19967 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44968 EXPECT_EQ(1, d.response_started_count());
969 EXPECT_FALSE(d.received_data_before_response());
Sergey Ulanov2e49f492017-09-14 19:37:51970 EXPECT_EQ(d.bytes_received(), static_cast<int>(sizeof(kTestFileContent)));
[email protected]f7022f32014-08-21 16:32:19971 EXPECT_EQ("", r->GetSocketAddress().host());
972 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04973
974 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19975 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44976 }
977}
978
[email protected]ba40bb762012-12-17 07:11:04979TEST_F(URLRequestTest, FileTestCancel) {
Sergey Ulanov2e49f492017-09-14 19:37:51980 const char kTestFileContent[] = "Hello";
981 base::FilePath test_file;
982 ASSERT_NO_FATAL_FAILURE(
983 CreateTestFile(kTestFileContent, sizeof(kTestFileContent), &test_file));
984
985 GURL test_url = FilePathToFileURL(test_file);
[email protected]ba40bb762012-12-17 07:11:04986
987 TestDelegate d;
988 {
rhalavatib7bd7c792017-04-27 05:25:16989 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
Sergey Ulanov2e49f492017-09-14 19:37:51990 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]ba40bb762012-12-17 07:11:04991
[email protected]f7022f32014-08-21 16:32:19992 r->Start();
993 EXPECT_TRUE(r->is_pending());
994 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04995 }
[email protected]79e1fd62013-06-20 06:50:04996 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04997 // destroyed.
[email protected]255620da2013-08-19 13:14:29998 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04999}
1000
[email protected]316c1e5e2012-09-12 15:17:441001TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
1002 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361003 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441004 FillBuffer(buffer.get(), buffer_size);
1005
Sergey Ulanov2e49f492017-09-14 19:37:511006 base::FilePath test_file;
1007 ASSERT_NO_FATAL_FAILURE(
1008 CreateTestFile(buffer.get(), buffer_size, &test_file));
1009 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441010
1011 const size_t first_byte_position = 500;
1012 const size_t last_byte_position = buffer_size - first_byte_position;
1013 const size_t content_length = last_byte_position - first_byte_position + 1;
1014 std::string partial_buffer_string(buffer.get() + first_byte_position,
1015 buffer.get() + last_byte_position + 1);
1016
1017 TestDelegate d;
1018 {
rhalavatib7bd7c792017-04-27 05:25:161019 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1020 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441021
1022 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381023 headers.SetHeader(
1024 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591025 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:381026 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191027 r->SetExtraRequestHeaders(headers);
1028 r->Start();
1029 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441030
[email protected]255620da2013-08-19 13:14:291031 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191032 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441033 EXPECT_EQ(1, d.response_started_count());
1034 EXPECT_FALSE(d.received_data_before_response());
1035 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1036 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1037 EXPECT_TRUE(partial_buffer_string == d.data_received());
1038 }
[email protected]316c1e5e2012-09-12 15:17:441039}
1040
1041TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1042 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361043 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441044 FillBuffer(buffer.get(), buffer_size);
1045
Sergey Ulanov2e49f492017-09-14 19:37:511046 base::FilePath test_file;
1047 ASSERT_NO_FATAL_FAILURE(
1048 CreateTestFile(buffer.get(), buffer_size, &test_file));
1049 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441050
1051 const size_t first_byte_position = 500;
1052 const size_t last_byte_position = buffer_size - 1;
1053 const size_t content_length = last_byte_position - first_byte_position + 1;
1054 std::string partial_buffer_string(buffer.get() + first_byte_position,
1055 buffer.get() + last_byte_position + 1);
1056
1057 TestDelegate d;
1058 {
rhalavatib7bd7c792017-04-27 05:25:161059 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1060 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441061
1062 HttpRequestHeaders headers;
1063 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591064 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381065 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191066 r->SetExtraRequestHeaders(headers);
1067 r->Start();
1068 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441069
[email protected]255620da2013-08-19 13:14:291070 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191071 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441072 EXPECT_EQ(1, d.response_started_count());
1073 EXPECT_FALSE(d.received_data_before_response());
1074 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1075 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1076 EXPECT_TRUE(partial_buffer_string == d.data_received());
1077 }
[email protected]316c1e5e2012-09-12 15:17:441078}
1079
1080TEST_F(URLRequestTest, FileTestMultipleRanges) {
1081 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361082 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441083 FillBuffer(buffer.get(), buffer_size);
1084
Sergey Ulanov2e49f492017-09-14 19:37:511085 base::FilePath test_file;
1086 ASSERT_NO_FATAL_FAILURE(
1087 CreateTestFile(buffer.get(), buffer_size, &test_file));
1088 GURL temp_url = FilePathToFileURL(test_file);
[email protected]316c1e5e2012-09-12 15:17:441089
1090 TestDelegate d;
1091 {
rhalavatib7bd7c792017-04-27 05:25:161092 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1093 temp_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:441094
1095 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381096 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191097 r->SetExtraRequestHeaders(headers);
1098 r->Start();
1099 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441100
[email protected]255620da2013-08-19 13:14:291101 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441102 EXPECT_TRUE(d.request_failed());
1103 }
[email protected]316c1e5e2012-09-12 15:17:441104}
1105
[email protected]3ca8b362013-11-11 22:18:071106TEST_F(URLRequestTest, AllowFileURLs) {
Sergey Ulanov2e49f492017-09-14 19:37:511107 std::string test_data("monkey");
[email protected]3ca8b362013-11-11 22:18:071108 base::FilePath test_file;
Sergey Ulanov2e49f492017-09-14 19:37:511109 ASSERT_NO_FATAL_FAILURE(
1110 CreateTestFile(test_data.data(), test_data.size(), &test_file));
1111
satoruxddac0442017-05-29 06:06:181112 // The directory part of the path returned from CreateTemporaryFileInDir()
1113 // can be slightly different from |absolute_temp_dir| on Windows.
1114 // Example: C:\\Users\\CHROME~2 -> C:\\Users\\chrome-bot
1115 // Hence the test should use the directory name of |test_file|, rather than
1116 // |absolute_temp_dir|, for whitelisting.
1117 base::FilePath real_temp_dir = test_file.DirName();
[email protected]cba24642014-08-15 20:49:591118 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071119 {
1120 TestDelegate d;
satoruxddac0442017-05-29 06:06:181121 CookieBlockingNetworkDelegate network_delegate;
1122 network_delegate.AddToWhitelist(real_temp_dir);
[email protected]3ca8b362013-11-11 22:18:071123 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161124 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1125 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191126 r->Start();
[email protected]3ca8b362013-11-11 22:18:071127 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181128 // This should be allowed as the file path is whitelisted.
[email protected]3ca8b362013-11-11 22:18:071129 EXPECT_FALSE(d.request_failed());
1130 EXPECT_EQ(test_data, d.data_received());
1131 }
1132
1133 {
1134 TestDelegate d;
satoruxddac0442017-05-29 06:06:181135 CookieBlockingNetworkDelegate network_delegate;
[email protected]3ca8b362013-11-11 22:18:071136 default_context_.set_network_delegate(&network_delegate);
rhalavatib7bd7c792017-04-27 05:25:161137 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1138 test_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191139 r->Start();
[email protected]3ca8b362013-11-11 22:18:071140 base::RunLoop().Run();
satoruxddac0442017-05-29 06:06:181141 // This should be rejected as the file path is not whitelisted.
[email protected]3ca8b362013-11-11 22:18:071142 EXPECT_TRUE(d.request_failed());
1143 EXPECT_EQ("", d.data_received());
satoruxddac0442017-05-29 06:06:181144 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
[email protected]3ca8b362013-11-11 22:18:071145 }
1146}
1147
Kevin Marshalla9f05ec2017-07-14 02:10:051148#if defined(OS_POSIX) && !defined(OS_FUCHSIA) // Because of symbolic links.
satoruxddac0442017-05-29 06:06:181149
1150TEST_F(URLRequestTest, SymlinksToFiles) {
Sergey Ulanov2e49f492017-09-14 19:37:511151 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181152 // Get an absolute path since temp_dir can contain a symbolic link.
1153 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511154 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181155
1156 // Create a good directory (will be whitelisted) and a good file.
1157 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1158 ASSERT_TRUE(base::CreateDirectory(good_dir));
1159 base::FilePath good_file;
1160 ASSERT_TRUE(base::CreateTemporaryFileInDir(good_dir, &good_file));
1161 std::string good_data("good");
1162 base::WriteFile(good_file, good_data.data(), good_data.size());
1163 // See the comment in AllowFileURLs() for why this is done.
1164 base::FilePath real_good_dir = good_file.DirName();
1165
1166 // Create a bad directory (will not be whitelisted) and a bad file.
1167 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1168 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1169 base::FilePath bad_file;
1170 ASSERT_TRUE(base::CreateTemporaryFileInDir(bad_dir, &bad_file));
1171 std::string bad_data("bad");
1172 base::WriteFile(bad_file, bad_data.data(), bad_data.size());
1173
1174 // This symlink will point to the good file. Access to the symlink will be
1175 // allowed as both the symlink and the destination file are in the same
1176 // good directory.
1177 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1178 ASSERT_TRUE(base::CreateSymbolicLink(good_file, good_symlink));
1179 GURL good_file_url = FilePathToFileURL(good_symlink);
1180 // This symlink will point to the bad file. Even though the symlink is in
1181 // the good directory, access to the symlink will be rejected since it
1182 // points to the bad file.
1183 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1184 ASSERT_TRUE(base::CreateSymbolicLink(bad_file, bad_symlink));
1185 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1186
1187 CookieBlockingNetworkDelegate network_delegate;
1188 network_delegate.AddToWhitelist(real_good_dir);
1189 {
1190 TestDelegate d;
1191 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371192 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1193 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181194 r->Start();
1195 base::RunLoop().Run();
1196 // good_file_url should be allowed.
1197 EXPECT_FALSE(d.request_failed());
1198 EXPECT_EQ(good_data, d.data_received());
1199 }
1200
1201 {
1202 TestDelegate d;
1203 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371204 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1205 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181206 r->Start();
1207 base::RunLoop().Run();
1208 // bad_file_url should be rejected.
1209 EXPECT_TRUE(d.request_failed());
1210 EXPECT_EQ("", d.data_received());
1211 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1212 }
1213}
1214
1215TEST_F(URLRequestTest, SymlinksToDirs) {
Sergey Ulanov2e49f492017-09-14 19:37:511216 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
satoruxddac0442017-05-29 06:06:181217 // Get an absolute path since temp_dir can contain a symbolic link.
1218 base::FilePath absolute_temp_dir =
Sergey Ulanov2e49f492017-09-14 19:37:511219 base::MakeAbsoluteFilePath(temp_dir_.GetPath());
satoruxddac0442017-05-29 06:06:181220
1221 // Create a good directory (will be whitelisted).
1222 base::FilePath good_dir = absolute_temp_dir.AppendASCII("good");
1223 ASSERT_TRUE(base::CreateDirectory(good_dir));
1224
1225 // Create a bad directory (will not be whitelisted).
1226 base::FilePath bad_dir = absolute_temp_dir.AppendASCII("bad");
1227 ASSERT_TRUE(base::CreateDirectory(bad_dir));
1228
1229 // This symlink will point to the good directory. Access to the symlink
1230 // will be allowed as the symlink is in the good dir that'll be white
1231 // listed.
1232 base::FilePath good_symlink = good_dir.AppendASCII("good_symlink");
1233 ASSERT_TRUE(base::CreateSymbolicLink(good_dir, good_symlink));
1234 GURL good_file_url = FilePathToFileURL(good_symlink);
1235 // This symlink will point to the bad directory. Even though the symlink is
1236 // in the good directory, access to the symlink will be rejected since it
1237 // points to the bad directory.
1238 base::FilePath bad_symlink = good_dir.AppendASCII("bad_symlink");
1239 ASSERT_TRUE(base::CreateSymbolicLink(bad_dir, bad_symlink));
1240 GURL bad_file_url = FilePathToFileURL(bad_symlink);
1241
1242 CookieBlockingNetworkDelegate network_delegate;
1243 network_delegate.AddToWhitelist(good_dir);
1244 {
1245 TestDelegate d;
1246 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371247 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1248 good_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181249 r->Start();
1250 base::RunLoop().Run();
1251 // good_file_url should be allowed.
1252 EXPECT_FALSE(d.request_failed());
1253 ASSERT_NE(d.data_received().find("good_symlink"), std::string::npos);
1254 }
1255
1256 {
1257 TestDelegate d;
1258 default_context_.set_network_delegate(&network_delegate);
Ramin Halavati91cbba342017-07-19 13:13:371259 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
1260 bad_file_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
satoruxddac0442017-05-29 06:06:181261 r->Start();
1262 base::RunLoop().Run();
1263 // bad_file_url should be rejected.
1264 EXPECT_TRUE(d.request_failed());
1265 EXPECT_EQ("", d.data_received());
1266 EXPECT_EQ(ERR_ACCESS_DENIED, d.request_status());
1267 }
1268}
1269
Kevin Marshalla9f05ec2017-07-14 02:10:051270#endif // defined(OS_POSIX) && !defined(OS_FUCHSIA)
[email protected]316c1e5e2012-09-12 15:17:441271
1272TEST_F(URLRequestTest, FileDirCancelTest) {
1273 // Put in mock resource provider.
1274 NetModule::SetResourceProvider(TestNetResourceProvider);
1275
1276 TestDelegate d;
1277 {
[email protected]6cdfd7f2013-02-08 20:40:151278 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441279 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1280 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1281 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1282
danakj8522a25b2016-04-16 00:17:361283 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161284 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d,
1285 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191286 req->Start();
1287 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441288
1289 d.set_cancel_in_received_data_pending(true);
1290
[email protected]255620da2013-08-19 13:14:291291 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441292 }
1293
1294 // Take out mock resource provider.
1295 NetModule::SetResourceProvider(NULL);
1296}
1297
[email protected]5f9581402013-10-30 13:08:321298TEST_F(URLRequestTest, FileDirOutputSanity) {
1299 // Verify the general sanity of the the output of the file:
1300 // directory lister by checking for the output of a known existing
1301 // file.
1302 const char sentinel_name[] = "filedir-sentinel";
1303
1304 base::FilePath path;
1305 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471306 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321307
1308 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161309 std::unique_ptr<URLRequest> req(
1310 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1311 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191312 req->Start();
[email protected]5f9581402013-10-30 13:08:321313 base::RunLoop().Run();
1314
1315 // Generate entry for the sentinel file.
1316 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581317 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491318 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321319 EXPECT_GT(info.size, 0);
1320 std::string sentinel_output = GetDirectoryListingEntry(
1321 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
satoruxddac0442017-05-29 06:06:181322 std::string(sentinel_name), false /* is_dir */, info.size,
1323
[email protected]5f9581402013-10-30 13:08:321324 info.last_modified);
1325
1326 ASSERT_LT(0, d.bytes_received());
1327 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501328 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321329 // Check for the entry generated for the "sentinel" file.
1330 const std::string& data = d.data_received();
1331 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1332}
1333
[email protected]316c1e5e2012-09-12 15:17:441334TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1335 // There is an implicit redirect when loading a file path that matches a
1336 // directory and does not end with a slash. Ensure that following such
1337 // redirects does not crash. See http://crbug.com/18686.
1338
[email protected]6cdfd7f2013-02-08 20:40:151339 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441340 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471341 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441342
1343 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161344 std::unique_ptr<URLRequest> req(
1345 default_context_.CreateRequest(FilePathToFileURL(path), DEFAULT_PRIORITY,
1346 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191347 req->Start();
[email protected]255620da2013-08-19 13:14:291348 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441349
1350 ASSERT_EQ(1, d.received_redirect_count());
1351 ASSERT_LT(0, d.bytes_received());
1352 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501353 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441354}
1355
1356#if defined(OS_WIN)
1357// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1358TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1359 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:161360 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
1361 GURL("file:///"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:191362 req->Start();
[email protected]255620da2013-08-19 13:14:291363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441364
1365 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501366 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441367}
[email protected]5ecf7cb282014-05-11 01:49:551368#endif // defined(OS_WIN)
1369
brettwa1228ebb2016-10-28 03:51:341370#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551371
1372TEST_F(URLRequestTest, InvalidUrlTest) {
1373 TestDelegate d;
1374 {
rhalavatib7bd7c792017-04-27 05:25:161375 std::unique_ptr<URLRequest> r(
1376 default_context_.CreateRequest(GURL("invalid url"), DEFAULT_PRIORITY,
1377 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551378
[email protected]f7022f32014-08-21 16:32:191379 r->Start();
1380 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551381
1382 base::RunLoop().Run();
1383 EXPECT_TRUE(d.request_failed());
1384 }
1385}
1386
jochen0e3b3a62014-09-16 18:31:231387TEST_F(URLRequestTest, InvalidReferrerTest) {
1388 TestURLRequestContext context;
1389 TestNetworkDelegate network_delegate;
1390 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1391 context.set_network_delegate(&network_delegate);
1392 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361393 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:161394 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d,
1395 TRAFFIC_ANNOTATION_FOR_TESTS));
jochen0e3b3a62014-09-16 18:31:231396 req->SetReferrer("https://somewhere.com/");
1397
1398 req->Start();
1399 base::RunLoop().Run();
1400 EXPECT_TRUE(d.request_failed());
1401}
1402
[email protected]5ecf7cb282014-05-11 01:49:551403#if defined(OS_WIN)
1404TEST_F(URLRequestTest, ResolveShortcutTest) {
1405 base::FilePath app_path;
1406 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471407 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551408 app_path = app_path.AppendASCII("with-headers.html");
1409
1410 std::wstring lnk_path = app_path.value() + L".lnk";
1411
1412 base::win::ScopedCOMInitializer com_initializer;
1413
1414 // Temporarily create a shortcut for test
1415 {
Robert Liaoc88f99d12017-10-17 21:48:331416 Microsoft::WRL::ComPtr<IShellLink> shell;
robliaoeb9bfd642017-05-18 17:35:161417 ASSERT_TRUE(SUCCEEDED(::CoCreateInstance(
1418 CLSID_ShellLink, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&shell))));
Robert Liaoc88f99d12017-10-17 21:48:331419 Microsoft::WRL::ComPtr<IPersistFile> persist;
robliao310fa98b2017-05-11 17:14:001420 ASSERT_TRUE(SUCCEEDED(shell.CopyTo(persist.GetAddressOf())));
[email protected]5ecf7cb282014-05-11 01:49:551421 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1422 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1423 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1424 }
1425
1426 TestDelegate d;
1427 {
danakj8522a25b2016-04-16 00:17:361428 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161429 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1430 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5ecf7cb282014-05-11 01:49:551431
[email protected]f7022f32014-08-21 16:32:191432 r->Start();
1433 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551434
1435 base::RunLoop().Run();
1436
1437 WIN32_FILE_ATTRIBUTE_DATA data;
1438 GetFileAttributesEx(app_path.value().c_str(),
1439 GetFileExInfoStandard, &data);
1440 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1441 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1442 FILE_ATTRIBUTE_NORMAL, NULL);
1443 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361444 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551445 DWORD read_size;
1446 BOOL result;
1447 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1448 &read_size, NULL);
1449 std::string content(buffer.get(), read_size);
1450 CloseHandle(file);
1451
[email protected]f7022f32014-08-21 16:32:191452 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551453 EXPECT_EQ(1, d.received_redirect_count());
1454 EXPECT_EQ(content, d.data_received());
1455 }
1456
1457 // Clean the shortcut
1458 DeleteFile(lnk_path.c_str());
1459}
1460#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441461
1462// Custom URLRequestJobs for use with interceptor tests
1463class RestartTestJob : public URLRequestTestJob {
1464 public:
1465 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1466 : URLRequestTestJob(request, network_delegate, true) {}
1467 protected:
dchengb03027d2014-10-21 12:00:201468 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441469 private:
Chris Watkins7a41d3552017-12-01 02:13:271470 ~RestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441471};
1472
1473class CancelTestJob : public URLRequestTestJob {
1474 public:
1475 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1476 : URLRequestTestJob(request, network_delegate, true) {}
1477 protected:
dchengb03027d2014-10-21 12:00:201478 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441479 private:
Chris Watkins7a41d3552017-12-01 02:13:271480 ~CancelTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441481};
1482
1483class CancelThenRestartTestJob : public URLRequestTestJob {
1484 public:
1485 explicit CancelThenRestartTestJob(URLRequest* request,
1486 NetworkDelegate* network_delegate)
1487 : URLRequestTestJob(request, network_delegate, true) {
1488 }
1489 protected:
dchengb03027d2014-10-21 12:00:201490 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441491 request_->Cancel();
1492 this->NotifyRestartRequired();
1493 }
1494 private:
Chris Watkins7a41d3552017-12-01 02:13:271495 ~CancelThenRestartTestJob() override = default;
[email protected]316c1e5e2012-09-12 15:17:441496};
1497
bengr1bf8e942014-11-07 01:36:501498// An Interceptor for use with interceptor tests.
1499class MockURLRequestInterceptor : public URLRequestInterceptor {
1500 public:
1501 // Static getters for canned response header and data strings.
1502 static std::string ok_data() {
1503 return URLRequestTestJob::test_data_1();
1504 }
1505
1506 static std::string ok_headers() {
1507 return URLRequestTestJob::test_headers();
1508 }
1509
1510 static std::string redirect_data() {
1511 return std::string();
1512 }
1513
1514 static std::string redirect_headers() {
1515 return URLRequestTestJob::test_redirect_headers();
1516 }
1517
1518 static std::string error_data() {
1519 return std::string("ohhh nooooo mr. bill!");
1520 }
1521
1522 static std::string error_headers() {
1523 return URLRequestTestJob::test_error_headers();
1524 }
1525
1526 MockURLRequestInterceptor()
1527 : intercept_main_request_(false), restart_main_request_(false),
1528 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1529 simulate_main_network_error_(false),
1530 intercept_redirect_(false), cancel_redirect_request_(false),
1531 intercept_final_response_(false), cancel_final_request_(false),
1532 use_url_request_http_job_(false),
1533 did_intercept_main_(false), did_restart_main_(false),
1534 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1535 did_simulate_error_main_(false),
1536 did_intercept_redirect_(false), did_cancel_redirect_(false),
1537 did_intercept_final_(false), did_cancel_final_(false) {
1538 }
1539
Chris Watkins7a41d3552017-12-01 02:13:271540 ~MockURLRequestInterceptor() override = default;
bengr1bf8e942014-11-07 01:36:501541
1542 // URLRequestInterceptor implementation:
1543 URLRequestJob* MaybeInterceptRequest(
1544 URLRequest* request,
1545 NetworkDelegate* network_delegate) const override {
1546 if (restart_main_request_) {
1547 restart_main_request_ = false;
1548 did_restart_main_ = true;
1549 return new RestartTestJob(request, network_delegate);
1550 }
1551 if (cancel_main_request_) {
1552 cancel_main_request_ = false;
1553 did_cancel_main_ = true;
1554 return new CancelTestJob(request, network_delegate);
1555 }
1556 if (cancel_then_restart_main_request_) {
1557 cancel_then_restart_main_request_ = false;
1558 did_cancel_then_restart_main_ = true;
1559 return new CancelThenRestartTestJob(request, network_delegate);
1560 }
1561 if (simulate_main_network_error_) {
1562 simulate_main_network_error_ = false;
1563 did_simulate_error_main_ = true;
1564 if (use_url_request_http_job_) {
1565 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1566 }
1567 // This job will result in error since the requested URL is not one of the
1568 // URLs supported by these tests.
1569 return new URLRequestTestJob(request, network_delegate, true);
1570 }
1571 if (!intercept_main_request_)
1572 return nullptr;
1573 intercept_main_request_ = false;
1574 did_intercept_main_ = true;
1575 URLRequestTestJob* job = new URLRequestTestJob(request,
1576 network_delegate,
1577 main_headers_,
1578 main_data_,
1579 true);
1580 job->set_load_timing_info(main_request_load_timing_info_);
1581 return job;
1582 }
1583
1584 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1585 NetworkDelegate* network_delegate,
1586 const GURL& location) const override {
1587 if (cancel_redirect_request_) {
1588 cancel_redirect_request_ = false;
1589 did_cancel_redirect_ = true;
1590 return new CancelTestJob(request, network_delegate);
1591 }
1592 if (!intercept_redirect_)
1593 return nullptr;
1594 intercept_redirect_ = false;
1595 did_intercept_redirect_ = true;
1596 if (use_url_request_http_job_) {
1597 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1598 }
1599 return new URLRequestTestJob(request,
1600 network_delegate,
1601 redirect_headers_,
1602 redirect_data_,
1603 true);
1604 }
1605
1606 URLRequestJob* MaybeInterceptResponse(
1607 URLRequest* request,
1608 NetworkDelegate* network_delegate) const override {
1609 if (cancel_final_request_) {
1610 cancel_final_request_ = false;
1611 did_cancel_final_ = true;
1612 return new CancelTestJob(request, network_delegate);
1613 }
1614 if (!intercept_final_response_)
1615 return nullptr;
1616 intercept_final_response_ = false;
1617 did_intercept_final_ = true;
1618 if (use_url_request_http_job_) {
1619 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1620 }
1621 return new URLRequestTestJob(request,
1622 network_delegate,
1623 final_headers_,
1624 final_data_,
1625 true);
1626 }
1627
1628 void set_intercept_main_request(bool intercept_main_request) {
1629 intercept_main_request_ = intercept_main_request;
1630 }
1631
1632 void set_main_headers(const std::string& main_headers) {
1633 main_headers_ = main_headers;
1634 }
1635
1636 void set_main_data(const std::string& main_data) {
1637 main_data_ = main_data;
1638 }
1639
1640 void set_main_request_load_timing_info(
1641 const LoadTimingInfo& main_request_load_timing_info) {
1642 main_request_load_timing_info_ = main_request_load_timing_info;
1643 }
1644
1645 void set_restart_main_request(bool restart_main_request) {
1646 restart_main_request_ = restart_main_request;
1647 }
1648
1649 void set_cancel_main_request(bool cancel_main_request) {
1650 cancel_main_request_ = cancel_main_request;
1651 }
1652
1653 void set_cancel_then_restart_main_request(
1654 bool cancel_then_restart_main_request) {
1655 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1656 }
1657
1658 void set_simulate_main_network_error(bool simulate_main_network_error) {
1659 simulate_main_network_error_ = simulate_main_network_error;
1660 }
1661
1662 void set_intercept_redirect(bool intercept_redirect) {
1663 intercept_redirect_ = intercept_redirect;
1664 }
1665
1666 void set_redirect_headers(const std::string& redirect_headers) {
1667 redirect_headers_ = redirect_headers;
1668 }
1669
1670 void set_redirect_data(const std::string& redirect_data) {
1671 redirect_data_ = redirect_data;
1672 }
1673
1674 void set_cancel_redirect_request(bool cancel_redirect_request) {
1675 cancel_redirect_request_ = cancel_redirect_request;
1676 }
1677
1678 void set_intercept_final_response(bool intercept_final_response) {
1679 intercept_final_response_ = intercept_final_response;
1680 }
1681
1682 void set_final_headers(const std::string& final_headers) {
1683 final_headers_ = final_headers;
1684 }
1685
1686 void set_final_data(const std::string& final_data) {
1687 final_data_ = final_data;
1688 }
1689
1690 void set_cancel_final_request(bool cancel_final_request) {
1691 cancel_final_request_ = cancel_final_request;
1692 }
1693
1694 void set_use_url_request_http_job(bool use_url_request_http_job) {
1695 use_url_request_http_job_ = use_url_request_http_job;
1696 }
1697
1698 bool did_intercept_main() const {
1699 return did_intercept_main_;
1700 }
1701
1702 bool did_restart_main() const {
1703 return did_restart_main_;
1704 }
1705
1706 bool did_cancel_main() const {
1707 return did_cancel_main_;
1708 }
1709
1710 bool did_cancel_then_restart_main() const {
1711 return did_cancel_then_restart_main_;
1712 }
1713
1714 bool did_simulate_error_main() const {
1715 return did_simulate_error_main_;
1716 }
1717
1718 bool did_intercept_redirect() const {
1719 return did_intercept_redirect_;
1720 }
1721
1722 bool did_cancel_redirect() const {
1723 return did_cancel_redirect_;
1724 }
1725
1726 bool did_intercept_final() const {
1727 return did_intercept_final_;
1728 }
1729
1730 bool did_cancel_final() const {
1731 return did_cancel_final_;
1732 }
1733
1734 private:
1735 // Indicate whether to intercept the main request, and if so specify the
1736 // response to return and the LoadTimingInfo to use.
1737 mutable bool intercept_main_request_;
1738 mutable std::string main_headers_;
1739 mutable std::string main_data_;
1740 mutable LoadTimingInfo main_request_load_timing_info_;
1741
1742 // These indicate actions that can be taken within MaybeInterceptRequest.
1743 mutable bool restart_main_request_;
1744 mutable bool cancel_main_request_;
1745 mutable bool cancel_then_restart_main_request_;
1746 mutable bool simulate_main_network_error_;
1747
1748 // Indicate whether to intercept redirects, and if so specify the response to
1749 // return.
1750 mutable bool intercept_redirect_;
1751 mutable std::string redirect_headers_;
1752 mutable std::string redirect_data_;
1753
1754 // Cancel the request within MaybeInterceptRedirect.
1755 mutable bool cancel_redirect_request_;
1756
1757 // Indicate whether to intercept the final response, and if so specify the
1758 // response to return.
1759 mutable bool intercept_final_response_;
1760 mutable std::string final_headers_;
1761 mutable std::string final_data_;
1762
1763 // Cancel the final request within MaybeInterceptResponse.
1764 mutable bool cancel_final_request_;
1765
1766 // Instruct the interceptor to use a real URLRequestHTTPJob.
1767 mutable bool use_url_request_http_job_;
1768
1769 // These indicate if the interceptor did something or not.
1770 mutable bool did_intercept_main_;
1771 mutable bool did_restart_main_;
1772 mutable bool did_cancel_main_;
1773 mutable bool did_cancel_then_restart_main_;
1774 mutable bool did_simulate_error_main_;
1775 mutable bool did_intercept_redirect_;
1776 mutable bool did_cancel_redirect_;
1777 mutable bool did_intercept_final_;
1778 mutable bool did_cancel_final_;
1779};
1780
1781// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1782class URLRequestInterceptorTest : public URLRequestTest {
1783 public:
1784 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1785 }
1786
1787 ~URLRequestInterceptorTest() override {
1788 // URLRequestJobs may post clean-up tasks on destruction.
1789 base::RunLoop().RunUntilIdle();
1790 }
1791
1792 void SetUpFactory() override {
1793 interceptor_ = new MockURLRequestInterceptor();
1794 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361795 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501796 }
1797
1798 MockURLRequestInterceptor* interceptor() const {
1799 return interceptor_;
1800 }
1801
1802 private:
1803 MockURLRequestInterceptor* interceptor_;
1804};
1805
1806TEST_F(URLRequestInterceptorTest, Intercept) {
1807 // Intercept the main request and respond with a simple response.
1808 interceptor()->set_intercept_main_request(true);
1809 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1810 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591811 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361812 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161813 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1814 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501815 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1816 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1817 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
Randy Smith4cd4d36a2017-08-24 01:01:091818 req->SetUserData(&user_data0, base::WrapUnique(user_data0));
avi0d991472017-04-27 07:04:041819 req->SetUserData(&user_data1, base::WrapUnique(user_data1));
1820 req->SetUserData(&user_data2, base::WrapUnique(user_data2));
bengr1bf8e942014-11-07 01:36:501821 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191822 req->Start();
[email protected]255620da2013-08-19 13:14:291823 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591824
bengr1bf8e942014-11-07 01:36:501825 // Make sure we can retrieve our specific user data.
Randy Smith4cd4d36a2017-08-24 01:01:091826 EXPECT_EQ(user_data0, req->GetUserData(&user_data0));
bengr1bf8e942014-11-07 01:36:501827 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1828 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591829
bengr1bf8e942014-11-07 01:36:501830 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501831 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501832 EXPECT_EQ(200, req->response_headers()->response_code());
1833 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1834 EXPECT_EQ(1, d.response_started_count());
1835 EXPECT_EQ(0, d.received_redirect_count());
1836}
[email protected]2bba3252013-04-08 19:50:591837
bengr1bf8e942014-11-07 01:36:501838TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1839 // Intercept the main request and respond with a redirect.
1840 interceptor()->set_intercept_main_request(true);
1841 interceptor()->set_main_headers(
1842 MockURLRequestInterceptor::redirect_headers());
1843 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1844
1845 // Intercept that redirect and respond with a final OK response.
1846 interceptor()->set_intercept_redirect(true);
1847 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1848 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1849
1850 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361851 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161852 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1853 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501854 req->set_method("GET");
1855 req->Start();
1856 base::RunLoop().Run();
1857
1858 // Check that the interceptor got called as expected.
1859 EXPECT_TRUE(interceptor()->did_intercept_main());
1860 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1861
1862 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501863 int status = d.request_status();
1864 EXPECT_EQ(OK, status);
1865 if (status == OK)
bengr1bf8e942014-11-07 01:36:501866 EXPECT_EQ(200, req->response_headers()->response_code());
1867
1868 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1869 EXPECT_EQ(1, d.response_started_count());
1870 EXPECT_EQ(0, d.received_redirect_count());
1871}
1872
1873TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1874 // Intercept the main request to generate a server error response.
1875 interceptor()->set_intercept_main_request(true);
1876 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1877 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1878
1879 // Intercept that error and respond with an OK response.
1880 interceptor()->set_intercept_final_response(true);
1881 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1882 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1883
1884 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361885 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161886 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1887 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501888 req->set_method("GET");
1889 req->Start();
1890 base::RunLoop().Run();
1891
1892 // Check that the interceptor got called as expected.
1893 EXPECT_TRUE(interceptor()->did_intercept_main());
1894 EXPECT_TRUE(interceptor()->did_intercept_final());
1895
1896 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501897 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501898 EXPECT_EQ(200, req->response_headers()->response_code());
1899 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1900 EXPECT_EQ(1, d.response_started_count());
1901 EXPECT_EQ(0, d.received_redirect_count());
1902}
1903
1904TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1905 // Intercept the main request to simulate a network error.
1906 interceptor()->set_simulate_main_network_error(true);
1907
1908 // Intercept that error and respond with an OK response.
1909 interceptor()->set_intercept_final_response(true);
1910 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1911 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1912
1913 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361914 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161915 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1916 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501917 req->set_method("GET");
1918 req->Start();
1919 base::RunLoop().Run();
1920
1921 // Check that the interceptor got called as expected.
1922 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1923 EXPECT_TRUE(interceptor()->did_intercept_final());
1924
1925 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501926 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501927 EXPECT_EQ(200, req->response_headers()->response_code());
1928 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1929 EXPECT_EQ(1, d.response_started_count());
1930 EXPECT_EQ(0, d.received_redirect_count());
1931}
1932
1933TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1934 // Restart the main request.
1935 interceptor()->set_restart_main_request(true);
1936
1937 // then intercept the new main request and respond with an OK response
1938 interceptor()->set_intercept_main_request(true);
1939 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1940 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1941
1942 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361943 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161944 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1945 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501946 req->set_method("GET");
1947 req->Start();
1948 base::RunLoop().Run();
1949
1950 // Check that the interceptor got called as expected.
1951 EXPECT_TRUE(interceptor()->did_restart_main());
1952 EXPECT_TRUE(interceptor()->did_intercept_main());
1953
1954 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501955 int status = d.request_status();
1956 EXPECT_EQ(OK, status);
1957 if (status == OK)
bengr1bf8e942014-11-07 01:36:501958 EXPECT_EQ(200, req->response_headers()->response_code());
1959
1960 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1961 EXPECT_EQ(1, d.response_started_count());
1962 EXPECT_EQ(0, d.received_redirect_count());
1963}
1964
1965TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1966 // Intercept the main request and cancel from within the restarted job.
1967 interceptor()->set_cancel_main_request(true);
1968
1969 // Set up to intercept the final response and override it with an OK response.
1970 interceptor()->set_intercept_final_response(true);
1971 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1972 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1973
1974 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361975 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:161976 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
1977 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:501978 req->set_method("GET");
1979 req->Start();
1980 base::RunLoop().Run();
1981
1982 // Check that the interceptor got called as expected.
1983 EXPECT_TRUE(interceptor()->did_cancel_main());
1984 EXPECT_FALSE(interceptor()->did_intercept_final());
1985
1986 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501987 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501988}
1989
1990TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1991 // Intercept the main request and respond with a redirect.
1992 interceptor()->set_intercept_main_request(true);
1993 interceptor()->set_main_headers(
1994 MockURLRequestInterceptor::redirect_headers());
1995 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1996
1997 // Intercept the redirect and cancel from within that job.
1998 interceptor()->set_cancel_redirect_request(true);
1999
2000 // Set up to intercept the final response and override it with an OK response.
2001 interceptor()->set_intercept_final_response(true);
2002 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2003 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2004
2005 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362006 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162007 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2008 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502009 req->set_method("GET");
2010 req->Start();
2011 base::RunLoop().Run();
2012
2013 // Check that the interceptor got called as expected.
2014 EXPECT_TRUE(interceptor()->did_intercept_main());
2015 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2016 EXPECT_FALSE(interceptor()->did_intercept_final());
2017
2018 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502019 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502020}
2021
2022TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2023 // Intercept the main request to simulate a network error.
2024 interceptor()->set_simulate_main_network_error(true);
2025
2026 // Set up to intercept final the response and cancel from within that job.
2027 interceptor()->set_cancel_final_request(true);
2028
2029 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362030 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162031 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2032 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502033 req->set_method("GET");
2034 req->Start();
2035 base::RunLoop().Run();
2036
2037 // Check that the interceptor got called as expected.
2038 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2039 EXPECT_TRUE(interceptor()->did_cancel_final());
2040
2041 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502042 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:502043}
2044
2045TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2046 // Intercept the main request and cancel then restart from within that job.
2047 interceptor()->set_cancel_then_restart_main_request(true);
2048
2049 // Set up to intercept the final response and override it with an OK response.
2050 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:502051 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2052 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:502053
2054 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362055 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162056 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2057 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502058 req->set_method("GET");
2059 req->Start();
2060 base::RunLoop().Run();
2061
2062 // Check that the interceptor got called as expected.
2063 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2064 EXPECT_FALSE(interceptor()->did_intercept_final());
2065
2066 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:502067 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:592068}
2069
2070// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2071// reused. |connect_time_flags| is used to indicate if there should be dns
2072// or SSL times, and |used_proxy| is used for proxy times.
2073LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2074 int connect_time_flags,
2075 bool used_proxy) {
2076 LoadTimingInfo load_timing;
2077 load_timing.socket_log_id = 1;
2078
2079 if (used_proxy) {
2080 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2081 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2082 }
2083
2084 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2085 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2086 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2087 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2088 }
2089 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2090 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2091 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2092 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2093 }
2094 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2095
2096 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2097 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2098 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2099 return load_timing;
2100}
2101
2102// Same as above, but in the case of a reused socket.
2103LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2104 bool used_proxy) {
2105 LoadTimingInfo load_timing;
2106 load_timing.socket_log_id = 1;
2107 load_timing.socket_reused = true;
2108
2109 if (used_proxy) {
2110 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2111 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2112 }
2113
2114 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2115 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2116 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2117 return load_timing;
2118}
2119
bengr1bf8e942014-11-07 01:36:502120LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2121 const LoadTimingInfo& job_load_timing,
2122 const URLRequestContext& context,
2123 MockURLRequestInterceptor* interceptor) {
2124 interceptor->set_intercept_main_request(true);
2125 interceptor->set_main_request_load_timing_info(job_load_timing);
2126 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162127 std::unique_ptr<URLRequest> req(
2128 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
2129 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:502130 req->Start();
2131 base::RunLoop().Run();
2132
2133 LoadTimingInfo resulting_load_timing;
2134 req->GetLoadTimingInfo(&resulting_load_timing);
2135
2136 // None of these should be modified by the URLRequest.
2137 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2138 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2139 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2140 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2141 EXPECT_EQ(job_load_timing.receive_headers_end,
2142 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:572143 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
2144 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:502145
2146 return resulting_load_timing;
2147}
2148
[email protected]2bba3252013-04-08 19:50:592149// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502150TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592151 base::TimeTicks now = base::TimeTicks::Now();
2152 LoadTimingInfo job_load_timing =
2153 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2154
[email protected]2ca01e52013-10-31 22:05:192155 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502156 RunURLRequestInterceptorLoadTimingTest(
2157 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592158
2159 // Nothing should have been changed by the URLRequest.
2160 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2161 load_timing_result.proxy_resolve_start);
2162 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2163 load_timing_result.proxy_resolve_end);
2164 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2165 load_timing_result.connect_timing.dns_start);
2166 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2167 load_timing_result.connect_timing.dns_end);
2168 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2169 load_timing_result.connect_timing.connect_start);
2170 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2171 load_timing_result.connect_timing.connect_end);
2172 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2173 load_timing_result.connect_timing.ssl_start);
2174 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2175 load_timing_result.connect_timing.ssl_end);
2176
2177 // Redundant sanity check.
2178 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2179}
2180
2181// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502182TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592183 base::TimeTicks now = base::TimeTicks::Now();
2184 LoadTimingInfo job_load_timing =
2185 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2186
[email protected]2ca01e52013-10-31 22:05:192187 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502188 RunURLRequestInterceptorLoadTimingTest(
2189 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592190
2191 // Nothing should have been changed by the URLRequest.
2192 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2193 load_timing_result.proxy_resolve_start);
2194 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2195 load_timing_result.proxy_resolve_end);
2196 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2197 load_timing_result.connect_timing.dns_start);
2198 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2199 load_timing_result.connect_timing.dns_end);
2200 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2201 load_timing_result.connect_timing.connect_start);
2202 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2203 load_timing_result.connect_timing.connect_end);
2204 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2205 load_timing_result.connect_timing.ssl_start);
2206 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2207 load_timing_result.connect_timing.ssl_end);
2208
2209 // Redundant sanity check.
2210 TestLoadTimingNotReusedWithProxy(load_timing_result,
2211 CONNECT_TIMING_HAS_SSL_TIMES);
2212}
2213
2214// Make sure that URLRequest correctly adjusts proxy times when they're before
2215// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102216// the case of reusing a SPDY session. The connected socket is not considered
2217// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592218//
2219// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502220TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592221 base::TimeTicks now = base::TimeTicks::Now();
2222 LoadTimingInfo job_load_timing =
2223 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2224 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2225 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2226 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2227 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2228 job_load_timing.connect_timing.connect_start =
2229 now - base::TimeDelta::FromDays(2);
2230 job_load_timing.connect_timing.connect_end =
2231 now - base::TimeDelta::FromDays(1);
2232
[email protected]2ca01e52013-10-31 22:05:192233 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502234 RunURLRequestInterceptorLoadTimingTest(
2235 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592236
2237 // Proxy times, connect times, and DNS times should all be replaced with
2238 // request_start.
2239 EXPECT_EQ(load_timing_result.request_start,
2240 load_timing_result.proxy_resolve_start);
2241 EXPECT_EQ(load_timing_result.request_start,
2242 load_timing_result.proxy_resolve_end);
2243 EXPECT_EQ(load_timing_result.request_start,
2244 load_timing_result.connect_timing.dns_start);
2245 EXPECT_EQ(load_timing_result.request_start,
2246 load_timing_result.connect_timing.dns_end);
2247 EXPECT_EQ(load_timing_result.request_start,
2248 load_timing_result.connect_timing.connect_start);
2249 EXPECT_EQ(load_timing_result.request_start,
2250 load_timing_result.connect_timing.connect_end);
2251
2252 // Other times should have been left null.
2253 TestLoadTimingNotReusedWithProxy(load_timing_result,
2254 CONNECT_TIMING_HAS_DNS_TIMES);
2255}
2256
2257// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502258TEST_F(URLRequestInterceptorTest,
2259 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592260 base::TimeTicks now = base::TimeTicks::Now();
2261 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2262 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2263 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2264
[email protected]2ca01e52013-10-31 22:05:192265 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502266 RunURLRequestInterceptorLoadTimingTest(
2267 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592268
2269 // Proxy times and connect times should all be replaced with request_start.
2270 EXPECT_EQ(load_timing_result.request_start,
2271 load_timing_result.proxy_resolve_start);
2272 EXPECT_EQ(load_timing_result.request_start,
2273 load_timing_result.proxy_resolve_end);
2274
2275 // Other times should have been left null.
2276 TestLoadTimingReusedWithProxy(load_timing_result);
2277}
2278
2279// Make sure that URLRequest correctly adjusts connect times when they're before
2280// |request_start|, due to reusing a connected socket. The connected socket is
2281// not considered reused in this test (May be a preconnect).
2282//
2283// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502284TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592285 base::TimeTicks now = base::TimeTicks::Now();
2286 LoadTimingInfo job_load_timing =
2287 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2288 job_load_timing.connect_timing.connect_start =
2289 now - base::TimeDelta::FromDays(1);
2290 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2291 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2292 job_load_timing.connect_timing.connect_end =
2293 now - base::TimeDelta::FromDays(4);
2294
[email protected]2ca01e52013-10-31 22:05:192295 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502296 RunURLRequestInterceptorLoadTimingTest(
2297 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592298
2299 // Connect times, and SSL times should be replaced with request_start.
2300 EXPECT_EQ(load_timing_result.request_start,
2301 load_timing_result.connect_timing.connect_start);
2302 EXPECT_EQ(load_timing_result.request_start,
2303 load_timing_result.connect_timing.ssl_start);
2304 EXPECT_EQ(load_timing_result.request_start,
2305 load_timing_result.connect_timing.ssl_end);
2306 EXPECT_EQ(load_timing_result.request_start,
2307 load_timing_result.connect_timing.connect_end);
2308
2309 // Other times should have been left null.
2310 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2311}
2312
2313// Make sure that URLRequest correctly adjusts connect times when they're before
2314// |request_start|, due to reusing a connected socket in the case that there
2315// are also proxy times. The connected socket is not considered reused in this
2316// test (May be a preconnect).
2317//
2318// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502319TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592320 base::TimeTicks now = base::TimeTicks::Now();
2321 LoadTimingInfo job_load_timing =
2322 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2323 job_load_timing.connect_timing.connect_start =
2324 now - base::TimeDelta::FromDays(1);
2325 job_load_timing.connect_timing.connect_end =
2326 now - base::TimeDelta::FromDays(2);
2327
[email protected]2ca01e52013-10-31 22:05:192328 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502329 RunURLRequestInterceptorLoadTimingTest(
2330 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592331
2332 // Connect times should be replaced with proxy_resolve_end.
2333 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2334 load_timing_result.connect_timing.connect_start);
2335 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2336 load_timing_result.connect_timing.connect_end);
2337
2338 // Other times should have been left null.
2339 TestLoadTimingNotReusedWithProxy(load_timing_result,
2340 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2341}
2342
[email protected]316c1e5e2012-09-12 15:17:442343// Check that two different URL requests have different identifiers.
2344TEST_F(URLRequestTest, Identifiers) {
2345 TestDelegate d;
2346 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362347 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162348 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2349 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:362350 std::unique_ptr<URLRequest> other_req(
rhalavatib7bd7c792017-04-27 05:25:162351 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2352 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:442353
mmenke19378d22014-09-09 04:12:592354 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442355}
2356
blundellb8163592f2015-12-16 14:22:422357#if defined(OS_IOS)
2358// TODO(droger): Check that a failure to connect to the proxy is reported to
2359// the network delegate. crbug.com/496743
2360#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2361#else
2362#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2363#endif
2364TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442365 MockHostResolver host_resolver;
2366 host_resolver.rules()->AddSimulatedFailure("*");
2367
[email protected]ceefd7fd2012-11-29 00:36:242368 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442369 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2370
2371 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362372 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:162373 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d,
2374 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192375 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442376
[email protected]f7022f32014-08-21 16:32:192377 req->Start();
[email protected]255620da2013-08-19 13:14:292378 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442379
2380 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152381 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472382 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502383 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442384
2385 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012386 EXPECT_THAT(network_delegate.last_error(),
2387 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442388 EXPECT_EQ(1, network_delegate.completed_requests());
2389}
2390
[email protected]cba24642014-08-15 20:49:592391// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442392// content is empty.
2393TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2394 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:162395 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2396 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192397 req->Start();
[email protected]255620da2013-08-19 13:14:292398 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442399 EXPECT_EQ("", d.data_received());
2400 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2401}
2402
[email protected]5033ab82013-03-22 20:17:462403// Make sure that SetPriority actually sets the URLRequest's priority
2404// correctly, both before and after start.
2405TEST_F(URLRequestTest, SetPriorityBasic) {
2406 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362407 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162408 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2409 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192410 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462411
[email protected]f7022f32014-08-21 16:32:192412 req->SetPriority(LOW);
2413 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462414
[email protected]f7022f32014-08-21 16:32:192415 req->Start();
2416 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462417
[email protected]f7022f32014-08-21 16:32:192418 req->SetPriority(MEDIUM);
2419 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462420}
2421
2422// Make sure that URLRequest calls SetPriority on a job before calling
2423// Start on it.
2424TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2425 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362426 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162427 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2428 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192429 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462430
mmenkeed0498b2015-12-08 23:20:422431 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362432 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422433 req.get(), &default_network_delegate_, &job_priority));
2434 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2435 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462436
[email protected]f7022f32014-08-21 16:32:192437 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462438
[email protected]f7022f32014-08-21 16:32:192439 req->Start();
mmenkeed0498b2015-12-08 23:20:422440 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462441}
2442
2443// Make sure that URLRequest passes on its priority updates to its
2444// job.
2445TEST_F(URLRequestTest, SetJobPriority) {
2446 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362447 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162448 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d,
2449 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5033ab82013-03-22 20:17:462450
mmenkeed0498b2015-12-08 23:20:422451 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362452 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422453 req.get(), &default_network_delegate_, &job_priority));
2454 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462455
[email protected]f7022f32014-08-21 16:32:192456 req->SetPriority(LOW);
2457 req->Start();
mmenkeed0498b2015-12-08 23:20:422458 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462459
[email protected]f7022f32014-08-21 16:32:192460 req->SetPriority(MEDIUM);
2461 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422462 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462463}
2464
[email protected]bb1c4662013-11-14 00:00:072465// Setting the IGNORE_LIMITS load flag should be okay if the priority
2466// is MAXIMUM_PRIORITY.
2467TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2468 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362469 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162470 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d,
2471 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192472 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072473
mmenkeed0498b2015-12-08 23:20:422474 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362475 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422476 req.get(), &default_network_delegate_, &job_priority));
2477 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072478
[email protected]f7022f32014-08-21 16:32:192479 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2480 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072481
[email protected]f7022f32014-08-21 16:32:192482 req->SetPriority(MAXIMUM_PRIORITY);
2483 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072484
[email protected]f7022f32014-08-21 16:32:192485 req->Start();
2486 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422487 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072488}
2489
nick5d570de92015-05-04 20:16:162490namespace {
2491
2492// Less verbose way of running a simple testserver for the tests below.
David Benjamin42116f62017-11-20 21:45:392493class HttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442494 public:
David Benjamin42116f62017-11-20 21:45:392495 explicit HttpTestServer(const base::FilePath& document_root) {
tommycli59a63432015-11-06 00:10:552496 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272497 }
tommycli59a63432015-11-06 00:10:552498
David Benjamin42116f62017-11-20 21:45:392499 HttpTestServer() { AddDefaultHandlers(base::FilePath()); }
tommycli59a63432015-11-06 00:10:552500};
tommyclieae5f75f2015-11-05 19:07:272501
nick5d570de92015-05-04 20:16:162502} // namespace
2503
[email protected]f2f31b32013-01-16 23:24:092504TEST_F(URLRequestTest, DelayedCookieCallback) {
David Benjamin42116f62017-11-20 21:45:392505 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442506 ASSERT_TRUE(test_server.Start());
2507
2508 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362509 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502510 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442511
2512 // Set up a cookie.
2513 {
2514 TestNetworkDelegate network_delegate;
2515 context.set_network_delegate(&network_delegate);
2516 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362517 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552518 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162519 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192520 req->Start();
[email protected]255620da2013-08-19 13:14:292521 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442522 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2523 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2524 EXPECT_EQ(1, network_delegate.set_cookie_count());
2525 }
2526
2527 // Verify that the cookie is set.
2528 {
2529 TestNetworkDelegate network_delegate;
2530 context.set_network_delegate(&network_delegate);
2531 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362532 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162533 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2534 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192535 req->Start();
[email protected]255620da2013-08-19 13:14:292536 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442537
2538 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2539 != std::string::npos);
2540 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2541 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2542 }
2543}
2544
[email protected]f2f31b32013-01-16 23:24:092545TEST_F(URLRequestTest, DoNotSendCookies) {
David Benjamin42116f62017-11-20 21:45:392546 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442547 ASSERT_TRUE(test_server.Start());
2548
2549 // Set up a cookie.
2550 {
2551 TestNetworkDelegate network_delegate;
2552 default_context_.set_network_delegate(&network_delegate);
2553 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362554 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552555 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162556 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192557 req->Start();
[email protected]255620da2013-08-19 13:14:292558 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442559 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2560 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2561 }
2562
2563 // Verify that the cookie is set.
2564 {
2565 TestNetworkDelegate network_delegate;
2566 default_context_.set_network_delegate(&network_delegate);
2567 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362568 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162569 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2570 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192571 req->Start();
[email protected]255620da2013-08-19 13:14:292572 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442573
2574 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2575 != std::string::npos);
2576 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2577 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2578 }
2579
2580 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2581 {
2582 TestNetworkDelegate network_delegate;
2583 default_context_.set_network_delegate(&network_delegate);
2584 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362585 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162586 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2587 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192588 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2589 req->Start();
[email protected]255620da2013-08-19 13:14:292590 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442591
2592 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2593 == std::string::npos);
2594
2595 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2596 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2597 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2598 }
2599}
2600
2601TEST_F(URLRequestTest, DoNotSaveCookies) {
David Benjamin42116f62017-11-20 21:45:392602 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442603 ASSERT_TRUE(test_server.Start());
2604
2605 // Set up a cookie.
2606 {
2607 TestNetworkDelegate network_delegate;
2608 default_context_.set_network_delegate(&network_delegate);
2609 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362610 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552611 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162612 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192613 req->Start();
[email protected]255620da2013-08-19 13:14:292614 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442615
2616 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2617 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2618 EXPECT_EQ(1, network_delegate.set_cookie_count());
2619 }
2620
2621 // Try to set-up another cookie and update the previous cookie.
2622 {
2623 TestNetworkDelegate network_delegate;
2624 default_context_.set_network_delegate(&network_delegate);
2625 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362626 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552627 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162628 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192629 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2630 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442631
[email protected]255620da2013-08-19 13:14:292632 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442633
2634 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2635 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2636 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2637 EXPECT_EQ(0, network_delegate.set_cookie_count());
2638 }
2639
2640 // Verify the cookies weren't saved or updated.
2641 {
2642 TestNetworkDelegate network_delegate;
2643 default_context_.set_network_delegate(&network_delegate);
2644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362645 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162646 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2647 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192648 req->Start();
[email protected]255620da2013-08-19 13:14:292649 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442650
2651 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2652 == std::string::npos);
2653 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2654 != std::string::npos);
2655
2656 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2657 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2658 EXPECT_EQ(0, network_delegate.set_cookie_count());
2659 }
2660}
2661
2662TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392663 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442664 ASSERT_TRUE(test_server.Start());
2665
2666 // Set up a cookie.
2667 {
2668 TestNetworkDelegate network_delegate;
2669 default_context_.set_network_delegate(&network_delegate);
2670 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362671 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552672 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162673 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192674 req->Start();
[email protected]255620da2013-08-19 13:14:292675 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442676
2677 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2678 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2679 }
2680
2681 // Verify that the cookie is set.
2682 {
2683 TestNetworkDelegate network_delegate;
2684 default_context_.set_network_delegate(&network_delegate);
2685 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362686 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162687 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2688 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192689 req->Start();
[email protected]255620da2013-08-19 13:14:292690 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442691
2692 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2693 != std::string::npos);
2694
2695 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2696 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2697 }
2698
2699 // Verify that the cookie isn't sent.
2700 {
2701 TestNetworkDelegate network_delegate;
2702 default_context_.set_network_delegate(&network_delegate);
2703 TestDelegate d;
2704 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362705 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162706 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2707 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192708 req->Start();
[email protected]255620da2013-08-19 13:14:292709 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442710
2711 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2712 == std::string::npos);
2713
[email protected]22e045f2013-09-20 03:54:032714 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442715 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2716 }
2717}
2718
marqf14fff8d2015-12-02 15:52:292719// TODO(crbug.com/564656) This test is flaky on iOS.
2720#if defined(OS_IOS)
2721#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2722#else
2723#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2724#endif
[email protected]316c1e5e2012-09-12 15:17:442725TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
David Benjamin42116f62017-11-20 21:45:392726 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442727 ASSERT_TRUE(test_server.Start());
2728
2729 // Set up a cookie.
2730 {
2731 TestNetworkDelegate network_delegate;
2732 default_context_.set_network_delegate(&network_delegate);
2733 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362734 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552735 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162736 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192737 req->Start();
[email protected]255620da2013-08-19 13:14:292738 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442739
2740 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2741 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2742 }
2743
2744 // Try to set-up another cookie and update the previous cookie.
2745 {
2746 TestNetworkDelegate network_delegate;
2747 default_context_.set_network_delegate(&network_delegate);
2748 TestDelegate d;
2749 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362750 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552751 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162752 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192753 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442754
[email protected]255620da2013-08-19 13:14:292755 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442756
2757 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2758 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2759 }
2760
2761 // Verify the cookies weren't saved or updated.
2762 {
2763 TestNetworkDelegate network_delegate;
2764 default_context_.set_network_delegate(&network_delegate);
2765 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362766 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162767 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2768 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192769 req->Start();
[email protected]255620da2013-08-19 13:14:292770 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442771
2772 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2773 == std::string::npos);
2774 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2775 != std::string::npos);
2776
2777 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2778 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2779 }
2780}
2781
2782TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
David Benjamin42116f62017-11-20 21:45:392783 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442784 ASSERT_TRUE(test_server.Start());
2785
2786 // Set up an empty cookie.
2787 {
2788 TestNetworkDelegate network_delegate;
2789 default_context_.set_network_delegate(&network_delegate);
2790 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362791 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162792 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d,
2793 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192794 req->Start();
[email protected]255620da2013-08-19 13:14:292795 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442796
2797 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2798 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2799 EXPECT_EQ(0, network_delegate.set_cookie_count());
2800 }
2801}
2802
2803TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392804 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442805 ASSERT_TRUE(test_server.Start());
2806
2807 // Set up a cookie.
2808 {
2809 TestNetworkDelegate network_delegate;
2810 default_context_.set_network_delegate(&network_delegate);
2811 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362812 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552813 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162814 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192815 req->Start();
[email protected]255620da2013-08-19 13:14:292816 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442817
2818 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2819 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2820 }
2821
2822 // Verify that the cookie is set.
2823 {
2824 TestNetworkDelegate network_delegate;
2825 default_context_.set_network_delegate(&network_delegate);
2826 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362827 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162828 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2829 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192830 req->Start();
[email protected]255620da2013-08-19 13:14:292831 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442832
2833 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2834 != std::string::npos);
2835
2836 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2837 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2838 }
2839
2840 // Verify that the cookie isn't sent.
2841 {
2842 TestNetworkDelegate network_delegate;
2843 default_context_.set_network_delegate(&network_delegate);
2844 TestDelegate d;
2845 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362846 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162847 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2848 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192849 req->Start();
[email protected]255620da2013-08-19 13:14:292850 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442851
2852 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2853 == std::string::npos);
2854
[email protected]22e045f2013-09-20 03:54:032855 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442856 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2857 }
2858}
2859
2860TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
David Benjamin42116f62017-11-20 21:45:392861 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:442862 ASSERT_TRUE(test_server.Start());
2863
2864 // Set up a cookie.
2865 {
2866 TestNetworkDelegate network_delegate;
2867 default_context_.set_network_delegate(&network_delegate);
2868 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362869 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552870 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:162871 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192872 req->Start();
[email protected]255620da2013-08-19 13:14:292873 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442874
2875 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2876 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2877 }
2878
2879 // Try to set-up another cookie and update the previous cookie.
2880 {
2881 TestNetworkDelegate network_delegate;
2882 default_context_.set_network_delegate(&network_delegate);
2883 TestDelegate d;
2884 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362885 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552886 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
rhalavatib7bd7c792017-04-27 05:25:162887 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192888 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442889
[email protected]255620da2013-08-19 13:14:292890 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442891
2892 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2893 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2894 }
2895
2896 // Verify the cookies weren't saved or updated.
2897 {
2898 TestNetworkDelegate network_delegate;
2899 default_context_.set_network_delegate(&network_delegate);
2900 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362901 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162902 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2903 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:192904 req->Start();
[email protected]255620da2013-08-19 13:14:292905 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442906
2907 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2908 == std::string::npos);
2909 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2910 != std::string::npos);
2911
2912 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2913 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2914 }
2915}
2916
mkwstc5fa7762016-03-28 09:28:232917TEST_F(URLRequestTest, SameSiteCookies) {
David Benjamin42116f62017-11-20 21:45:392918 HttpTestServer test_server;
mkwst3f3daac2015-02-26 20:15:262919 ASSERT_TRUE(test_server.Start());
2920
mkwst202534e32016-01-15 16:07:152921 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152922 default_context_.set_network_delegate(&network_delegate);
2923
mkwstf71d0bd2016-03-21 14:15:242924 const std::string kHost = "example.test";
2925 const std::string kSubHost = "subdomain.example.test";
2926 const std::string kCrossHost = "cross-origin.test";
2927
2928 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262929 {
mkwst3f3daac2015-02-26 20:15:262930 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362931 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242932 test_server.GetURL(kHost,
2933 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2934 "LaxSameSiteCookie=1;SameSite=Lax"),
rhalavatib7bd7c792017-04-27 05:25:162935 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst3f3daac2015-02-26 20:15:262936 req->Start();
2937 base::RunLoop().Run();
2938 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2939 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242940 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262941 }
2942
mkwstf71d0bd2016-03-21 14:15:242943 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262944 {
mkwst3f3daac2015-02-26 20:15:262945 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362946 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162947 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2948 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462949 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:462950 req->set_initiator(url::Origin::Create(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262951 req->Start();
2952 base::RunLoop().Run();
2953
mkwstf71d0bd2016-03-21 14:15:242954 EXPECT_NE(std::string::npos,
2955 d.data_received().find("StrictSameSiteCookie=1"));
2956 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262957 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2958 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2959 }
2960
clamyfd58ca072016-12-21 17:18:322961 // Verify that both cookies are sent when the request has no initiator (can
2962 // happen for main frame browser-initiated navigations).
2963 {
2964 TestDelegate d;
2965 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162966 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2967 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462968 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
clamyfd58ca072016-12-21 17:18:322969 req->Start();
2970 base::RunLoop().Run();
2971
2972 EXPECT_NE(std::string::npos,
2973 d.data_received().find("StrictSameSiteCookie=1"));
2974 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2975 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2976 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2977 }
2978
mkwstf71d0bd2016-03-21 14:15:242979 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262980 {
mkwst3f3daac2015-02-26 20:15:262981 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362982 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:162983 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
2984 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:462985 req->set_site_for_cookies(test_server.GetURL(kSubHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:462986 req->set_initiator(url::Origin::Create(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152987 req->Start();
2988 base::RunLoop().Run();
2989
mkwstf71d0bd2016-03-21 14:15:242990 EXPECT_NE(std::string::npos,
2991 d.data_received().find("StrictSameSiteCookie=1"));
2992 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152993 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2994 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2995 }
2996
mkwstf71d0bd2016-03-21 14:15:242997 // Verify that neither cookie is not sent for cross-site requests.
2998 {
2999 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363000 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163001 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3002 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463003 req->set_site_for_cookies(test_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463004 req->set_initiator(
3005 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243006 req->Start();
3007 base::RunLoop().Run();
3008
3009 EXPECT_EQ(std::string::npos,
3010 d.data_received().find("StrictSameSiteCookie=1"));
3011 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
3012 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3013 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3014 }
3015
3016 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153017 // method is "safe".
3018 {
3019 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363020 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163021 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3022 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463023 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463024 req->set_initiator(
3025 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwstf71d0bd2016-03-21 14:15:243026 req->set_method("GET");
mkwst202534e32016-01-15 16:07:153027 req->Start();
3028 base::RunLoop().Run();
3029
mkwstf71d0bd2016-03-21 14:15:243030 EXPECT_EQ(std::string::npos,
3031 d.data_received().find("StrictSameSiteCookie=1"));
3032 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:153033 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3034 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3035 }
3036
mkwstf71d0bd2016-03-21 14:15:243037 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:153038 // method is unsafe (e.g. POST).
3039 {
3040 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363041 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163042 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3043 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463044 req->set_site_for_cookies(test_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463045 req->set_initiator(
3046 url::Origin::Create(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:153047 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:263048 req->Start();
3049 base::RunLoop().Run();
3050
mkwstf71d0bd2016-03-21 14:15:243051 EXPECT_EQ(std::string::npos,
3052 d.data_received().find("StrictSameSiteCookie=1"));
3053 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:263054 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3055 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3056 }
3057}
3058
estark557a5eb82015-12-01 22:57:103059// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:363060TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:553061 EmbeddedTestServer http_server;
3062 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363063 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553064 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3065 https_server.AddDefaultHandlers(
3066 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3067 ASSERT_TRUE(http_server.Start());
3068 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363069
estarkb15166b2015-12-18 16:56:383070 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363071 TestURLRequestContext context(true);
3072 context.set_network_delegate(&network_delegate);
3073 context.Init();
3074
estarkb15166b2015-12-18 16:56:383075 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363076 {
3077 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363078 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103079 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163080 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363081 req->Start();
3082 base::RunLoop().Run();
3083 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3084 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3085 }
3086
3087 // Verify that the cookie is not set.
3088 {
3089 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363090 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163091 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3092 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363093 req->Start();
3094 base::RunLoop().Run();
3095
jww79aceda2015-12-07 01:56:343096 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
3097 std::string::npos);
estarkcd39c11f2015-10-19 19:46:363098 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3099 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3100 }
3101}
3102
estarkb15166b2015-12-18 16:56:383103TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:553104 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3105 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363106 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553107 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363108
3109 TestNetworkDelegate network_delegate;
3110 TestURLRequestContext context(true);
3111 context.set_network_delegate(&network_delegate);
3112 context.Init();
3113
estarkb15166b2015-12-18 16:56:383114 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363115 {
3116 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163117 std::unique_ptr<URLRequest> req(context.CreateRequest(
3118 https_server.GetURL("/set-cookie?__Secure-foo=1"), DEFAULT_PRIORITY, &d,
3119 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363120 req->Start();
3121 base::RunLoop().Run();
3122 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3123 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3124 }
3125
3126 // Verify that the cookie is not set.
3127 {
3128 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363129 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163130 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3131 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363132 req->Start();
3133 base::RunLoop().Run();
3134
jww79aceda2015-12-07 01:56:343135 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363136 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3137 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3138 }
3139}
3140
estarkb15166b2015-12-18 16:56:383141TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:553142 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3143 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:363144 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:553145 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:363146
estarkb15166b2015-12-18 16:56:383147 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:363148 TestURLRequestContext context(true);
3149 context.set_network_delegate(&network_delegate);
3150 context.Init();
3151
estarkb15166b2015-12-18 16:56:383152 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:363153 {
3154 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363155 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:103156 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163157 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363158 req->Start();
3159 base::RunLoop().Run();
3160 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3161 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3162 }
3163
3164 // Verify that the cookie is set.
3165 {
3166 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363167 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163168 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3169 TRAFFIC_ANNOTATION_FOR_TESTS));
estarkcd39c11f2015-10-19 19:46:363170 req->Start();
3171 base::RunLoop().Run();
3172
jww79aceda2015-12-07 01:56:343173 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
3174 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3175 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3176 }
3177}
3178
3179// Tests that secure cookies can't be set on non-secure origins if strict secure
3180// cookies are enabled.
3181TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
3182 EmbeddedTestServer http_server;
3183 http_server.AddDefaultHandlers(
3184 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3185 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3186 https_server.AddDefaultHandlers(
3187 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3188 ASSERT_TRUE(http_server.Start());
3189 ASSERT_TRUE(https_server.Start());
3190
3191 TestExperimentalFeaturesNetworkDelegate network_delegate;
3192 TestURLRequestContext context(true);
3193 context.set_network_delegate(&network_delegate);
3194 context.Init();
3195
3196 // Try to set a Secure cookie, with experimental features enabled.
3197 {
3198 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363199 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343200 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163201 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343202 req->Start();
3203 base::RunLoop().Run();
3204 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3205 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3206 }
3207
3208 // Verify that the cookie is not set.
3209 {
3210 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363211 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163212 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3213 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343214 req->Start();
3215 base::RunLoop().Run();
3216
3217 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3218 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3219 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3220 }
3221}
3222
3223// Tests that secure cookies can be set on secure origins even if strict secure
3224// cookies are enabled.
3225TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3226 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3227 https_server.AddDefaultHandlers(
3228 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3229 ASSERT_TRUE(https_server.Start());
3230
3231 TestExperimentalFeaturesNetworkDelegate network_delegate;
3232 TestURLRequestContext context(true);
3233 context.set_network_delegate(&network_delegate);
3234 context.Init();
3235
3236 // Try to set a Secure cookie, with experimental features enabled.
3237 {
3238 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363239 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343240 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
rhalavatib7bd7c792017-04-27 05:25:163241 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343242 req->Start();
3243 base::RunLoop().Run();
3244 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3245 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3246 }
3247
3248 // Verify that the cookie is not set.
3249 {
3250 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363251 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163252 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3253 TRAFFIC_ANNOTATION_FOR_TESTS));
jww79aceda2015-12-07 01:56:343254 req->Start();
3255 base::RunLoop().Run();
3256
3257 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363258 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3259 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3260 }
3261}
3262
Mike West86149882017-07-28 10:41:493263TEST_F(URLRequestTest, CookieAgeMetrics) {
3264 EmbeddedTestServer http_server;
3265 http_server.AddDefaultHandlers(
3266 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3267 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3268 https_server.AddDefaultHandlers(
3269 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3270 ASSERT_TRUE(http_server.Start());
3271 ASSERT_TRUE(https_server.Start());
3272
3273 TestNetworkDelegate network_delegate;
3274 default_context_.set_network_delegate(&network_delegate);
3275 base::HistogramTester histograms;
3276
3277 const std::string kHost = "example.test";
3278 const std::string kCrossHost = "cross-origin.test";
3279
3280 // Set a test cookie.
3281 {
3282 TestDelegate d;
3283 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
Thiemo Nagel6c783dbf2018-03-21 13:53:303284 http_server.GetURL(kHost, "/set-cookie?cookie=value&cookie2=value2"),
3285 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike West86149882017-07-28 10:41:493286 req->Start();
3287 base::RunLoop().Run();
Thiemo Nagel6c783dbf2018-03-21 13:53:303288 ASSERT_EQ(2, network_delegate.set_cookie_count());
Mike West86149882017-07-28 10:41:493289 }
3290
Thiemo Nagel6c783dbf2018-03-21 13:53:303291 // Make a secure same-site request.
Mike West86149882017-07-28 10:41:493292 {
3293 TestDelegate d;
3294 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3295 https_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3296 TRAFFIC_ANNOTATION_FOR_TESTS));
Thiemo Nagel6c783dbf2018-03-21 13:53:303297 req->set_site_for_cookies(https_server.GetURL(kHost, "/"));
3298 req->set_initiator(url::Origin::Create(https_server.GetURL(kHost, "/")));
Mike West86149882017-07-28 10:41:493299 req->Start();
3300 base::RunLoop().Run();
3301 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3302 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
Thiemo Nagel6c783dbf2018-03-21 13:53:303303 histograms.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 0);
3304 histograms.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 1);
3305 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3306 0);
3307 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest", 0);
3308 histograms.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 0);
3309 histograms.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 2);
3310 }
3311
3312 // Make a secure cross-site request.
3313 {
3314 TestDelegate d;
3315 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3316 https_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3317 TRAFFIC_ANNOTATION_FOR_TESTS));
3318 req->set_site_for_cookies(https_server.GetURL(kCrossHost, "/"));
3319 req->set_initiator(
3320 url::Origin::Create(https_server.GetURL(kCrossHost, "/")));
3321 req->Start();
3322 base::RunLoop().Run();
3323 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3324 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 0);
3325 histograms.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 1);
3326 histograms.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 1);
3327 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3328 0);
3329 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest", 0);
3330 histograms.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 2);
3331 histograms.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 2);
Mike West86149882017-07-28 10:41:493332 }
3333
3334 // Make a non-secure same-site request.
3335 {
3336 TestDelegate d;
3337 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3338 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3339 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463340 req->set_site_for_cookies(http_server.GetURL(kHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463341 req->set_initiator(url::Origin::Create(http_server.GetURL(kHost, "/")));
Mike West86149882017-07-28 10:41:493342 req->Start();
3343 base::RunLoop().Run();
3344 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 0);
3345 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
Thiemo Nagel6c783dbf2018-03-21 13:53:303346 histograms.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 1);
3347 histograms.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 1);
3348 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3349 0);
3350 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest", 2);
3351 histograms.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 2);
3352 histograms.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 2);
Mike West86149882017-07-28 10:41:493353 }
3354
3355 // Make a non-secure cross-site request.
3356 {
3357 TestDelegate d;
3358 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3359 http_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3360 TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:463361 req->set_site_for_cookies(http_server.GetURL(kCrossHost, "/"));
Daniel Cheng88186bd52017-10-20 08:14:463362 req->set_initiator(
3363 url::Origin::Create(http_server.GetURL(kCrossHost, "/")));
Mike West86149882017-07-28 10:41:493364 req->Start();
3365 base::RunLoop().Run();
3366 histograms.ExpectTotalCount("Cookie.AgeForNonSecureCrossSiteRequest", 1);
3367 histograms.ExpectTotalCount("Cookie.AgeForNonSecureSameSiteRequest", 1);
Thiemo Nagel6c783dbf2018-03-21 13:53:303368 histograms.ExpectTotalCount("Cookie.AgeForSecureCrossSiteRequest", 1);
3369 histograms.ExpectTotalCount("Cookie.AgeForSecureSameSiteRequest", 1);
3370 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureCrossSiteRequest",
3371 2);
3372 histograms.ExpectTotalCount("Cookie.AllAgesForNonSecureSameSiteRequest", 2);
3373 histograms.ExpectTotalCount("Cookie.AllAgesForSecureCrossSiteRequest", 2);
3374 histograms.ExpectTotalCount("Cookie.AllAgesForSecureSameSiteRequest", 2);
Mike West86149882017-07-28 10:41:493375 }
3376}
3377
mmenkefb18c772015-09-30 22:22:503378// Tests that a request is cancelled while entering suspend mode. Uses mocks
3379// rather than a spawned test server because the connection used to talk to
3380// the test server is affected by entering suspend mode on Android.
3381TEST_F(URLRequestTest, CancelOnSuspend) {
3382 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363383 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503384
3385 URLRequestFailedJob::AddUrlHandler();
3386
3387 TestDelegate d;
3388 // Request that just hangs.
3389 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
rhalavatib7bd7c792017-04-27 05:25:163390 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3391 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mmenkefb18c772015-09-30 22:22:503392 r->Start();
3393
3394 power_monitor_source->Suspend();
3395 // Wait for the suspend notification to cause the request to fail.
3396 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503397 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503398 EXPECT_TRUE(d.request_failed());
3399 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3400
3401 URLRequestFilter::GetInstance()->ClearHandlers();
3402
3403 // Shouldn't be needed, but just in case.
3404 power_monitor_source->Resume();
3405}
3406
[email protected]5095cd72012-11-01 10:29:163407// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3408// value for the |fixed_date| argument given to the constructor.
3409class FixedDateNetworkDelegate : public TestNetworkDelegate {
3410 public:
3411 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3412 : fixed_date_(fixed_date) {}
Chris Watkins7a41d3552017-12-01 02:13:273413 ~FixedDateNetworkDelegate() override = default;
[email protected]5095cd72012-11-01 10:29:163414
[email protected]cba24642014-08-15 20:49:593415 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203416 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593417 URLRequest* request,
3418 const CompletionCallback& callback,
3419 const HttpResponseHeaders* original_response_headers,
3420 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133421 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163422
3423 private:
3424 std::string fixed_date_;
3425
3426 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3427};
3428
3429int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593430 URLRequest* request,
3431 const CompletionCallback& callback,
3432 const HttpResponseHeaders* original_response_headers,
3433 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163434 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593435 HttpResponseHeaders* new_response_headers =
3436 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163437
3438 new_response_headers->RemoveHeader("Date");
3439 new_response_headers->AddHeader("Date: " + fixed_date_);
3440
3441 *override_response_headers = new_response_headers;
3442 return TestNetworkDelegate::OnHeadersReceived(request,
3443 callback,
3444 original_response_headers,
[email protected]5f714132014-03-26 10:41:163445 override_response_headers,
3446 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163447}
3448
3449// Test that cookie expiration times are adjusted for server/client clock
3450// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3451// headers by defaulting to GMT. (crbug.com/135131)
3452TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
David Benjamin42116f62017-11-20 21:45:393453 HttpTestServer test_server;
[email protected]5095cd72012-11-01 10:29:163454 ASSERT_TRUE(test_server.Start());
3455
3456 // Set up an expired cookie.
3457 {
3458 TestNetworkDelegate network_delegate;
3459 default_context_.set_network_delegate(&network_delegate);
3460 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363461 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193462 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553463 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163464 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193465 req->Start();
[email protected]255620da2013-08-19 13:14:293466 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163467 }
3468 // Verify that the cookie is not set.
3469 {
3470 TestNetworkDelegate network_delegate;
3471 default_context_.set_network_delegate(&network_delegate);
3472 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363473 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163474 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3475 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193476 req->Start();
[email protected]255620da2013-08-19 13:14:293477 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163478
3479 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3480 }
3481 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3482 {
3483 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3484 default_context_.set_network_delegate(&network_delegate);
3485 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363486 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193487 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553488 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
rhalavatib7bd7c792017-04-27 05:25:163489 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193490 req->Start();
[email protected]255620da2013-08-19 13:14:293491 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163492 }
3493 // Verify that the cookie is set.
3494 {
3495 TestNetworkDelegate network_delegate;
3496 default_context_.set_network_delegate(&network_delegate);
3497 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363498 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163499 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d,
3500 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193501 req->Start();
[email protected]255620da2013-08-19 13:14:293502 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163503
3504 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3505 }
3506}
3507
3508
[email protected]316c1e5e2012-09-12 15:17:443509// Check that it is impossible to change the referrer in the extra headers of
3510// an URLRequest.
3511TEST_F(URLRequestTest, DoNotOverrideReferrer) {
David Benjamin42116f62017-11-20 21:45:393512 HttpTestServer test_server;
[email protected]316c1e5e2012-09-12 15:17:443513 ASSERT_TRUE(test_server.Start());
3514
3515 // If extra headers contain referer and the request contains a referer,
3516 // only the latter shall be respected.
3517 {
3518 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363519 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163520 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3521 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193522 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443523
3524 HttpRequestHeaders headers;
3525 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193526 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443527
[email protected]f7022f32014-08-21 16:32:193528 req->Start();
[email protected]255620da2013-08-19 13:14:293529 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443530
3531 EXPECT_EQ("http://foo.com/", d.data_received());
3532 }
3533
3534 // If extra headers contain a referer but the request does not, no referer
3535 // shall be sent in the header.
3536 {
3537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363538 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163539 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
3540 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:443541
3542 HttpRequestHeaders headers;
3543 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193544 req->SetExtraRequestHeaders(headers);
3545 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443546
[email protected]f7022f32014-08-21 16:32:193547 req->Start();
[email protected]255620da2013-08-19 13:14:293548 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443549
3550 EXPECT_EQ("None", d.data_received());
3551 }
3552}
3553
[email protected]b89290212009-08-14 22:37:353554class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113555 public:
mmenke9f2ec60c2015-06-01 20:59:473556 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113557
[email protected]b89290212009-08-14 22:37:353558 protected:
[email protected]21184962011-10-26 00:50:303559 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3560 // |request_method| is the method to use for the initial request.
3561 // |redirect_method| is the method that is expected to be used for the second
3562 // request, after redirection.
3563 // If |include_data| is true, data is uploaded with the request. The
3564 // response body is expected to match it exactly, if and only if
3565 // |request_method| == |redirect_method|.
3566 void HTTPRedirectMethodTest(const GURL& redirect_url,
3567 const std::string& request_method,
3568 const std::string& redirect_method,
3569 bool include_data) {
3570 static const char kData[] = "hello world";
3571 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163572 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3573 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193574 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303575 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073576 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303577 HttpRequestHeaders headers;
3578 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:323579 base::NumberToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543580 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193581 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303582 }
[email protected]f7022f32014-08-21 16:32:193583 req->Start();
[email protected]255620da2013-08-19 13:14:293584 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193585 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503586 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303587 if (include_data) {
3588 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543589 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3590 HttpRequestHeaders::kContentLength));
3591 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3592 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303593 EXPECT_EQ(kData, d.data_received());
3594 } else {
svaldez5b3a8972015-10-09 23:23:543595 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3596 HttpRequestHeaders::kContentLength));
3597 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3598 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303599 EXPECT_NE(kData, d.data_received());
3600 }
3601 }
3602 if (HasFailure())
3603 LOG(WARNING) << "Request method was: " << request_method;
3604 }
3605
Alex Clarke1e08882b32017-10-06 14:22:403606 // Requests |redirect_url|, which must return a HTTP 3xx redirect. It's also
3607 // used as the initial origin.
jww5fe460ff2015-03-28 00:22:513608 // |request_method| is the method to use for the initial request.
3609 // |redirect_method| is the method that is expected to be used for the second
3610 // request, after redirection.
Alex Clarke1e08882b32017-10-06 14:22:403611 // |expected_origin_value| is the expected value for the Origin header after
jww5fe460ff2015-03-28 00:22:513612 // redirection. If empty, expects that there will be no Origin header.
3613 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3614 const std::string& request_method,
3615 const std::string& redirect_method,
Alex Clarke1e08882b32017-10-06 14:22:403616 const std::string& expected_origin_value) {
jww5fe460ff2015-03-28 00:22:513617 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:163618 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
3619 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jww5fe460ff2015-03-28 00:22:513620 req->set_method(request_method);
3621 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3622 redirect_url.GetOrigin().spec(), false);
3623 req->Start();
3624
3625 base::RunLoop().Run();
3626
3627 EXPECT_EQ(redirect_method, req->method());
3628 // Note that there is no check for request success here because, for
3629 // purposes of testing, the request very well may fail. For example, if the
3630 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3631 // origin, there is not an HTTPS server in this unit test framework, so the
3632 // request would fail. However, that's fine, as long as the request headers
3633 // are in order and pass the checks below.
Alex Clarke1e08882b32017-10-06 14:22:403634 if (expected_origin_value.empty()) {
jww5fe460ff2015-03-28 00:22:513635 EXPECT_FALSE(
3636 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3637 } else {
3638 std::string origin_header;
3639 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3640 HttpRequestHeaders::kOrigin, &origin_header));
Alex Clarke1e08882b32017-10-06 14:22:403641 EXPECT_EQ(expected_origin_value, origin_header);
jww5fe460ff2015-03-28 00:22:513642 }
3643 }
3644
[email protected]762d2db2010-01-11 19:03:013645 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013646 const int kMsgSize = 20000; // multiple of 10
3647 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483648 char* uploadBytes = new char[kMsgSize+1];
3649 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013650 char marker = 'a';
3651 for (int idx = 0; idx < kMsgSize/10; idx++) {
3652 memcpy(ptr, "----------", 10);
3653 ptr += 10;
3654 if (idx % 100 == 0) {
3655 ptr--;
3656 *ptr++ = marker;
3657 if (++marker > 'z')
3658 marker = 'a';
3659 }
3660 }
3661 uploadBytes[kMsgSize] = '\0';
3662
[email protected]762d2db2010-01-11 19:03:013663 for (int i = 0; i < kIterations; ++i) {
3664 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363665 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163666 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d,
3667 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193668 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013669
mmenkecbc2b712014-10-09 20:29:073670 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013671
[email protected]f7022f32014-08-21 16:32:193672 r->Start();
3673 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013674
[email protected]255620da2013-08-19 13:14:293675 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013676
maksim.sisovb53724b52016-09-16 05:30:503677 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3678 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013679
3680 EXPECT_FALSE(d.received_data_before_response());
3681 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013682 }
3683 delete[] uploadBytes;
3684 }
3685
[email protected]ede03212012-09-07 12:52:263686 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343687 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363688 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553689 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363690 base::IntToString(num_cookies)),
rhalavatib7bd7c792017-04-27 05:25:163691 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]263163f2012-06-14 22:40:343692
[email protected]f7022f32014-08-21 16:32:193693 r->Start();
3694 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343695
[email protected]255620da2013-08-19 13:14:293696 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343697
maksim.sisovb53724b52016-09-16 05:30:503698 if (d.request_status() != OK) {
3699 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3700 return false;
3701 }
[email protected]263163f2012-06-14 22:40:343702
maksim.sisovb53724b52016-09-16 05:30:503703 return true;
[email protected]263163f2012-06-14 22:40:343704 }
3705
David Benjamin42116f62017-11-20 21:45:393706 HttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503707
tommycli59a63432015-11-06 00:10:553708 private:
David Benjamin42116f62017-11-20 21:45:393709 HttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353710};
3711
tommycli59a63432015-11-06 00:10:553712namespace {
3713
danakj8522a25b2016-04-16 00:17:363714std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553715 const test_server::HttpRequest& request) {
3716 if (request.headers.find("Host") == request.headers.end() ||
3717 request.headers.at("Host") != "www.redirect.com" ||
3718 request.method != test_server::METHOD_CONNECT) {
3719 return nullptr;
3720 }
3721
danakj8522a25b2016-04-16 00:17:363722 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553723 new test_server::BasicHttpResponse);
3724 http_response->set_code(HTTP_FOUND);
3725 http_response->AddCustomHeader("Location",
3726 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483727 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553728}
3729
3730} // namespace
3731
nharperb7441ef2016-01-25 23:54:143732class TestSSLConfigService : public SSLConfigService {
3733 public:
Ryan Sleevi5b4702a2018-04-06 22:23:563734 TestSSLConfigService(bool online_rev_checking,
nharperb7441ef2016-01-25 23:54:143735 bool rev_checking_required_local_anchors,
3736 bool token_binding_enabled)
Ryan Sleevi5b4702a2018-04-06 22:23:563737 : online_rev_checking_(online_rev_checking),
nharperb7441ef2016-01-25 23:54:143738 rev_checking_required_local_anchors_(
3739 rev_checking_required_local_anchors),
3740 token_binding_enabled_(token_binding_enabled),
davidben095ebb52017-04-12 22:23:343741 min_version_(kDefaultSSLVersionMin),
3742 max_version_(kDefaultSSLVersionMax) {}
nharperb7441ef2016-01-25 23:54:143743
davidben095ebb52017-04-12 22:23:343744 void set_max_version(uint16_t version) { max_version_ = version; }
nharperb7441ef2016-01-25 23:54:143745 void set_min_version(uint16_t version) { min_version_ = version; }
3746
nharperb7441ef2016-01-25 23:54:143747 // SSLConfigService:
3748 void GetSSLConfig(SSLConfig* config) override {
3749 *config = SSLConfig();
3750 config->rev_checking_enabled = online_rev_checking_;
nharperb7441ef2016-01-25 23:54:143751 config->rev_checking_required_local_anchors =
3752 rev_checking_required_local_anchors_;
davidben095ebb52017-04-12 22:23:343753 config->version_min = min_version_;
3754 config->version_max = max_version_;
nharperb7441ef2016-01-25 23:54:143755 if (token_binding_enabled_) {
3756 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3757 }
3758 }
3759
3760 protected:
Chris Watkins7a41d3552017-12-01 02:13:273761 ~TestSSLConfigService() override = default;
nharperb7441ef2016-01-25 23:54:143762
3763 private:
nharperb7441ef2016-01-25 23:54:143764 const bool online_rev_checking_;
3765 const bool rev_checking_required_local_anchors_;
3766 const bool token_binding_enabled_;
3767 uint16_t min_version_;
davidben095ebb52017-04-12 22:23:343768 uint16_t max_version_;
nharperb7441ef2016-01-25 23:54:143769};
3770
3771// TODO(svaldez): Update tests to use EmbeddedTestServer.
3772#if !defined(OS_IOS)
3773class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3774 public:
fdoray9f0b4782017-02-10 12:55:473775 TokenBindingURLRequestTest() = default;
fdoraya89e673c2017-01-31 21:44:213776
nharperb7441ef2016-01-25 23:54:143777 void SetUp() override {
3778 default_context_.set_ssl_config_service(
Ryan Sleevi5b4702a2018-04-06 22:23:563779 new TestSSLConfigService(false, false, true));
fdoraya89e673c2017-01-31 21:44:213780 channel_id_service_.reset(
3781 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:143782 default_context_.set_channel_id_service(channel_id_service_.get());
3783 URLRequestTestHTTP::SetUp();
3784 }
3785
3786 protected:
danakj8522a25b2016-04-16 00:17:363787 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143788};
3789
3790TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3791 SpawnedTestServer::SSLOptions ssl_options;
3792 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3793 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3794 ssl_options,
3795 base::FilePath(kTestFilePath));
3796 ASSERT_TRUE(https_test_server.Start());
3797
3798 TestDelegate d;
3799 {
danakj8522a25b2016-04-16 00:17:363800 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163801 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d,
3802 TRAFFIC_ANNOTATION_FOR_TESTS));
nharperb7441ef2016-01-25 23:54:143803 r->Start();
3804 EXPECT_TRUE(r->is_pending());
3805
3806 base::RunLoop().Run();
3807
maksim.sisovb53724b52016-09-16 05:30:503808 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143809
3810 HttpRequestHeaders headers;
3811 std::string token_binding_header, token_binding_message;
3812 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3813 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3814 &token_binding_header));
3815 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353816 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143817 &token_binding_message));
nharperd6e65822016-03-30 23:05:483818 std::vector<TokenBinding> token_bindings;
3819 ASSERT_TRUE(
3820 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3821 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143822
3823 EXPECT_GT(d.bytes_received(), 0);
3824 std::string ekm = d.data_received();
3825
nharperd6e65822016-03-30 23:05:483826 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353827 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3828 token_bindings[0].signature,
3829 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143830 }
3831}
nharperd6e65822016-03-30 23:05:483832
3833TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3834 SpawnedTestServer::SSLOptions ssl_options;
3835 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3836 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3837 ssl_options,
3838 base::FilePath(kTestFilePath));
3839 ASSERT_TRUE(https_test_server.Start());
3840
3841 TestDelegate d;
3842 {
3843 GURL redirect_url =
3844 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
rhalavatib7bd7c792017-04-27 05:25:163845 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3846 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483847 r->Start();
3848 EXPECT_TRUE(r->is_pending());
3849
3850 base::RunLoop().Run();
3851
maksim.sisovb53724b52016-09-16 05:30:503852 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483853
3854 HttpRequestHeaders headers;
3855 std::string token_binding_header, token_binding_message;
3856 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3857 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3858 &token_binding_header));
3859 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353860 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483861 &token_binding_message));
3862 std::vector<TokenBinding> token_bindings;
3863 ASSERT_TRUE(
3864 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3865 ASSERT_EQ(2ull, token_bindings.size());
3866
3867 EXPECT_GT(d.bytes_received(), 0);
3868 std::string ekm = d.data_received();
3869
3870 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353871 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3872 token_bindings[0].signature,
3873 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483874 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353875 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3876 token_bindings[1].signature,
3877 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483878 }
3879}
3880
3881// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3882// EmbeddedTestServer once crbug.com/599187 is resolved.
3883#if !defined(OS_ANDROID)
3884TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
Sergey Ulanov9e8d6f32017-08-14 22:12:583885 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP, base::FilePath());
nharperd6e65822016-03-30 23:05:483886 ASSERT_TRUE(http_server.Start());
3887 SpawnedTestServer::SSLOptions ssl_options;
3888 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3889 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3890 ssl_options,
3891 base::FilePath(kTestFilePath));
3892 ASSERT_TRUE(https_test_server.Start());
3893
3894 TestDelegate d;
3895 {
3896 GURL redirect_url = http_server.GetURL(
3897 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163898 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3899 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483900 r->Start();
3901 EXPECT_TRUE(r->is_pending());
3902
3903 base::RunLoop().Run();
3904
maksim.sisovb53724b52016-09-16 05:30:503905 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483906
3907 HttpRequestHeaders headers;
3908 std::string token_binding_header, token_binding_message;
3909 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3910 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3911 &token_binding_header));
3912 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353913 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483914 &token_binding_message));
3915 std::vector<TokenBinding> token_bindings;
3916 ASSERT_TRUE(
3917 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3918 ASSERT_EQ(1ull, token_bindings.size());
3919
3920 EXPECT_GT(d.bytes_received(), 0);
3921 std::string ekm = d.data_received();
3922
3923 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353924 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3925 token_bindings[0].signature,
3926 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483927 }
3928}
3929
3930// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363931// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483932// support Token Binding, then we do not send a Sec-Token-Binding when following
3933// the redirect.
3934TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3935 SpawnedTestServer::SSLOptions ssl_options;
3936 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3937 ssl_options,
3938 base::FilePath(kTestFilePath));
3939 ASSERT_TRUE(https_test_server.Start());
3940 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3941 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3942 ssl_options,
3943 base::FilePath(kTestFilePath));
3944 ASSERT_TRUE(token_binding_test_server.Start());
3945
3946 TestDelegate d;
3947 {
3948 GURL redirect_url = token_binding_test_server.GetURL(
3949 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
rhalavatib7bd7c792017-04-27 05:25:163950 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
3951 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
nharperd6e65822016-03-30 23:05:483952 r->Start();
3953 EXPECT_TRUE(r->is_pending());
3954
3955 base::RunLoop().Run();
3956
maksim.sisovb53724b52016-09-16 05:30:503957 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483958
3959 HttpRequestHeaders headers;
3960 std::string token_binding_header, token_binding_message;
3961 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3962 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3963 &token_binding_header));
3964 }
3965}
3966#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143967#endif // !defined(OS_IOS)
3968
3969// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113970// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553971// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113972// follow.
[email protected]f2f31b32013-01-16 23:24:093973TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553974 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:123975 base::BindRepeating(&HandleRedirectConnect));
tommycli59a63432015-11-06 00:10:553976 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113977
[email protected]ceefd7fd2012-11-29 00:36:243978 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043979 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553980 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503981
[email protected]d1ec59082009-02-11 02:48:153982 TestDelegate d;
3983 {
danakj8522a25b2016-04-16 00:17:363984 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:163985 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
3986 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:193987 r->Start();
3988 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153989
[email protected]255620da2013-08-19 13:14:293990 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153991
[email protected]d8fc4722014-06-13 13:17:153992 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473993 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503994 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083995 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153996 // We should not have followed the redirect.
3997 EXPECT_EQ(0, d.received_redirect_count());
3998 }
3999}
4000
[email protected]8202d0c2011-02-23 08:31:144001// This is the same as the previous test, but checks that the network delegate
4002// registers the error.
[email protected]c044616e2013-02-20 02:01:264003TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:554004 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:144005
[email protected]ceefd7fd2012-11-29 00:36:244006 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044007 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554008 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504009
[email protected]8202d0c2011-02-23 08:31:144010 TestDelegate d;
4011 {
danakj8522a25b2016-04-16 00:17:364012 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164013 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d,
4014 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194015 r->Start();
4016 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:144017
[email protected]255620da2013-08-19 13:14:294018 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:144019
[email protected]d8fc4722014-06-13 13:17:154020 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474021 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:144022 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:504023 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:144024 // We should not have followed the redirect.
4025 EXPECT_EQ(0, d.received_redirect_count());
4026
4027 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:014028 EXPECT_THAT(network_delegate.last_error(),
4029 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:144030 }
4031}
4032
[email protected]dc5a5cf2012-09-26 02:49:304033// Tests that we can block and asynchronously return OK in various stages.
4034TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
4035 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
4036 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4037 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4038 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
4039 };
4040 static const size_t blocking_stages_length = arraysize(blocking_stages);
4041
tommycli59a63432015-11-06 00:10:554042 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:304043
4044 TestDelegate d;
4045 BlockingNetworkDelegate network_delegate(
4046 BlockingNetworkDelegate::USER_CALLBACK);
4047 network_delegate.set_block_on(
4048 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
4049 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
4050 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
4051
4052 TestURLRequestContext context(true);
4053 context.set_network_delegate(&network_delegate);
4054 context.Init();
4055
4056 {
danakj8522a25b2016-04-16 00:17:364057 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164058 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4059 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc5a5cf2012-09-26 02:49:304060
[email protected]f7022f32014-08-21 16:32:194061 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:304062 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:294063 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304064 EXPECT_EQ(blocking_stages[i],
4065 network_delegate.stage_blocked_for_callback());
4066 network_delegate.DoCallback(OK);
4067 }
[email protected]255620da2013-08-19 13:14:294068 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194069 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:504070 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:304071 EXPECT_EQ(1, network_delegate.created_requests());
4072 EXPECT_EQ(0, network_delegate.destroyed_requests());
4073 }
4074 EXPECT_EQ(1, network_delegate.destroyed_requests());
4075}
4076
[email protected]4c76d7c2011-04-15 19:14:124077// Tests that the network delegate can block and cancel a request.
4078TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:554079 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124080
4081 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304082 BlockingNetworkDelegate network_delegate(
4083 BlockingNetworkDelegate::AUTO_CALLBACK);
4084 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
4085 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:124086
[email protected]d5a4dd62012-05-23 01:41:044087 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554088 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504089
[email protected]4c76d7c2011-04-15 19:14:124090 {
rhalavatib7bd7c792017-04-27 05:25:164091 std::unique_ptr<URLRequest> r(
4092 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4093 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124094
[email protected]f7022f32014-08-21 16:32:194095 r->Start();
[email protected]255620da2013-08-19 13:14:294096 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124097
[email protected]d8fc4722014-06-13 13:17:154098 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474099 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504100 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:124101 EXPECT_EQ(1, network_delegate.created_requests());
4102 EXPECT_EQ(0, network_delegate.destroyed_requests());
4103 }
4104 EXPECT_EQ(1, network_delegate.destroyed_requests());
4105}
4106
[email protected]b4438d32012-09-27 06:15:304107// Helper function for NetworkDelegateCancelRequestAsynchronously and
4108// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
4109// delegate operating in |block_mode| and a request for |url|. It blocks the
4110// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
4111void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
4112 BlockingNetworkDelegate::Stage stage,
4113 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:364114 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:304115 BlockingNetworkDelegate network_delegate(block_mode);
4116 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
4117 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:364118
[email protected]b4438d32012-09-27 06:15:304119 TestURLRequestContext context(true);
4120 context.set_network_delegate(&network_delegate);
4121 context.Init();
[email protected]3cd384c602011-08-31 16:12:364122
4123 {
rhalavatib7bd7c792017-04-27 05:25:164124 std::unique_ptr<URLRequest> r(context.CreateRequest(
4125 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]3cd384c602011-08-31 16:12:364126
[email protected]f7022f32014-08-21 16:32:194127 r->Start();
[email protected]255620da2013-08-19 13:14:294128 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:364129
[email protected]d8fc4722014-06-13 13:17:154130 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:474131 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
4132 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
4133 EXPECT_FALSE(r->proxy_server().is_valid());
4134 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
4135 EXPECT_TRUE(r->proxy_server().is_direct());
4136 } else {
4137 NOTREACHED();
4138 }
maksim.sisovb53724b52016-09-16 05:30:504139 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:364140 EXPECT_EQ(1, network_delegate.created_requests());
4141 EXPECT_EQ(0, network_delegate.destroyed_requests());
4142 }
4143 EXPECT_EQ(1, network_delegate.destroyed_requests());
4144}
4145
[email protected]b4438d32012-09-27 06:15:304146// The following 3 tests check that the network delegate can cancel a request
4147// synchronously in various stages of the request.
4148TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:554149 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304150 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4151 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554152 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304153}
4154
4155TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:554156 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304157 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4158 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554159 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304160}
4161
4162TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:554163 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304164 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
4165 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554166 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304167}
4168
4169// The following 3 tests check that the network delegate can cancel a request
4170// asynchronously in various stages of the request.
4171TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:554172 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304173 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4174 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:554175 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304176}
4177
4178TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:554179 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304180 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4181 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:554182 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304183}
4184
4185TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:554186 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:304187 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
4188 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:554189 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:304190}
4191
[email protected]4c76d7c2011-04-15 19:14:124192// Tests that the network delegate can block and redirect a request to a new
4193// URL.
4194TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:554195 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:124196
4197 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304198 BlockingNetworkDelegate network_delegate(
4199 BlockingNetworkDelegate::AUTO_CALLBACK);
4200 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554201 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:124202 network_delegate.set_redirect_url(redirect_url);
4203
[email protected]d5a4dd62012-05-23 01:41:044204 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554205 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504206
[email protected]4c76d7c2011-04-15 19:14:124207 {
tommycli59a63432015-11-06 00:10:554208 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164209 std::unique_ptr<URLRequest> r(context.CreateRequest(
4210 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]4c76d7c2011-04-15 19:14:124211
[email protected]6be6fa92014-08-06 23:44:564212 // Quit after hitting the redirect, so can check the headers.
4213 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194214 r->Start();
[email protected]255620da2013-08-19 13:14:294215 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:124216
[email protected]6be6fa92014-08-06 23:44:564217 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194218 EXPECT_EQ(307, r->GetResponseCode());
4219 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564220 std::string location;
[email protected]f7022f32014-08-21 16:32:194221 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4222 &location));
[email protected]6be6fa92014-08-06 23:44:564223 EXPECT_EQ(redirect_url, GURL(location));
4224
4225 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194226 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564227 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:504228 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474229 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4230 http_test_server()->host_port_pair()),
4231 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094232 // before_send_headers_with_proxy_count only increments for headers sent
4233 // through an untunneled proxy.
4234 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554235 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4236 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:274237
maksim.sisovb53724b52016-09-16 05:30:504238 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194239 EXPECT_EQ(redirect_url, r->url());
4240 EXPECT_EQ(original_url, r->original_url());
4241 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:124242 EXPECT_EQ(1, network_delegate.created_requests());
4243 EXPECT_EQ(0, network_delegate.destroyed_requests());
4244 }
4245 EXPECT_EQ(1, network_delegate.destroyed_requests());
4246}
4247
[email protected]b813ed72012-04-05 08:21:364248// Tests that the network delegate can block and redirect a request to a new
4249// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
4250TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:554251 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:364252
4253 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304254 BlockingNetworkDelegate network_delegate(
4255 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:554256 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:364257 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:364258
[email protected]d5a4dd62012-05-23 01:41:044259 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554260 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:364261
4262 {
tommycli59a63432015-11-06 00:10:554263 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164264 std::unique_ptr<URLRequest> r(context.CreateRequest(
4265 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]b813ed72012-04-05 08:21:364266
[email protected]6be6fa92014-08-06 23:44:564267 // Quit after hitting the redirect, so can check the headers.
4268 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194269 r->Start();
[email protected]255620da2013-08-19 13:14:294270 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:364271
[email protected]6be6fa92014-08-06 23:44:564272 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194273 EXPECT_EQ(307, r->GetResponseCode());
4274 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564275 std::string location;
[email protected]f7022f32014-08-21 16:32:194276 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4277 &location));
[email protected]6be6fa92014-08-06 23:44:564278 EXPECT_EQ(redirect_url, GURL(location));
4279
4280 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194281 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564282 base::RunLoop().Run();
4283
maksim.sisovb53724b52016-09-16 05:30:504284 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474285 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4286 http_test_server()->host_port_pair()),
4287 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094288 // before_send_headers_with_proxy_count only increments for headers sent
4289 // through an untunneled proxy.
4290 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554291 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4292 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:504293 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194294 EXPECT_EQ(redirect_url, r->url());
4295 EXPECT_EQ(original_url, r->original_url());
4296 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:364297 EXPECT_EQ(1, network_delegate.created_requests());
4298 EXPECT_EQ(0, network_delegate.destroyed_requests());
4299 }
4300 EXPECT_EQ(1, network_delegate.destroyed_requests());
4301}
4302
[email protected]3c5ca8c2011-09-29 01:14:514303// Tests that redirects caused by the network delegate preserve POST data.
4304TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:554305 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:514306
4307 const char kData[] = "hello world";
4308
4309 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304310 BlockingNetworkDelegate network_delegate(
4311 BlockingNetworkDelegate::AUTO_CALLBACK);
4312 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:554313 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:514314 network_delegate.set_redirect_url(redirect_url);
4315
[email protected]ef2bf422012-05-11 03:27:094316 TestURLRequestContext context(true);
4317 context.set_network_delegate(&network_delegate);
4318 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:514319
4320 {
tommycli59a63432015-11-06 00:10:554321 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164322 std::unique_ptr<URLRequest> r(context.CreateRequest(
4323 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194324 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074325 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514326 HttpRequestHeaders headers;
4327 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:324328 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194329 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564330
4331 // Quit after hitting the redirect, so can check the headers.
4332 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194333 r->Start();
[email protected]255620da2013-08-19 13:14:294334 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514335
[email protected]6be6fa92014-08-06 23:44:564336 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194337 EXPECT_EQ(307, r->GetResponseCode());
4338 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564339 std::string location;
[email protected]f7022f32014-08-21 16:32:194340 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4341 &location));
[email protected]6be6fa92014-08-06 23:44:564342 EXPECT_EQ(redirect_url, GURL(location));
4343
4344 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194345 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564346 base::RunLoop().Run();
4347
maksim.sisovb53724b52016-09-16 05:30:504348 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194349 EXPECT_EQ(redirect_url, r->url());
4350 EXPECT_EQ(original_url, r->original_url());
4351 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514352 EXPECT_EQ(1, network_delegate.created_requests());
4353 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194354 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514355 EXPECT_EQ(kData, d.data_received());
4356 }
4357 EXPECT_EQ(1, network_delegate.destroyed_requests());
4358}
4359
[email protected]5f714132014-03-26 10:41:164360// Tests that the network delegate can block and redirect a request to a new
4361// URL during OnHeadersReceived.
4362TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554363 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164364
4365 TestDelegate d;
4366 BlockingNetworkDelegate network_delegate(
4367 BlockingNetworkDelegate::AUTO_CALLBACK);
4368 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554369 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164370 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4371
4372 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554373 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164374
4375 {
tommycli59a63432015-11-06 00:10:554376 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:164377 std::unique_ptr<URLRequest> r(context.CreateRequest(
4378 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:164379
[email protected]f7022f32014-08-21 16:32:194380 r->Start();
[email protected]5f714132014-03-26 10:41:164381 base::RunLoop().Run();
4382
maksim.sisovb53724b52016-09-16 05:30:504383 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474384 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4385 http_test_server()->host_port_pair()),
4386 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094387 // before_send_headers_with_proxy_count only increments for headers sent
4388 // through an untunneled proxy.
4389 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554390 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4391 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194392
maksim.sisovb53724b52016-09-16 05:30:504393 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194394 EXPECT_EQ(redirect_url, r->url());
4395 EXPECT_EQ(original_url, r->original_url());
4396 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164397 EXPECT_EQ(2, network_delegate.created_requests());
4398 EXPECT_EQ(0, network_delegate.destroyed_requests());
4399 }
4400 EXPECT_EQ(1, network_delegate.destroyed_requests());
4401}
4402
[email protected]c2911d72011-10-03 22:16:364403// Tests that the network delegate can synchronously complete OnAuthRequired
4404// by taking no action. This indicates that the NetworkDelegate does not want to
4405// handle the challenge, and is passing the buck along to the
4406// URLRequest::Delegate.
4407TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554408 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364409
4410 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304411 BlockingNetworkDelegate network_delegate(
4412 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364413
[email protected]ef2bf422012-05-11 03:27:094414 TestURLRequestContext context(true);
4415 context.set_network_delegate(&network_delegate);
4416 context.Init();
[email protected]c2911d72011-10-03 22:16:364417
[email protected]f3cf9802011-10-28 18:44:584418 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364419
4420 {
tommycli59a63432015-11-06 00:10:554421 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164422 std::unique_ptr<URLRequest> r(context.CreateRequest(
4423 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194424 r->Start();
[email protected]79e1fd62013-06-20 06:50:044425
[email protected]255620da2013-08-19 13:14:294426 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044427
maksim.sisovb53724b52016-09-16 05:30:504428 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194429 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044430 EXPECT_TRUE(d.auth_required_called());
4431 EXPECT_EQ(1, network_delegate.created_requests());
4432 EXPECT_EQ(0, network_delegate.destroyed_requests());
4433 }
4434 EXPECT_EQ(1, network_delegate.destroyed_requests());
4435}
4436
4437TEST_F(URLRequestTestHTTP,
4438 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554439 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044440
4441 TestDelegate d;
4442 BlockingNetworkDelegate network_delegate(
4443 BlockingNetworkDelegate::SYNCHRONOUS);
4444
4445 TestURLRequestContext context(true);
4446 context.set_network_delegate(&network_delegate);
4447 context.Init();
4448
4449 d.set_credentials(AuthCredentials(kUser, kSecret));
4450
4451 {
tommycli59a63432015-11-06 00:10:554452 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164453 std::unique_ptr<URLRequest> r(context.CreateRequest(
4454 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194455 r->Start();
[email protected]79e1fd62013-06-20 06:50:044456
shivanisha8061c4202017-06-13 23:35:524457 base::RunLoop().Run();
4458
[email protected]79e1fd62013-06-20 06:50:044459 {
4460 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194461 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
shivanisha8061c4202017-06-13 23:35:524462 EXPECT_TRUE(headers.HasHeader("Authorization"));
[email protected]79e1fd62013-06-20 06:50:044463 }
4464
maksim.sisovb53724b52016-09-16 05:30:504465 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194466 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364467 EXPECT_TRUE(d.auth_required_called());
4468 EXPECT_EQ(1, network_delegate.created_requests());
4469 EXPECT_EQ(0, network_delegate.destroyed_requests());
4470 }
4471 EXPECT_EQ(1, network_delegate.destroyed_requests());
4472}
4473
4474// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404475// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364476TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554477 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364478
4479 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304480 BlockingNetworkDelegate network_delegate(
4481 BlockingNetworkDelegate::SYNCHRONOUS);
4482 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364483 network_delegate.set_auth_retval(
4484 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4485
[email protected]f3cf9802011-10-28 18:44:584486 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364487
[email protected]ef2bf422012-05-11 03:27:094488 TestURLRequestContext context(true);
4489 context.set_network_delegate(&network_delegate);
4490 context.Init();
[email protected]c2911d72011-10-03 22:16:364491
4492 {
tommycli59a63432015-11-06 00:10:554493 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164494 std::unique_ptr<URLRequest> r(context.CreateRequest(
4495 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194496 r->Start();
[email protected]255620da2013-08-19 13:14:294497 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364498
maksim.sisovb53724b52016-09-16 05:30:504499 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194500 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364501 EXPECT_FALSE(d.auth_required_called());
4502 EXPECT_EQ(1, network_delegate.created_requests());
4503 EXPECT_EQ(0, network_delegate.destroyed_requests());
4504 }
4505 EXPECT_EQ(1, network_delegate.destroyed_requests());
4506}
4507
[email protected]79e1fd62013-06-20 06:50:044508// Same as above, but also tests that GetFullRequestHeaders returns the proper
4509// headers (for the first or second request) when called at the proper times.
4510TEST_F(URLRequestTestHTTP,
4511 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554512 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044513
4514 TestDelegate d;
4515 BlockingNetworkDelegate network_delegate(
4516 BlockingNetworkDelegate::SYNCHRONOUS);
4517 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4518 network_delegate.set_auth_retval(
4519 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4520
4521 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4522
4523 TestURLRequestContext context(true);
4524 context.set_network_delegate(&network_delegate);
4525 context.Init();
4526
4527 {
tommycli59a63432015-11-06 00:10:554528 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164529 std::unique_ptr<URLRequest> r(context.CreateRequest(
4530 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194531 r->Start();
[email protected]255620da2013-08-19 13:14:294532 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044533
maksim.sisovb53724b52016-09-16 05:30:504534 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194535 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044536 EXPECT_FALSE(d.auth_required_called());
4537 EXPECT_EQ(1, network_delegate.created_requests());
4538 EXPECT_EQ(0, network_delegate.destroyed_requests());
4539
4540 {
4541 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194542 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044543 EXPECT_TRUE(headers.HasHeader("Authorization"));
4544 }
4545 }
4546 EXPECT_EQ(1, network_delegate.destroyed_requests());
4547}
4548
[email protected]c2911d72011-10-03 22:16:364549// Tests that the network delegate can synchronously complete OnAuthRequired
4550// by cancelling authentication.
4551TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554552 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364553
4554 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304555 BlockingNetworkDelegate network_delegate(
4556 BlockingNetworkDelegate::SYNCHRONOUS);
4557 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364558 network_delegate.set_auth_retval(
4559 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4560
[email protected]ef2bf422012-05-11 03:27:094561 TestURLRequestContext context(true);
4562 context.set_network_delegate(&network_delegate);
4563 context.Init();
[email protected]c2911d72011-10-03 22:16:364564
4565 {
tommycli59a63432015-11-06 00:10:554566 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164567 std::unique_ptr<URLRequest> r(context.CreateRequest(
4568 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194569 r->Start();
[email protected]255620da2013-08-19 13:14:294570 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364571
maksim.sisovb53724b52016-09-16 05:30:504572 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194573 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364574 EXPECT_FALSE(d.auth_required_called());
4575 EXPECT_EQ(1, network_delegate.created_requests());
4576 EXPECT_EQ(0, network_delegate.destroyed_requests());
4577 }
4578 EXPECT_EQ(1, network_delegate.destroyed_requests());
4579}
4580
4581// Tests that the network delegate can asynchronously complete OnAuthRequired
4582// by taking no action. This indicates that the NetworkDelegate does not want
4583// to handle the challenge, and is passing the buck along to the
4584// URLRequest::Delegate.
4585TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554586 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364587
4588 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304589 BlockingNetworkDelegate network_delegate(
4590 BlockingNetworkDelegate::AUTO_CALLBACK);
4591 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364592
[email protected]ef2bf422012-05-11 03:27:094593 TestURLRequestContext context(true);
4594 context.set_network_delegate(&network_delegate);
4595 context.Init();
[email protected]c2911d72011-10-03 22:16:364596
[email protected]f3cf9802011-10-28 18:44:584597 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364598
4599 {
tommycli59a63432015-11-06 00:10:554600 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164601 std::unique_ptr<URLRequest> r(context.CreateRequest(
4602 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194603 r->Start();
[email protected]255620da2013-08-19 13:14:294604 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364605
maksim.sisovb53724b52016-09-16 05:30:504606 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194607 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364608 EXPECT_TRUE(d.auth_required_called());
4609 EXPECT_EQ(1, network_delegate.created_requests());
4610 EXPECT_EQ(0, network_delegate.destroyed_requests());
4611 }
4612 EXPECT_EQ(1, network_delegate.destroyed_requests());
4613}
4614
4615// Tests that the network delegate can asynchronously complete OnAuthRequired
4616// by setting credentials.
4617TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554618 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364619
4620 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304621 BlockingNetworkDelegate network_delegate(
4622 BlockingNetworkDelegate::AUTO_CALLBACK);
4623 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364624 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364625 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4626
[email protected]f3cf9802011-10-28 18:44:584627 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364628 network_delegate.set_auth_credentials(auth_credentials);
4629
[email protected]ef2bf422012-05-11 03:27:094630 TestURLRequestContext context(true);
4631 context.set_network_delegate(&network_delegate);
4632 context.Init();
[email protected]c2911d72011-10-03 22:16:364633
4634 {
tommycli59a63432015-11-06 00:10:554635 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164636 std::unique_ptr<URLRequest> r(context.CreateRequest(
4637 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194638 r->Start();
[email protected]255620da2013-08-19 13:14:294639 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364640
maksim.sisovb53724b52016-09-16 05:30:504641 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194642 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364643 EXPECT_FALSE(d.auth_required_called());
4644 EXPECT_EQ(1, network_delegate.created_requests());
4645 EXPECT_EQ(0, network_delegate.destroyed_requests());
4646 }
4647 EXPECT_EQ(1, network_delegate.destroyed_requests());
4648}
4649
4650// Tests that the network delegate can asynchronously complete OnAuthRequired
4651// by cancelling authentication.
4652TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554653 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364654
4655 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304656 BlockingNetworkDelegate network_delegate(
4657 BlockingNetworkDelegate::AUTO_CALLBACK);
4658 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364659 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364660 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4661
[email protected]ef2bf422012-05-11 03:27:094662 TestURLRequestContext context(true);
4663 context.set_network_delegate(&network_delegate);
4664 context.Init();
[email protected]c2911d72011-10-03 22:16:364665
4666 {
tommycli59a63432015-11-06 00:10:554667 GURL url(http_test_server()->GetURL("/auth-basic"));
rhalavatib7bd7c792017-04-27 05:25:164668 std::unique_ptr<URLRequest> r(context.CreateRequest(
4669 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:194670 r->Start();
[email protected]255620da2013-08-19 13:14:294671 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364672
maksim.sisovb53724b52016-09-16 05:30:504673 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194674 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364675 EXPECT_FALSE(d.auth_required_called());
4676 EXPECT_EQ(1, network_delegate.created_requests());
4677 EXPECT_EQ(0, network_delegate.destroyed_requests());
4678 }
4679 EXPECT_EQ(1, network_delegate.destroyed_requests());
4680}
4681
David Benjamin0bda12f2018-02-07 19:58:454682// Tests that NetworkDelegate header overrides from the 401 response do not
4683// affect the 200 response. This is a regression test for
4684// https://crbug.com/801237.
4685TEST_F(URLRequestTestHTTP, NetworkDelegateOverrideHeadersWithAuth) {
4686 ASSERT_TRUE(http_test_server()->Start());
4687
4688 TestDelegate d;
4689 d.set_credentials(AuthCredentials(kUser, kSecret));
4690 default_network_delegate_.set_add_header_to_first_response(true);
4691
4692 {
4693 GURL url(http_test_server()->GetURL("/auth-basic"));
4694 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4695 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4696 r->Start();
4697
4698 base::RunLoop().Run();
4699
4700 EXPECT_EQ(OK, d.request_status());
4701 EXPECT_EQ(200, r->GetResponseCode());
4702 EXPECT_TRUE(d.auth_required_called());
4703 EXPECT_FALSE(r->response_headers()->HasHeader("X-Network-Delegate"));
4704 }
4705
4706 {
4707 GURL url(http_test_server()->GetURL("/defaultresponse"));
4708 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
4709 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
4710 r->Start();
4711
4712 base::RunLoop().Run();
4713
4714 // Check that set_add_header_to_first_response normally adds a header.
4715 EXPECT_EQ(OK, d.request_status());
4716 EXPECT_EQ(200, r->GetResponseCode());
4717 EXPECT_TRUE(r->response_headers()->HasHeader("X-Network-Delegate"));
4718 }
4719}
4720
[email protected]9045b8822012-01-13 20:35:354721// Tests that we can handle when a network request was canceled while we were
4722// waiting for the network delegate.
4723// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4724TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554725 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354726
4727 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304728 BlockingNetworkDelegate network_delegate(
4729 BlockingNetworkDelegate::USER_CALLBACK);
4730 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354731
[email protected]ef2bf422012-05-11 03:27:094732 TestURLRequestContext context(true);
4733 context.set_network_delegate(&network_delegate);
4734 context.Init();
[email protected]9045b8822012-01-13 20:35:354735
4736 {
rhalavatib7bd7c792017-04-27 05:25:164737 std::unique_ptr<URLRequest> r(
4738 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4739 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354740
[email protected]f7022f32014-08-21 16:32:194741 r->Start();
[email protected]255620da2013-08-19 13:14:294742 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304743 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4744 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354745 EXPECT_EQ(0, network_delegate.completed_requests());
4746 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194747 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354748 // Ensure that network delegate is notified.
4749 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504750 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354751 EXPECT_EQ(1, network_delegate.created_requests());
4752 EXPECT_EQ(0, network_delegate.destroyed_requests());
4753 }
4754 EXPECT_EQ(1, network_delegate.destroyed_requests());
4755}
4756
4757// Tests that we can handle when a network request was canceled while we were
4758// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004759// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4760// callback.
[email protected]9045b8822012-01-13 20:35:354761TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554762 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354763
4764 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304765 BlockingNetworkDelegate network_delegate(
4766 BlockingNetworkDelegate::USER_CALLBACK);
4767 network_delegate.set_block_on(
4768 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354769
[email protected]ef2bf422012-05-11 03:27:094770 TestURLRequestContext context(true);
4771 context.set_network_delegate(&network_delegate);
4772 context.Init();
[email protected]9045b8822012-01-13 20:35:354773
4774 {
rhalavatib7bd7c792017-04-27 05:25:164775 std::unique_ptr<URLRequest> r(
4776 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4777 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354778
[email protected]f7022f32014-08-21 16:32:194779 r->Start();
[email protected]255620da2013-08-19 13:14:294780 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304781 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4782 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354783 EXPECT_EQ(0, network_delegate.completed_requests());
4784 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194785 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354786 // Ensure that network delegate is notified.
4787 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504788 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354789 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
4795// Tests that we can handle when a network request was canceled while we were
4796// waiting for the network delegate.
4797// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4798TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554799 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354800
4801 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304802 BlockingNetworkDelegate network_delegate(
4803 BlockingNetworkDelegate::USER_CALLBACK);
4804 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354805
[email protected]ef2bf422012-05-11 03:27:094806 TestURLRequestContext context(true);
4807 context.set_network_delegate(&network_delegate);
4808 context.Init();
[email protected]9045b8822012-01-13 20:35:354809
4810 {
rhalavatib7bd7c792017-04-27 05:25:164811 std::unique_ptr<URLRequest> r(
4812 context.CreateRequest(http_test_server()->GetURL("/"), DEFAULT_PRIORITY,
4813 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354814
[email protected]f7022f32014-08-21 16:32:194815 r->Start();
[email protected]255620da2013-08-19 13:14:294816 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304817 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4818 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354819 EXPECT_EQ(0, network_delegate.completed_requests());
4820 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194821 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354822 // Ensure that network delegate is notified.
4823 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504824 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354825 EXPECT_EQ(1, network_delegate.created_requests());
4826 EXPECT_EQ(0, network_delegate.destroyed_requests());
4827 }
4828 EXPECT_EQ(1, network_delegate.destroyed_requests());
4829}
4830
4831// Tests that we can handle when a network request was canceled while we were
4832// waiting for the network delegate.
4833// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024834TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554835 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354836
4837 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304838 BlockingNetworkDelegate network_delegate(
4839 BlockingNetworkDelegate::USER_CALLBACK);
4840 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354841
[email protected]ef2bf422012-05-11 03:27:094842 TestURLRequestContext context(true);
4843 context.set_network_delegate(&network_delegate);
4844 context.Init();
[email protected]9045b8822012-01-13 20:35:354845
4846 {
danakj8522a25b2016-04-16 00:17:364847 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164848 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
4849 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]9045b8822012-01-13 20:35:354850
[email protected]f7022f32014-08-21 16:32:194851 r->Start();
[email protected]255620da2013-08-19 13:14:294852 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304853 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4854 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354855 EXPECT_EQ(0, network_delegate.completed_requests());
4856 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194857 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354858 // Ensure that network delegate is notified.
4859 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504860 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354861 EXPECT_EQ(1, network_delegate.created_requests());
4862 EXPECT_EQ(0, network_delegate.destroyed_requests());
4863 }
4864 EXPECT_EQ(1, network_delegate.destroyed_requests());
4865}
4866
tommycli59a63432015-11-06 00:10:554867namespace {
4868
danakj8522a25b2016-04-16 00:17:364869std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554870 const test_server::HttpRequest& request) {
4871 if (request.headers.find("Host") == request.headers.end() ||
4872 request.headers.at("Host") != "www.server-auth.com" ||
4873 request.method != test_server::METHOD_CONNECT) {
4874 return nullptr;
4875 }
4876
danakj8522a25b2016-04-16 00:17:364877 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554878 new test_server::BasicHttpResponse);
4879 http_response->set_code(HTTP_UNAUTHORIZED);
4880 http_response->AddCustomHeader("WWW-Authenticate",
4881 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484882 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554883}
4884
4885} // namespace
4886
4887// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114888// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554889// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354890TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554891 http_test_server()->RegisterRequestHandler(
Matt Menke2b2a60472018-02-07 02:12:124892 base::BindRepeating(&HandleServerAuthConnect));
tommycli59a63432015-11-06 00:10:554893 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114894
[email protected]ceefd7fd2012-11-29 00:36:244895 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044896 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554897 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504898
[email protected]dc651782009-02-14 01:45:084899 TestDelegate d;
4900 {
danakj8522a25b2016-04-16 00:17:364901 std::unique_ptr<URLRequest> r(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164902 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d,
4903 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]dc651782009-02-14 01:45:084904
[email protected]f7022f32014-08-21 16:32:194905 r->Start();
4906 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084907
[email protected]255620da2013-08-19 13:14:294908 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084909
[email protected]d8fc4722014-06-13 13:17:154910 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474911 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504912 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084913 }
4914}
4915
[email protected]b89290212009-08-14 22:37:354916TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554917 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114918
initial.commit586acc5fe2008-07-26 22:42:524919 TestDelegate d;
4920 {
danakj8522a25b2016-04-16 00:17:364921 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164922 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4923 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524924
[email protected]f7022f32014-08-21 16:32:194925 r->Start();
4926 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524927
[email protected]255620da2013-08-19 13:14:294928 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524929
4930 EXPECT_EQ(1, d.response_started_count());
4931 EXPECT_FALSE(d.received_data_before_response());
4932 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554933 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194934 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554935 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194936 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164937
[email protected]9e743cd2010-03-16 07:03:534938 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524939 }
initial.commit586acc5fe2008-07-26 22:42:524940}
4941
[email protected]263163f2012-06-14 22:40:344942// This test has the server send a large number of cookies to the client.
4943// To ensure that no number of cookies causes a crash, a galloping binary
4944// search is used to estimate that maximum number of cookies that are accepted
4945// by the browser. Beyond the maximum number, the request will fail with
4946// ERR_RESPONSE_HEADERS_TOO_BIG.
Sergey Ulanov0fb900c2017-09-20 00:27:314947#if defined(OS_WIN) || defined(OS_FUCHSIA)
[email protected]69dd6fe2013-02-23 23:15:304948// http://crbug.com/177916
4949#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4950#else
4951#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4952#endif // defined(OS_WIN)
4953TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554954 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344955
4956 int lower_bound = 0;
4957 int upper_bound = 1;
4958
4959 // Double the number of cookies until the response header limits are
4960 // exceeded.
4961 while (DoManyCookiesRequest(upper_bound)) {
4962 lower_bound = upper_bound;
4963 upper_bound *= 2;
4964 ASSERT_LT(upper_bound, 1000000);
4965 }
4966
pkasting6b68a162014-12-01 22:10:294967 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344968 if (tolerance < 2)
4969 tolerance = 2;
4970
4971 // Perform a binary search to find the highest possible number of cookies,
4972 // within the desired tolerance.
4973 while (upper_bound - lower_bound >= tolerance) {
4974 int num_cookies = (lower_bound + upper_bound) / 2;
4975
4976 if (DoManyCookiesRequest(num_cookies))
4977 lower_bound = num_cookies;
4978 else
4979 upper_bound = num_cookies;
4980 }
4981 // Success: the test did not crash.
4982}
4983
[email protected]b89290212009-08-14 22:37:354984TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554985 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114986
initial.commit586acc5fe2008-07-26 22:42:524987 TestDelegate d;
4988 {
danakj8522a25b2016-04-16 00:17:364989 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:164990 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
4991 TRAFFIC_ANNOTATION_FOR_TESTS));
initial.commit586acc5fe2008-07-26 22:42:524992
[email protected]f7022f32014-08-21 16:32:194993 r->Start();
4994 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524995
[email protected]255620da2013-08-19 13:14:294996 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524997
4998 EXPECT_EQ(1, d.response_started_count());
4999 EXPECT_FALSE(d.received_data_before_response());
5000 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555001 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195002 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555003 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195004 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:525005 }
[email protected]5d7b373e2009-09-02 07:19:035006}
5007
[email protected]79e1fd62013-06-20 06:50:045008TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:555009 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:045010
5011 TestDelegate d;
5012 {
tommycli59a63432015-11-06 00:10:555013 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
rhalavatib7bd7c792017-04-27 05:25:165014 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
5015 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:045016
5017 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:195018 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:045019
[email protected]f7022f32014-08-21 16:32:195020 r->Start();
5021 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:045022
[email protected]255620da2013-08-19 13:14:295023 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045024
5025 EXPECT_EQ(1, d.response_started_count());
5026 EXPECT_FALSE(d.received_data_before_response());
5027 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555028 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195029 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555030 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195031 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:045032
5033 EXPECT_TRUE(d.have_full_request_headers());
5034 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5035 }
5036}
5037
[email protected]58e32bb2013-01-21 18:23:255038TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:555039 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255040
5041 TestDelegate d;
5042 {
danakj8522a25b2016-04-16 00:17:365043 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165044 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
5045 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]58e32bb2013-01-21 18:23:255046
[email protected]f7022f32014-08-21 16:32:195047 r->Start();
5048 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:255049
[email protected]255620da2013-08-19 13:14:295050 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255051
5052 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195053 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255054 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5055
5056 EXPECT_EQ(1, d.response_started_count());
5057 EXPECT_FALSE(d.received_data_before_response());
5058 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:555059 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:195060 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:555061 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:195062 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:255063 }
5064}
5065
tommycli59a63432015-11-06 00:10:555066// TODO(svaldez): Update tests to use EmbeddedTestServer.
5067#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395068TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:555069 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555070 base::FilePath(kTestFilePath));
5071
5072 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:395073
5074 // Parameter that specifies the Content-Length field in the response:
5075 // C - Compressed length.
5076 // U - Uncompressed length.
5077 // L - Large length (larger than both C & U).
5078 // M - Medium length (between C & U).
5079 // S - Small length (smaller than both C & U).
5080 const char test_parameters[] = "CULMS";
5081 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
5082 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:445083 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:395084 // S has too little data, but we seem to accept it.
5085 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:375086 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:395087
xunjielifb4da222016-07-14 18:38:595088 base::FilePath file_path;
5089 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
5090 file_path = file_path.Append(kTestFilePath);
5091 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
5092 std::string expected_content;
5093 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
5094
5095 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:395096 TestDelegate d;
5097 {
tommycli59a63432015-11-06 00:10:555098 std::string test_file = base::StringPrintf(
5099 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:395100
[email protected]ceefd7fd2012-11-29 00:36:245101 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095102 TestURLRequestContext context(true);
5103 context.set_network_delegate(&network_delegate);
5104 context.Init();
[email protected]87a09a92011-07-14 15:50:505105
rhalavatib7bd7c792017-04-27 05:25:165106 std::unique_ptr<URLRequest> r(
5107 context.CreateRequest(test_server.GetURL(test_file), DEFAULT_PRIORITY,
5108 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195109 r->Start();
5110 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:395111
[email protected]255620da2013-08-19 13:14:295112 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:395113
5114 EXPECT_EQ(1, d.response_started_count());
5115 EXPECT_FALSE(d.received_data_before_response());
5116 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:505117 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:395118 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:505119 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
5120 << "\"";
xunjielifb4da222016-07-14 18:38:595121 if (test_parameters[i] == 'S') {
5122 // When content length is smaller than both compressed length and
5123 // uncompressed length, HttpStreamParser might not read the full
5124 // response body.
5125 continue;
5126 }
5127 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:395128 } else {
maksim.sisovb53724b52016-09-16 05:30:505129 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:395130 << " Parameter = \"" << test_file << "\"";
5131 }
5132 }
5133 }
5134}
tommycli59a63432015-11-06 00:10:555135#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:395136
[email protected]58e32bb2013-01-21 18:23:255137TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:555138 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:255139
tommycli59a63432015-11-06 00:10:555140 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455141 GURL original_url =
tommycli59a63432015-11-06 00:10:555142 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:255143 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165144 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5145 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195146 req->Start();
[email protected]255620da2013-08-19 13:14:295147 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255148
5149 EXPECT_EQ(1, d.response_started_count());
5150 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195151 EXPECT_EQ(destination_url, req->url());
5152 EXPECT_EQ(original_url, req->original_url());
5153 ASSERT_EQ(2U, req->url_chain().size());
5154 EXPECT_EQ(original_url, req->url_chain()[0]);
5155 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:255156
5157 LoadTimingInfo load_timing_info_before_redirect;
5158 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
5159 &load_timing_info_before_redirect));
5160 TestLoadTimingNotReused(load_timing_info_before_redirect,
5161 CONNECT_TIMING_HAS_DNS_TIMES);
5162
5163 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195164 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255165 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5166
5167 // Check that a new socket was used on redirect, since the server does not
5168 // supposed keep-alive sockets, and that the times before the redirect are
5169 // before the ones recorded for the second request.
5170 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
5171 load_timing_info.socket_log_id);
5172 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
5173 load_timing_info.connect_timing.connect_start);
5174}
5175
[email protected]8f1ac082011-04-19 21:14:135176TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:555177 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:135178
tommycli59a63432015-11-06 00:10:555179 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:455180 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:555181 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
5182 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
5183 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:135184 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165185 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5186 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195187 req->Start();
[email protected]255620da2013-08-19 13:14:295188 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:135189
5190 EXPECT_EQ(1, d.response_started_count());
5191 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195192 EXPECT_EQ(destination_url, req->url());
5193 EXPECT_EQ(original_url, req->original_url());
5194 ASSERT_EQ(3U, req->url_chain().size());
5195 EXPECT_EQ(original_url, req->url_chain()[0]);
5196 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
5197 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:135198}
5199
[email protected]abe1c4a2013-10-25 19:28:515200// First and second pieces of information logged by delegates to URLRequests.
5201const char kFirstDelegateInfo[] = "Wonderful delegate";
5202const char kSecondDelegateInfo[] = "Exciting delegate";
5203
5204// Logs delegate information to a URLRequest. The first string is logged
5205// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
5206// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
5207// another asynchronous call is used to clear the delegate information
5208// before calling a callback. The object then deletes itself.
5209class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
5210 public:
5211 typedef base::Callback<void()> Callback;
5212
5213 // Each time delegate information is added to the URLRequest, the resulting
5214 // load state is checked. The expected load state after each request is
5215 // passed in as an argument.
5216 static void Run(URLRequest* url_request,
5217 LoadState expected_first_load_state,
5218 LoadState expected_second_load_state,
5219 LoadState expected_third_load_state,
5220 const Callback& callback) {
5221 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
5222 url_request,
5223 expected_first_load_state,
5224 expected_second_load_state,
5225 expected_third_load_state,
5226 callback);
5227 logger->Start();
5228 }
5229
5230 // Checks that the log entries, starting with log_position, contain the
5231 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
5232 // recorded. Returns the index of entry after the expected number of
5233 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:465234 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:515235 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:515236 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
5237 if (log_position + 3 >= entries.size()) {
5238 ADD_FAILURE() << "Not enough log entries";
5239 return entries.size();
5240 }
5241 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:005242 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5243 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075244 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515245 &delegate_info));
5246 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
5247
5248 ++log_position;
mikecirone8b85c432016-09-08 19:11:005249 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5250 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515251
5252 ++log_position;
mikecirone8b85c432016-09-08 19:11:005253 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5254 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:075255 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:515256 &delegate_info));
5257 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
5258
5259 ++log_position;
mikecirone8b85c432016-09-08 19:11:005260 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
5261 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515262
5263 return log_position + 1;
5264 }
5265
5266 private:
5267 friend class base::RefCounted<AsyncDelegateLogger>;
5268
5269 AsyncDelegateLogger(URLRequest* url_request,
5270 LoadState expected_first_load_state,
5271 LoadState expected_second_load_state,
5272 LoadState expected_third_load_state,
5273 const Callback& callback)
5274 : url_request_(url_request),
5275 expected_first_load_state_(expected_first_load_state),
5276 expected_second_load_state_(expected_second_load_state),
5277 expected_third_load_state_(expected_third_load_state),
5278 callback_(callback) {
5279 }
5280
Chris Watkins7a41d3552017-12-01 02:13:275281 ~AsyncDelegateLogger() = default;
[email protected]abe1c4a2013-10-25 19:28:515282
5283 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:535284 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515285 LoadStateWithParam load_state = url_request_->GetLoadState();
5286 EXPECT_EQ(expected_first_load_state_, load_state.state);
5287 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:455288 base::ThreadTaskRunnerHandle::Get()->PostTask(
5289 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:515290 }
5291
5292 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:535293 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:515294 LoadStateWithParam load_state = url_request_->GetLoadState();
5295 EXPECT_EQ(expected_second_load_state_, load_state.state);
5296 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
5297 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5298 } else {
5299 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
5300 }
skyostil4891b25b2015-06-11 11:43:455301 base::ThreadTaskRunnerHandle::Get()->PostTask(
5302 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:515303 }
5304
5305 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:535306 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:515307 LoadStateWithParam load_state = url_request_->GetLoadState();
5308 EXPECT_EQ(expected_third_load_state_, load_state.state);
5309 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:085310 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515311 callback_.Run();
5312 }
5313
5314 URLRequest* url_request_;
5315 const int expected_first_load_state_;
5316 const int expected_second_load_state_;
5317 const int expected_third_load_state_;
5318 const Callback callback_;
5319
5320 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
5321};
5322
5323// NetworkDelegate that logs delegate information before a request is started,
5324// before headers are sent, when headers are read, and when auth information
5325// is requested. Uses AsyncDelegateLogger.
5326class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
5327 public:
Chris Watkins7a41d3552017-12-01 02:13:275328 AsyncLoggingNetworkDelegate() = default;
5329 ~AsyncLoggingNetworkDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515330
5331 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:205332 int OnBeforeURLRequest(URLRequest* request,
5333 const CompletionCallback& callback,
5334 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:515335 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
5336 return RunCallbackAsynchronously(request, callback);
5337 }
5338
ryansturm2343cb62016-06-15 01:09:005339 int OnBeforeStartTransaction(URLRequest* request,
5340 const CompletionCallback& callback,
5341 HttpRequestHeaders* headers) override {
5342 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:515343 return RunCallbackAsynchronously(request, callback);
5344 }
5345
dchengb03027d2014-10-21 12:00:205346 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:515347 URLRequest* request,
5348 const CompletionCallback& callback,
5349 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:165350 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:135351 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:165352 TestNetworkDelegate::OnHeadersReceived(request,
5353 callback,
[email protected]abe1c4a2013-10-25 19:28:515354 original_response_headers,
[email protected]5f714132014-03-26 10:41:165355 override_response_headers,
5356 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:515357 return RunCallbackAsynchronously(request, callback);
5358 }
5359
dchengb03027d2014-10-21 12:00:205360 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:515361 URLRequest* request,
5362 const AuthChallengeInfo& auth_info,
5363 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:135364 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:515365 AsyncDelegateLogger::Run(
5366 request,
5367 LOAD_STATE_WAITING_FOR_DELEGATE,
5368 LOAD_STATE_WAITING_FOR_DELEGATE,
5369 LOAD_STATE_WAITING_FOR_DELEGATE,
5370 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5371 callback, credentials));
5372 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5373 }
5374
5375 private:
5376 static int RunCallbackAsynchronously(
5377 URLRequest* request,
5378 const CompletionCallback& callback) {
5379 AsyncDelegateLogger::Run(
5380 request,
5381 LOAD_STATE_WAITING_FOR_DELEGATE,
5382 LOAD_STATE_WAITING_FOR_DELEGATE,
5383 LOAD_STATE_WAITING_FOR_DELEGATE,
5384 base::Bind(callback, OK));
5385 return ERR_IO_PENDING;
5386 }
5387
5388 static void SetAuthAndResume(const AuthCallback& callback,
5389 AuthCredentials* credentials) {
5390 *credentials = AuthCredentials(kUser, kSecret);
5391 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5392 }
5393
5394 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5395};
5396
5397// URLRequest::Delegate that logs delegate information when the headers
5398// are received, when each read completes, and during redirects. Uses
5399// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5400//
5401// Inherits from TestDelegate to reuse the TestDelegate code to handle
5402// advancing to the next step in most cases, as well as cancellation.
5403class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5404 public:
5405 enum CancelStage {
5406 NO_CANCEL = 0,
5407 CANCEL_ON_RECEIVED_REDIRECT,
5408 CANCEL_ON_RESPONSE_STARTED,
5409 CANCEL_ON_READ_COMPLETED
5410 };
5411
5412 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5413 : cancel_stage_(cancel_stage) {
5414 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5415 set_cancel_in_received_redirect(true);
5416 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5417 set_cancel_in_response_started(true);
5418 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5419 set_cancel_in_received_data(true);
5420 }
Chris Watkins7a41d3552017-12-01 02:13:275421 ~AsyncLoggingUrlRequestDelegate() override = default;
[email protected]abe1c4a2013-10-25 19:28:515422
5423 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205424 void OnReceivedRedirect(URLRequest* request,
5425 const RedirectInfo& redirect_info,
5426 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515427 *defer_redirect = true;
5428 AsyncDelegateLogger::Run(
5429 request,
5430 LOAD_STATE_WAITING_FOR_DELEGATE,
5431 LOAD_STATE_WAITING_FOR_DELEGATE,
5432 LOAD_STATE_WAITING_FOR_DELEGATE,
5433 base::Bind(
5434 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595435 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515436 }
5437
maksim.sisov0f4aa142016-09-05 05:55:285438 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515439 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285440 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5441 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5442 base::Bind(
5443 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5444 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515445 }
5446
dchengb03027d2014-10-21 12:00:205447 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515448 AsyncDelegateLogger::Run(
5449 request,
5450 LOAD_STATE_IDLE,
5451 LOAD_STATE_IDLE,
5452 LOAD_STATE_IDLE,
5453 base::Bind(
5454 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5455 base::Unretained(this), request, bytes_read));
5456 }
5457
5458 private:
5459 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595460 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515461 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595462 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515463 // FollowDeferredRedirect should not be called after cancellation.
5464 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5465 return;
5466 if (!defer_redirect)
5467 request->FollowDeferredRedirect();
5468 }
5469
maksim.sisov0f4aa142016-09-05 05:55:285470 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515471 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285472 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515473 }
5474
5475 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5476 // The parent class continues the request.
5477 TestDelegate::OnReadCompleted(request, bytes_read);
5478 }
5479
5480 const CancelStage cancel_stage_;
5481
5482 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5483};
5484
5485// Tests handling of delegate info before a request starts.
5486TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555487 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515488
5489 TestDelegate request_delegate;
5490 TestURLRequestContext context(true);
5491 context.set_network_delegate(NULL);
5492 context.set_net_log(&net_log_);
5493 context.Init();
5494
5495 {
rhalavatib7bd7c792017-04-27 05:25:165496 std::unique_ptr<URLRequest> r(context.CreateRequest(
5497 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY,
5498 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195499 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515500 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085501 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515502
5503 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195504 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515505 LOAD_STATE_WAITING_FOR_DELEGATE,
5506 LOAD_STATE_WAITING_FOR_DELEGATE,
5507 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195508 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515509
5510 base::RunLoop().Run();
5511
[email protected]f7022f32014-08-21 16:32:195512 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505513 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515514 }
5515
mmenke43758e62015-05-04 21:09:465516 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515517 net_log_.GetEntries(&entries);
5518 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005519 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515520
5521 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5522
5523 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005524 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5525 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515526}
5527
5528// Tests handling of delegate info from a network delegate.
5529TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555530 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515531
5532 TestDelegate request_delegate;
5533 AsyncLoggingNetworkDelegate network_delegate;
5534 TestURLRequestContext context(true);
5535 context.set_network_delegate(&network_delegate);
5536 context.set_net_log(&net_log_);
5537 context.Init();
5538
5539 {
rhalavatib7bd7c792017-04-27 05:25:165540 std::unique_ptr<URLRequest> r(context.CreateRequest(
5541 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY,
5542 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195543 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515544 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085545 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515546
[email protected]f7022f32014-08-21 16:32:195547 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515548 base::RunLoop().Run();
5549
[email protected]f7022f32014-08-21 16:32:195550 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505551 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515552 EXPECT_EQ(1, network_delegate.created_requests());
5553 EXPECT_EQ(0, network_delegate.destroyed_requests());
5554 }
5555 EXPECT_EQ(1, network_delegate.destroyed_requests());
5556
5557 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465558 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515559 net_log_.GetEntries(&entries);
5560 for (size_t i = 0; i < 3; ++i) {
5561 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005562 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5563 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515564
5565 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5566 log_position + 1);
5567
5568 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005569 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5570 entries[log_position].type);
5571 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515572 }
5573
mikecirone8b85c432016-09-08 19:11:005574 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5575 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515576}
5577
5578// Tests handling of delegate info from a network delegate in the case of an
5579// HTTP redirect.
5580TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555581 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515582
5583 TestDelegate request_delegate;
5584 AsyncLoggingNetworkDelegate network_delegate;
5585 TestURLRequestContext context(true);
5586 context.set_network_delegate(&network_delegate);
5587 context.set_net_log(&net_log_);
5588 context.Init();
5589
5590 {
danakj8522a25b2016-04-16 00:17:365591 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555592 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165593 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195594 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515595 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085596 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515597
[email protected]f7022f32014-08-21 16:32:195598 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515599 base::RunLoop().Run();
5600
[email protected]f7022f32014-08-21 16:32:195601 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505602 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515603 EXPECT_EQ(2, network_delegate.created_requests());
5604 EXPECT_EQ(0, network_delegate.destroyed_requests());
5605 }
5606 EXPECT_EQ(1, network_delegate.destroyed_requests());
5607
5608 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465609 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515610 net_log_.GetEntries(&entries);
5611 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005612 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515613 for (size_t i = 0; i < 3; ++i) {
5614 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005615 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5616 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515617
5618 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5619 log_position + 1);
5620
5621 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005622 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5623 entries[log_position].type);
5624 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515625 }
5626
5627 // The URLRequest::Delegate then gets informed about the redirect.
5628 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005629 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5630 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515631
5632 // The NetworkDelegate logged information in the same three events as before.
5633 for (size_t i = 0; i < 3; ++i) {
5634 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005635 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5636 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515637
5638 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5639 log_position + 1);
5640
5641 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005642 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5643 entries[log_position].type);
5644 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515645 }
5646
mikecirone8b85c432016-09-08 19:11:005647 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5648 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515649}
5650
5651// Tests handling of delegate info from a network delegate in the case of HTTP
5652// AUTH.
5653TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555654 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515655
5656 TestDelegate request_delegate;
5657 AsyncLoggingNetworkDelegate network_delegate;
5658 TestURLRequestContext context(true);
5659 context.set_network_delegate(&network_delegate);
5660 context.set_net_log(&net_log_);
5661 context.Init();
5662
5663 {
rhalavatib7bd7c792017-04-27 05:25:165664 std::unique_ptr<URLRequest> r(context.CreateRequest(
5665 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY,
5666 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195667 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515668 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085669 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515670
[email protected]f7022f32014-08-21 16:32:195671 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515672 base::RunLoop().Run();
5673
[email protected]f7022f32014-08-21 16:32:195674 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505675 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515676 EXPECT_EQ(1, network_delegate.created_requests());
5677 EXPECT_EQ(0, network_delegate.destroyed_requests());
5678 }
5679 EXPECT_EQ(1, network_delegate.destroyed_requests());
5680
5681 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465682 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515683 net_log_.GetEntries(&entries);
5684 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005685 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5686 // in
5687 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515688 for (size_t i = 0; i < 6; ++i) {
5689 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005690 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5691 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515692
5693 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5694 log_position + 1);
5695
5696 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005697 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5698 entries[log_position].type);
5699 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515700 }
5701
mikecirone8b85c432016-09-08 19:11:005702 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5703 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515704}
5705
tommycli59a63432015-11-06 00:10:555706// TODO(svaldez): Update tests to use EmbeddedTestServer.
5707#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515708// Tests handling of delegate info from a URLRequest::Delegate.
5709TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555710 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
tommycli59a63432015-11-06 00:10:555711 base::FilePath(kTestFilePath));
5712
5713 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515714
5715 AsyncLoggingUrlRequestDelegate request_delegate(
5716 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5717 TestURLRequestContext context(true);
5718 context.set_network_delegate(NULL);
5719 context.set_net_log(&net_log_);
5720 context.Init();
5721
5722 {
5723 // A chunked response with delays between chunks is used to make sure that
5724 // attempts by the URLRequest delegate to log information while reading the
5725 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485726 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515727 // that it occurs.
danakj8522a25b2016-04-16 00:17:365728 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555729 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:165730 &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195731 LoadStateWithParam load_state = r->GetLoadState();
5732 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515733 base::RunLoop().Run();
5734
[email protected]f7022f32014-08-21 16:32:195735 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505736 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515737 }
5738
mmenke43758e62015-05-04 21:09:465739 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515740 net_log_.GetEntries(&entries);
5741
[email protected]1826a402014-01-08 15:40:485742 size_t log_position = 0;
5743
[email protected]abe1c4a2013-10-25 19:28:515744 // The delegate info should only have been logged on header complete. Other
5745 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005746 log_position = ExpectLogContainsSomewhereAfter(
5747 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5748 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515749
5750 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5751 log_position + 1);
5752
5753 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005754 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5755 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515756
mikecirone8b85c432016-09-08 19:11:005757 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5758 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515759 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005760 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515761}
tommycli59a63432015-11-06 00:10:555762#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515763
5764// Tests handling of delegate info from a URLRequest::Delegate in the case of
5765// an HTTP redirect.
5766TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555767 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515768
5769 AsyncLoggingUrlRequestDelegate request_delegate(
5770 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5771 TestURLRequestContext context(true);
5772 context.set_network_delegate(NULL);
5773 context.set_net_log(&net_log_);
5774 context.Init();
5775
5776 {
danakj8522a25b2016-04-16 00:17:365777 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555778 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165779 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195780 LoadStateWithParam load_state = r->GetLoadState();
5781 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515782 base::RunLoop().Run();
5783
[email protected]f7022f32014-08-21 16:32:195784 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505785 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515786 }
5787
mmenke43758e62015-05-04 21:09:465788 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515789 net_log_.GetEntries(&entries);
5790
5791 // Delegate info should only have been logged in OnReceivedRedirect and
5792 // OnResponseStarted.
5793 size_t log_position = 0;
5794 for (int i = 0; i < 2; ++i) {
5795 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005796 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5797 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515798
5799 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5800 log_position + 1);
5801
5802 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005803 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5804 entries[log_position].type);
5805 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515806 }
5807
mikecirone8b85c432016-09-08 19:11:005808 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5809 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515810 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005811 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515812}
5813
5814// Tests handling of delegate info from a URLRequest::Delegate in the case of
5815// an HTTP redirect, with cancellation at various points.
5816TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555817 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515818
5819 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5820 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5821 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5822 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5823 };
5824
5825 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5826 ++test_case) {
5827 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:515828 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:045829 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:515830 context.set_network_delegate(NULL);
5831 context.set_net_log(&net_log);
5832 context.Init();
5833
5834 {
danakj8522a25b2016-04-16 00:17:365835 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555836 http_test_server()->GetURL("/server-redirect?simple.html"),
rhalavatib7bd7c792017-04-27 05:25:165837 DEFAULT_PRIORITY, &request_delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195838 LoadStateWithParam load_state = r->GetLoadState();
5839 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515840 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505841 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515842 }
5843
mmenke43758e62015-05-04 21:09:465844 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515845 net_log.GetEntries(&entries);
5846
5847 // Delegate info is always logged in both OnReceivedRedirect and
5848 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5849 // OnResponseStarted delegate call is after cancellation, but logging is
5850 // still currently supported in that call.
5851 size_t log_position = 0;
5852 for (int i = 0; i < 2; ++i) {
5853 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005854 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5855 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515856
5857 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5858 log_position + 1);
5859
5860 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005861 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5862 entries[log_position].type);
5863 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515864 }
5865
mikecirone8b85c432016-09-08 19:11:005866 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5867 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515868 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005869 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515870 }
5871}
5872
[email protected]847c0fa92012-11-06 16:37:425873namespace {
5874
5875const char kExtraHeader[] = "Allow-Snafu";
5876const char kExtraValue[] = "fubar";
5877
5878class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205879 void OnReceivedRedirect(URLRequest* request,
5880 const RedirectInfo& redirect_info,
5881 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595882 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425883 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5884 }
5885};
5886
5887} // namespace
5888
5889TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555890 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425891
tommycli59a63432015-11-06 00:10:555892 GURL destination_url =
5893 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5894 GURL original_url =
5895 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425896 RedirectWithAdditionalHeadersDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165897 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5898 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195899 req->Start();
[email protected]255620da2013-08-19 13:14:295900 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425901
5902 std::string value;
[email protected]f7022f32014-08-21 16:32:195903 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425904 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5905 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195906 EXPECT_FALSE(req->is_pending());
5907 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425908 EXPECT_EQ(kExtraValue, d.data_received());
5909}
5910
[email protected]251a1b92012-11-13 11:01:095911namespace {
5912
5913const char kExtraHeaderToRemove[] = "To-Be-Removed";
5914
5915class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205916 void OnReceivedRedirect(URLRequest* request,
5917 const RedirectInfo& redirect_info,
5918 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595919 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095920 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5921 }
5922};
5923
5924} // namespace
5925
5926TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555927 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095928
tommycli59a63432015-11-06 00:10:555929 GURL destination_url = http_test_server()->GetURL(
5930 "/echoheader?" + std::string(kExtraHeaderToRemove));
5931 GURL original_url =
5932 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095933 RedirectWithHeaderRemovalDelegate d;
rhalavatib7bd7c792017-04-27 05:25:165934 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
5935 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:195936 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5937 req->Start();
[email protected]255620da2013-08-19 13:14:295938 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095939
5940 std::string value;
[email protected]f7022f32014-08-21 16:32:195941 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095942 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195943 EXPECT_FALSE(req->is_pending());
5944 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095945 EXPECT_EQ("None", d.data_received());
5946}
5947
mmenke94f1bd92016-12-07 21:13:055948TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:445949 TestDelegate d;
5950 {
danakj8522a25b2016-04-16 00:17:365951 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165952 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d,
5953 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445954
[email protected]f7022f32014-08-21 16:32:195955 r->Start();
5956 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445957
[email protected]f7022f32014-08-21 16:32:195958 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445959
[email protected]255620da2013-08-19 13:14:295960 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445961
5962 // We expect to receive OnResponseStarted even though the request has been
5963 // cancelled.
5964 EXPECT_EQ(1, d.response_started_count());
5965 EXPECT_EQ(0, d.bytes_received());
5966 EXPECT_FALSE(d.received_data_before_response());
5967 }
5968}
5969
mmenke94f1bd92016-12-07 21:13:055970TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:555971 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445972
5973 TestDelegate d;
5974 {
danakj8522a25b2016-04-16 00:17:365975 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165976 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
5977 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:445978
5979 d.set_cancel_in_response_started(true);
5980
[email protected]f7022f32014-08-21 16:32:195981 r->Start();
5982 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445983
[email protected]255620da2013-08-19 13:14:295984 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445985
5986 EXPECT_EQ(1, d.response_started_count());
5987 EXPECT_EQ(0, d.bytes_received());
5988 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505989 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445990 }
5991}
5992
mmenke94f1bd92016-12-07 21:13:055993TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:555994 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445995
5996 TestDelegate d;
5997 {
danakj8522a25b2016-04-16 00:17:365998 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:165999 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
6000 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke94f1bd92016-12-07 21:13:056001
6002 d.set_cancel_in_received_data(true);
6003
6004 r->Start();
6005 EXPECT_TRUE(r->is_pending());
6006
6007 base::RunLoop().Run();
6008
6009 EXPECT_EQ(1, d.response_started_count());
6010 EXPECT_NE(0, d.received_bytes_count());
6011 EXPECT_FALSE(d.received_data_before_response());
6012 EXPECT_EQ(ERR_ABORTED, d.request_status());
6013 }
6014}
6015
6016TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
6017 ASSERT_TRUE(http_test_server()->Start());
6018
6019 TestDelegate d;
6020 {
6021 // This returns an empty response (With headers).
6022 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166023 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6024 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446025
6026 d.set_cancel_in_received_data(true);
6027
[email protected]f7022f32014-08-21 16:32:196028 r->Start();
6029 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446030
[email protected]255620da2013-08-19 13:14:296031 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446032
6033 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:056034 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:446035 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506036 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446037 }
6038}
6039
mmenke94f1bd92016-12-07 21:13:056040TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:556041 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446042
6043 TestDelegate d;
6044 {
danakj8522a25b2016-04-16 00:17:366045 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166046 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
6047 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:446048
[email protected]f7022f32014-08-21 16:32:196049 r->Start();
6050 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446051
6052 // The request will be implicitly canceled when it is destroyed. The
6053 // test delegate must not post a quit message when this happens because
6054 // this test doesn't actually have a message loop. The quit message would
6055 // get put on this thread's message queue and the next test would exit
6056 // early, causing problems.
6057 d.set_quit_on_complete(false);
6058 }
6059 // expect things to just cleanup properly.
6060
kimwjdalsl2bb4ff02015-12-16 22:06:026061 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:446062 // message loop
6063 EXPECT_FALSE(d.received_data_before_response());
6064 EXPECT_EQ(0, d.bytes_received());
6065}
6066
mmenke94f1bd92016-12-07 21:13:056067TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:556068 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446069
6070 // populate cache
6071 {
6072 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366073 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166074 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6075 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196076 r->Start();
[email protected]255620da2013-08-19 13:14:296077 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506078 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446079 }
6080
6081 // cancel read from cache (see bug 990242)
6082 {
6083 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366084 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166085 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
6086 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196087 r->Start();
6088 r->Cancel();
[email protected]255620da2013-08-19 13:14:296089 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446090
maksim.sisovb53724b52016-09-16 05:30:506091 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446092 EXPECT_EQ(1, d.response_started_count());
6093 EXPECT_EQ(0, d.bytes_received());
6094 EXPECT_FALSE(d.received_data_before_response());
6095 }
6096}
6097
6098TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:556099 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446100 HTTPUploadDataOperationTest("POST");
6101}
6102
6103TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:556104 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446105 HTTPUploadDataOperationTest("PUT");
6106}
6107
6108TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:556109 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446110
6111 TestDelegate d;
6112 {
danakj8522a25b2016-04-16 00:17:366113 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166114 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6115 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196116 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446117
[email protected]f7022f32014-08-21 16:32:196118 r->Start();
6119 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446120
[email protected]255620da2013-08-19 13:14:296121 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446122
maksim.sisovb53724b52016-09-16 05:30:506123 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6124 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446125
6126 EXPECT_FALSE(d.received_data_before_response());
6127 EXPECT_TRUE(d.data_received().empty());
6128 }
6129}
6130
6131TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:556132 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446133
6134 TestDelegate d;
6135 {
danakj8522a25b2016-04-16 00:17:366136 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166137 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6138 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196139 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:446140
[email protected]6cdfd7f2013-02-08 20:40:156141 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:446142 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:026143 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:446144
danakj8522a25b2016-04-16 00:17:366145 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:446146
[email protected]6cdfd7f2013-02-08 20:40:156147 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446148 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476149 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446150 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
Jeremy Roman0579ed62017-08-29 15:56:196151 element_readers.push_back(std::make_unique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:146152 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:076153 std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046154 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6155 std::move(element_readers), 0));
[email protected]316c1e5e2012-09-12 15:17:446156
[email protected]f7022f32014-08-21 16:32:196157 r->Start();
6158 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446159
[email protected]255620da2013-08-19 13:14:296160 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446161
avibf0746c2015-12-09 19:53:146162 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:296163 ASSERT_EQ(true, base::GetFileSize(path, &size64));
6164 ASSERT_LE(size64, std::numeric_limits<int>::max());
6165 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:366166 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:446167
[email protected]7600d0b2013-12-08 21:43:306168 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:446169
maksim.sisovb53724b52016-09-16 05:30:506170 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
6171 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:446172
6173 EXPECT_FALSE(d.received_data_before_response());
6174
[email protected]329b68b2012-11-14 17:54:276175 EXPECT_EQ(size, d.bytes_received());
6176 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446177 }
6178}
6179
[email protected]999dd8c2013-11-12 06:45:546180TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:556181 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:546182
6183 TestDelegate d;
6184 {
danakj8522a25b2016-04-16 00:17:366185 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166186 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6187 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196188 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:546189
danakj8522a25b2016-04-16 00:17:366190 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:546191
Jeremy Roman0579ed62017-08-29 15:56:196192 element_readers.push_back(std::make_unique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:456193 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:546194 base::FilePath(FILE_PATH_LITERAL(
6195 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:076196 0, std::numeric_limits<uint64_t>::max(), base::Time()));
Bence Béky8f9d7d3952017-10-09 19:58:046197 r->set_upload(std::make_unique<ElementsUploadDataStream>(
6198 std::move(element_readers), 0));
[email protected]999dd8c2013-11-12 06:45:546199
[email protected]f7022f32014-08-21 16:32:196200 r->Start();
6201 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:546202
6203 base::RunLoop().Run();
6204
[email protected]999dd8c2013-11-12 06:45:546205 EXPECT_TRUE(d.request_failed());
6206 EXPECT_FALSE(d.received_data_before_response());
6207 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:506208 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:546209 }
6210}
6211
mmenke56b0cbb912016-03-28 21:34:536212namespace {
6213
6214// Adds a standard set of data to an upload for chunked upload integration
6215// tests.
6216void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
6217 writer->AppendData("a", 1, false);
6218 writer->AppendData("bcd", 3, false);
6219 writer->AppendData("this is a longer chunk than before.", 35, false);
6220 writer->AppendData("\r\n\r\n", 4, false);
6221 writer->AppendData("0", 1, false);
6222 writer->AppendData("2323", 4, true);
6223}
6224
6225// Checks that the upload data added in AddChunksToUpload() was echoed back from
6226// the server.
6227void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
6228 // This should match the chunks sent by AddChunksToUpload().
6229 const std::string expected_data =
6230 "abcdthis is a longer chunk than before.\r\n\r\n02323";
6231
maksim.sisovb53724b52016-09-16 05:30:506232 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
6233 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:536234
6235 EXPECT_FALSE(d->received_data_before_response());
6236
6237 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
6238 EXPECT_EQ(expected_data, d->data_received());
6239}
6240
6241} // namespace
6242
[email protected]316c1e5e2012-09-12 15:17:446243TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:556244 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446245
6246 TestDelegate d;
6247 {
danakj8522a25b2016-04-16 00:17:366248 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166249 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6250 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366251 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536252 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366253 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536254 upload_data_stream->CreateWriter();
6255 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196256 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:536257 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:196258 r->Start();
6259 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446260
[email protected]255620da2013-08-19 13:14:296261 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446262
[email protected]f7022f32014-08-21 16:32:196263 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446264 }
6265}
6266
[email protected]329b68b2012-11-14 17:54:276267TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:556268 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:276269
6270 TestDelegate d;
6271 {
danakj8522a25b2016-04-16 00:17:366272 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166273 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6274 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366275 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536276 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366277 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536278 upload_data_stream->CreateWriter();
Bence Béky8f9d7d3952017-10-09 19:58:046279 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196280 r->set_method("POST");
6281 r->Start();
6282 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:536283 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296284 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:276285
[email protected]f7022f32014-08-21 16:32:196286 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:276287 }
6288}
6289
[email protected]316c1e5e2012-09-12 15:17:446290TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:556291 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446292
6293 TestDelegate d;
6294 {
danakj8522a25b2016-04-16 00:17:366295 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166296 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d,
6297 TRAFFIC_ANNOTATION_FOR_TESTS));
danakj8522a25b2016-04-16 00:17:366298 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:536299 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:366300 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:536301 upload_data_stream->CreateWriter();
6302 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:196303 r->set_method("POST");
6304 r->Start();
6305 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:446306
[email protected]255620da2013-08-19 13:14:296307 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:536308 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:296309 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446310
[email protected]f7022f32014-08-21 16:32:196311 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:446312 }
6313}
6314
6315TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:556316 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446317
6318 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366319 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166320 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d,
6321 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196322 req->Start();
[email protected]255620da2013-08-19 13:14:296323 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446324
[email protected]f7022f32014-08-21 16:32:196325 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:446326
6327 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:196328 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:446329
6330 std::string header;
6331 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
6332 EXPECT_EQ("private", header);
6333
6334 header.clear();
6335 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
6336 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
6337
6338 // The response has two "X-Multiple-Entries" headers.
6339 // This verfies our output has them concatenated together.
6340 header.clear();
6341 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
6342 EXPECT_EQ("a, b", header);
6343}
6344
tommycli59a63432015-11-06 00:10:556345// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
6346// security state. (see http://crbug.com/550977).
6347#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:466348TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:556349 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6350 https_test_server.SetSSLConfig(
6351 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6352 https_test_server.ServeFilesFromSourceDirectory(
6353 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466354 ASSERT_TRUE(https_test_server.Start());
6355
tommycli59a63432015-11-06 00:10:556356 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:466357 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366358 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166359 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6360 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196361 request->Start();
[email protected]255620da2013-08-19 13:14:296362 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466363
6364 TransportSecurityState* security_state =
6365 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406366 TransportSecurityState::STSState sts_state;
6367 TransportSecurityState::PKPState pkp_state;
6368 EXPECT_TRUE(
6369 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6370 EXPECT_FALSE(
6371 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6372 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6373 sts_state.upgrade_mode);
6374 EXPECT_TRUE(sts_state.include_subdomains);
6375 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:036376#if defined(OS_ANDROID)
6377 // Android's CertVerifyProc does not (yet) handle pins.
6378#else
martijnc0d6b622015-06-30 19:14:406379 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036380#endif
[email protected]37fd55fb2013-06-29 13:13:276381}
6382
estarka5da76702015-04-09 04:00:166383TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556384 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6385 https_test_server.ServeFilesFromSourceDirectory(
6386 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166387 ASSERT_TRUE(https_test_server.Start());
6388 // Make sure this test fails if the test server is changed to not
6389 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556390 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6391 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166392
6393 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366394 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166395 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d,
6396 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166397 request->Start();
6398 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166399 TransportSecurityState* security_state =
6400 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406401 TransportSecurityState::STSState sts_state;
6402 EXPECT_FALSE(
6403 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166404}
6405
estark06e0dac2015-08-07 21:56:016406namespace {
Martijn Croonenb1383da2017-10-11 11:56:356407const char kExpectCTStaticHostname[] = "expect-ct.preloaded.test";
6408const char kExpectStapleStaticHostname[] = "expect-staple.preloaded.test";
6409const char kExpectStapleReportURI[] =
6410 "http://report-uri.preloaded.test/expect-staple";
estark06e0dac2015-08-07 21:56:016411const char kHPKPReportUri[] = "https://hpkp-report.test";
6412} // namespace
6413
[email protected]37fd55fb2013-06-29 13:13:276414// Tests that enabling HPKP on a domain does not affect the HSTS
6415// validity/expiration.
dadrian2faf2062016-07-16 00:03:176416TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016417 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556418 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6419 https_test_server.SetSSLConfig(
6420 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6421 https_test_server.ServeFilesFromSourceDirectory(
6422 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276423 ASSERT_TRUE(https_test_server.Start());
6424
tommycli59a63432015-11-06 00:10:556425 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166426
[email protected]37fd55fb2013-06-29 13:13:276427 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366428 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166429 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6430 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196431 request->Start();
[email protected]255620da2013-08-19 13:14:296432 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276433 TransportSecurityState* security_state =
6434 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406435 TransportSecurityState::STSState sts_state;
6436 TransportSecurityState::PKPState pkp_state;
6437 EXPECT_FALSE(
6438 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6439 EXPECT_TRUE(
6440 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6441 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6442 sts_state.upgrade_mode);
6443 EXPECT_FALSE(sts_state.include_subdomains);
6444 EXPECT_FALSE(pkp_state.include_subdomains);
6445 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016446 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406447 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466448}
6449
estark06e0dac2015-08-07 21:56:016450// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176451TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016452 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556453 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6454 https_test_server.SetSSLConfig(
6455 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6456 https_test_server.ServeFilesFromSourceDirectory(
6457 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016458 ASSERT_TRUE(https_test_server.Start());
6459
tommycli59a63432015-11-06 00:10:556460 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016461
6462 // Set up a pin for |test_server_hostname|.
6463 TransportSecurityState security_state;
6464 const base::Time current_time(base::Time::Now());
6465 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6466 HashValueVector hashes;
6467 HashValue hash1;
6468 HashValue hash2;
6469 // The values here don't matter, as long as they are different from
6470 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446471 ASSERT_TRUE(
6472 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6473 ASSERT_TRUE(
6474 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016475 hashes.push_back(hash1);
6476 hashes.push_back(hash2);
6477 security_state.AddHPKP(test_server_hostname, expiry,
6478 false, /* include subdomains */
6479 hashes, report_uri);
6480
6481 MockCertificateReportSender mock_report_sender;
6482 security_state.SetReportSender(&mock_report_sender);
6483
6484 // Set up a MockCertVerifier to trigger a violation of the previously
6485 // set pin.
6486 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6487 ASSERT_TRUE(cert);
6488
6489 MockCertVerifier cert_verifier;
6490 CertVerifyResult verify_result;
6491 verify_result.verified_cert = cert;
6492 verify_result.is_issued_by_known_root = true;
6493 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446494 ASSERT_TRUE(
6495 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016496 verify_result.public_key_hashes.push_back(hash3);
6497 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6498
6499 TestNetworkDelegate network_delegate;
6500 TestURLRequestContext context(true);
6501 context.set_transport_security_state(&security_state);
6502 context.set_network_delegate(&network_delegate);
6503 context.set_cert_verifier(&cert_verifier);
6504 context.Init();
6505
6506 // Now send a request to trigger the violation.
6507 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366508 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166509 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
6510 TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016511 violating_request->Start();
6512 base::RunLoop().Run();
6513
6514 // Check that a report was sent.
6515 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6516 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446517 EXPECT_EQ("application/json; charset=utf-8",
6518 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366519 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016520 base::JSONReader::Read(mock_report_sender.latest_report()));
6521 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086522 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016523 base::DictionaryValue* report_dict;
6524 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6525 std::string report_hostname;
6526 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6527 EXPECT_EQ(test_server_hostname, report_hostname);
6528}
6529
6530// Tests that reports get sent on requests with
6531// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176532TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016533 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556534 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6535 https_test_server.SetSSLConfig(
6536 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6537 https_test_server.ServeFilesFromSourceDirectory(
6538 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016539 ASSERT_TRUE(https_test_server.Start());
6540
tommycli59a63432015-11-06 00:10:556541 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016542
6543 TransportSecurityState security_state;
6544 MockCertificateReportSender mock_report_sender;
6545 security_state.SetReportSender(&mock_report_sender);
6546
6547 // Set up a MockCertVerifier to violate the pin in the Report-Only
6548 // header.
6549 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6550 ASSERT_TRUE(cert);
6551
6552 MockCertVerifier cert_verifier;
6553 CertVerifyResult verify_result;
6554 verify_result.verified_cert = cert;
6555 verify_result.is_issued_by_known_root = true;
6556 HashValue hash;
6557 // This value doesn't matter, as long as it is different from the pins
6558 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446559 ASSERT_TRUE(
6560 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016561 verify_result.public_key_hashes.push_back(hash);
6562 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6563
6564 TestNetworkDelegate network_delegate;
6565 TestURLRequestContext context(true);
6566 context.set_transport_security_state(&security_state);
6567 context.set_network_delegate(&network_delegate);
6568 context.set_cert_verifier(&cert_verifier);
6569 context.Init();
6570
6571 // Now send a request to trigger the violation.
6572 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366573 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556574 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166575 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016576 violating_request->Start();
6577 base::RunLoop().Run();
6578
6579 // Check that a report was sent.
6580 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6581 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446582 EXPECT_EQ("application/json; charset=utf-8",
6583 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366584 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016585 base::JSONReader::Read(mock_report_sender.latest_report()));
6586 ASSERT_TRUE(value);
jdoerriee48b26a2017-12-09 14:19:086587 ASSERT_TRUE(value->is_dict());
estark06e0dac2015-08-07 21:56:016588 base::DictionaryValue* report_dict;
6589 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6590 std::string report_hostname;
6591 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6592 EXPECT_EQ(test_server_hostname, report_hostname);
6593}
6594
6595// Tests that reports do not get sent on requests with
6596// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176597TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016598 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556599 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6600 https_test_server.SetSSLConfig(
6601 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6602 https_test_server.ServeFilesFromSourceDirectory(
6603 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016604 ASSERT_TRUE(https_test_server.Start());
6605
tommycli59a63432015-11-06 00:10:556606 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016607
6608 TransportSecurityState security_state;
6609 MockCertificateReportSender mock_report_sender;
6610 security_state.SetReportSender(&mock_report_sender);
6611
6612 TestNetworkDelegate network_delegate;
6613 MockCertVerifier mock_cert_verifier;
6614 TestURLRequestContext context(true);
6615 context.set_transport_security_state(&security_state);
6616 context.set_network_delegate(&network_delegate);
6617 context.set_cert_verifier(&mock_cert_verifier);
6618 mock_cert_verifier.set_default_result(OK);
6619 context.Init();
6620
6621 // Now send a request that does not trigger the violation.
6622 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366623 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556624 https_test_server.GetURL("/hpkp-headers-report-only.html"),
rhalavatib7bd7c792017-04-27 05:25:166625 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark06e0dac2015-08-07 21:56:016626 request->Start();
6627 base::RunLoop().Run();
6628
6629 // Check that a report was not sent.
6630 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6631 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6632}
6633
estarka5da76702015-04-09 04:00:166634TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556635 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6636 https_test_server.ServeFilesFromSourceDirectory(
6637 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166638 ASSERT_TRUE(https_test_server.Start());
6639 // Make sure this test fails if the test server is changed to not
6640 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556641 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6642 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166643
6644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366645 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166646 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6647 TRAFFIC_ANNOTATION_FOR_TESTS));
estarka5da76702015-04-09 04:00:166648 request->Start();
6649 base::RunLoop().Run();
6650
6651 TransportSecurityState* security_state =
6652 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406653 TransportSecurityState::PKPState pkp_state;
6654 EXPECT_FALSE(
6655 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166656}
6657
dadriandf302c42016-06-10 18:48:596658TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6659 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6660 https_test_server.SetSSLConfig(
6661 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6662 https_test_server.ServeFilesFromSourceDirectory(
6663 base::FilePath(kTestFilePath));
6664 ASSERT_TRUE(https_test_server.Start());
6665
6666 // Set up a MockCertVerifier to be a local root that violates the pin
6667 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6668 ASSERT_TRUE(cert);
6669
6670 MockCertVerifier cert_verifier;
6671 CertVerifyResult verify_result;
6672 verify_result.verified_cert = cert;
6673 verify_result.is_issued_by_known_root = false;
6674 HashValue hash;
6675 ASSERT_TRUE(
6676 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6677 verify_result.public_key_hashes.push_back(hash);
6678 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6679 cert_verifier.set_default_result(OK);
6680
6681 std::string test_server_hostname = https_test_server.GetURL("/").host();
6682
6683 // Set up HPKP
6684 base::Time current_time = base::Time::Now();
6685 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6686 HashValue pin;
6687 ASSERT_TRUE(
6688 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6689 HashValueVector hashes;
6690 hashes.push_back(pin);
6691 GURL report_uri(kHPKPReportUri);
6692 TransportSecurityState security_state;
6693 security_state.AddHPKP(test_server_hostname, expiry,
6694 false, /* include subdomains */
6695 hashes, report_uri);
6696
6697 TestNetworkDelegate network_delegate;
6698 TestURLRequestContext context(true);
6699 context.set_transport_security_state(&security_state);
6700 context.set_network_delegate(&network_delegate);
6701 context.set_cert_verifier(&cert_verifier);
6702 context.Init();
6703
6704 TestDelegate d;
6705 std::unique_ptr<URLRequest> request(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:166706 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
6707 TRAFFIC_ANNOTATION_FOR_TESTS));
dadriandf302c42016-06-10 18:48:596708 request->Start();
6709 base::RunLoop().Run();
6710
6711 TransportSecurityState::PKPState pkp_state;
6712 EXPECT_TRUE(
6713 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6714 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6715}
6716
[email protected]242d8562012-10-30 21:20:466717TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556718 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6719 https_test_server.SetSSLConfig(
6720 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6721 https_test_server.ServeFilesFromSourceDirectory(
6722 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466723 ASSERT_TRUE(https_test_server.Start());
6724
tommycli59a63432015-11-06 00:10:556725 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166726
[email protected]242d8562012-10-30 21:20:466727 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366728 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556729 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166730 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196731 request->Start();
[email protected]255620da2013-08-19 13:14:296732 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466733
6734 // We should have set parameters from the first header, not the second.
6735 TransportSecurityState* security_state =
6736 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406737 TransportSecurityState::STSState sts_state;
6738 EXPECT_TRUE(
6739 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6740 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6741 sts_state.upgrade_mode);
6742 EXPECT_FALSE(sts_state.include_subdomains);
6743 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466744}
6745
[email protected]9f972ec2013-04-10 20:24:366746TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556747 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6748 https_test_server.SetSSLConfig(
6749 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6750 https_test_server.ServeFilesFromSourceDirectory(
6751 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366752 ASSERT_TRUE(https_test_server.Start());
6753
tommycli59a63432015-11-06 00:10:556754 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166755
[email protected]9f972ec2013-04-10 20:24:366756 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366757 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556758 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:166759 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196760 request->Start();
[email protected]255620da2013-08-19 13:14:296761 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366762
6763 // We should have set parameters from the first header, not the second.
6764 TransportSecurityState* security_state =
6765 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406766 TransportSecurityState::STSState sts_state;
6767 TransportSecurityState::PKPState pkp_state;
6768 EXPECT_TRUE(
6769 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6770 EXPECT_TRUE(
6771 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6772 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6773 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036774#if defined(OS_ANDROID)
6775 // Android's CertVerifyProc does not (yet) handle pins.
6776#else
martijnc0d6b622015-06-30 19:14:406777 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036778#endif
martijnc0d6b622015-06-30 19:14:406779 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366780
[email protected]a165f092013-06-12 16:10:056781 // Even though there is an HSTS header asserting includeSubdomains, it is
6782 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406783 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056784 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406785 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366786}
6787
[email protected]37fd55fb2013-06-29 13:13:276788// Tests that when multiple HPKP headers are present, asserting different
6789// policies, that only the first such policy is processed.
6790TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556791 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6792 https_test_server.SetSSLConfig(
6793 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6794 https_test_server.ServeFilesFromSourceDirectory(
6795 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276796 ASSERT_TRUE(https_test_server.Start());
6797
tommycli59a63432015-11-06 00:10:556798 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166799
[email protected]37fd55fb2013-06-29 13:13:276800 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366801 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556802 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
rhalavatib7bd7c792017-04-27 05:25:166803 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:196804 request->Start();
[email protected]255620da2013-08-19 13:14:296805 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276806
6807 TransportSecurityState* security_state =
6808 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406809 TransportSecurityState::STSState sts_state;
6810 TransportSecurityState::PKPState pkp_state;
6811 EXPECT_TRUE(
6812 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6813 EXPECT_TRUE(
6814 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6815 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6816 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036817#if defined(OS_ANDROID)
6818 // Android's CertVerifyProc does not (yet) handle pins.
6819#else
martijnc0d6b622015-06-30 19:14:406820 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036821#endif
martijnc0d6b622015-06-30 19:14:406822 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276823
martijnc0d6b622015-06-30 19:14:406824 EXPECT_TRUE(sts_state.include_subdomains);
6825 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276826}
6827
estark1614475f2016-03-10 03:46:476828// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6829// called.
6830class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6831 public:
6832 MockExpectCTReporter() : num_failures_(0) {}
Chris Watkins7a41d3552017-12-01 02:13:276833 ~MockExpectCTReporter() override = default;
estark1614475f2016-03-10 03:46:476834
6835 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6836 const GURL& report_uri,
estarkae028b462017-06-20 23:25:016837 base::Time expiration,
estarkbf1b52962017-05-05 17:05:256838 const X509Certificate* validated_certificate_chain,
6839 const X509Certificate* served_certificate_chain,
6840 const SignedCertificateTimestampAndStatusList&
6841 signed_certificate_timestamps) override {
estark1614475f2016-03-10 03:46:476842 num_failures_++;
6843 }
6844
6845 uint32_t num_failures() { return num_failures_; }
6846
6847 private:
6848 uint32_t num_failures_;
6849};
6850
Emily Stark627238f2017-11-29 03:29:546851// A CTPolicyEnforcer that returns a default CTPolicyCompliance value
estark1614475f2016-03-10 03:46:476852// for every certificate.
6853class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6854 public:
6855 MockCTPolicyEnforcer()
Emily Stark627238f2017-11-29 03:29:546856 : default_result_(ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS) {}
Chris Watkins7a41d3552017-12-01 02:13:276857 ~MockCTPolicyEnforcer() override = default;
estark1614475f2016-03-10 03:46:476858
Emily Stark627238f2017-11-29 03:29:546859 ct::CTPolicyCompliance CheckCompliance(
estark1614475f2016-03-10 03:46:476860 X509Certificate* cert,
6861 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206862 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476863 return default_result_;
6864 }
6865
Emily Stark627238f2017-11-29 03:29:546866 void set_default_result(ct::CTPolicyCompliance default_result) {
estark1614475f2016-03-10 03:46:476867 default_result_ = default_result;
6868 }
6869
6870 private:
Emily Stark627238f2017-11-29 03:29:546871 ct::CTPolicyCompliance default_result_;
estark1614475f2016-03-10 03:46:476872};
6873
Emily Stark4cfecf072017-08-08 01:05:516874// Tests that Expect CT headers for the preload list are processed correctly.
6875TEST_F(URLRequestTestHTTP, PreloadExpectCTHeader) {
Martijn Croonenb1383da2017-10-11 11:56:356876 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
6877
estark1614475f2016-03-10 03:46:476878 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6879 https_test_server.SetSSLConfig(
6880 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6881 https_test_server.ServeFilesFromSourceDirectory(
6882 base::FilePath(kTestFilePath));
6883 ASSERT_TRUE(https_test_server.Start());
6884
6885 MockExpectCTReporter reporter;
6886 TransportSecurityState transport_security_state;
6887 transport_security_state.enable_static_expect_ct_ = true;
6888 transport_security_state.SetExpectCTReporter(&reporter);
6889
6890 // Set up a MockCertVerifier to accept the certificate that the server sends.
6891 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6892 ASSERT_TRUE(cert);
6893 MockCertVerifier cert_verifier;
6894 CertVerifyResult verify_result;
6895 verify_result.verified_cert = cert;
6896 verify_result.is_issued_by_known_root = true;
6897 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6898
rsleevi22cae1672016-12-28 01:53:366899 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6900 // CT violation.
6901 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476902 MockCTPolicyEnforcer ct_policy_enforcer;
6903 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546904 ct::CTPolicyCompliance::CT_POLICY_NOT_ENOUGH_SCTS);
estark1614475f2016-03-10 03:46:476905
6906 TestNetworkDelegate network_delegate;
6907 // Use a MockHostResolver (which by default maps all hosts to
6908 // 127.0.0.1) so that the request can be sent to a site on the Expect
6909 // CT preload list.
6910 MockHostResolver host_resolver;
6911 TestURLRequestContext context(true);
6912 context.set_host_resolver(&host_resolver);
6913 context.set_transport_security_state(&transport_security_state);
6914 context.set_network_delegate(&network_delegate);
6915 context.set_cert_verifier(&cert_verifier);
6916 context.set_cert_transparency_verifier(&ct_verifier);
vabr13d00742017-06-05 10:31:466917 context.set_ct_policy_enforcer(&ct_policy_enforcer);
estark1614475f2016-03-10 03:46:476918 context.Init();
6919
6920 // Now send a request to trigger the violation.
6921 TestDelegate d;
Emily Stark4cfecf072017-08-08 01:05:516922 GURL url = https_test_server.GetURL("/expect-ct-header-preload.html");
estark1614475f2016-03-10 03:46:476923 GURL::Replacements replace_host;
6924 replace_host.SetHostStr(kExpectCTStaticHostname);
6925 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:166926 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
6927 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark1614475f2016-03-10 03:46:476928 violating_request->Start();
6929 base::RunLoop().Run();
6930
6931 EXPECT_EQ(1u, reporter.num_failures());
6932}
Emily Stark4cfecf072017-08-08 01:05:516933
6934// Tests that Expect CT HTTP headers are processed correctly.
6935TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6936 base::test::ScopedFeatureList feature_list;
6937 feature_list.InitAndEnableFeature(
6938 TransportSecurityState::kDynamicExpectCTFeature);
6939
6940 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6941 https_test_server.SetSSLConfig(
6942 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6943 https_test_server.ServeFilesFromSourceDirectory(
6944 base::FilePath(kTestFilePath));
6945 ASSERT_TRUE(https_test_server.Start());
6946
6947 MockExpectCTReporter reporter;
6948 TransportSecurityState transport_security_state;
6949 transport_security_state.SetExpectCTReporter(&reporter);
6950
6951 // Set up a MockCertVerifier to accept the certificate that the server sends.
6952 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6953 ASSERT_TRUE(cert);
6954 MockCertVerifier cert_verifier;
6955 CertVerifyResult verify_result;
6956 verify_result.verified_cert = cert;
6957 verify_result.is_issued_by_known_root = true;
6958 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6959
6960 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
6961 // compliance.
6962 DoNothingCTVerifier ct_verifier;
6963 MockCTPolicyEnforcer ct_policy_enforcer;
6964 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:546965 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:516966
6967 TestNetworkDelegate network_delegate;
6968 // Use a MockHostResolver (which by default maps all hosts to
6969 // 127.0.0.1).
6970 MockHostResolver host_resolver;
6971 TestURLRequestContext context(true);
6972 context.set_host_resolver(&host_resolver);
6973 context.set_transport_security_state(&transport_security_state);
6974 context.set_network_delegate(&network_delegate);
6975 context.set_cert_verifier(&cert_verifier);
6976 context.set_cert_transparency_verifier(&ct_verifier);
6977 context.set_ct_policy_enforcer(&ct_policy_enforcer);
6978 context.Init();
6979
6980 // Now send a request to trigger the header processing.
6981 TestDelegate d;
6982 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6983 std::unique_ptr<URLRequest> request(context.CreateRequest(
6984 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
6985 request->Start();
6986 base::RunLoop().Run();
6987
6988 TransportSecurityState::ExpectCTState state;
6989 ASSERT_TRUE(
6990 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
6991 EXPECT_TRUE(state.enforce);
6992 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
6993}
6994
6995// Tests that if multiple Expect CT HTTP headers are sent, they are all
6996// processed.
6997TEST_F(URLRequestTestHTTP, MultipleExpectCTHeaders) {
6998 base::test::ScopedFeatureList feature_list;
6999 feature_list.InitAndEnableFeature(
7000 TransportSecurityState::kDynamicExpectCTFeature);
7001
7002 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7003 https_test_server.SetSSLConfig(
7004 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
7005 https_test_server.ServeFilesFromSourceDirectory(
7006 base::FilePath(kTestFilePath));
7007 ASSERT_TRUE(https_test_server.Start());
7008
7009 MockExpectCTReporter reporter;
7010 TransportSecurityState transport_security_state;
7011 transport_security_state.SetExpectCTReporter(&reporter);
7012
7013 // Set up a MockCertVerifier to accept the certificate that the server sends.
7014 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
7015 ASSERT_TRUE(cert);
7016 MockCertVerifier cert_verifier;
7017 CertVerifyResult verify_result;
7018 verify_result.verified_cert = cert;
7019 verify_result.is_issued_by_known_root = true;
7020 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
7021
7022 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to simulate CT
7023 // compliance.
7024 DoNothingCTVerifier ct_verifier;
7025 MockCTPolicyEnforcer ct_policy_enforcer;
7026 ct_policy_enforcer.set_default_result(
Emily Stark627238f2017-11-29 03:29:547027 ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS);
Emily Stark4cfecf072017-08-08 01:05:517028
7029 TestNetworkDelegate network_delegate;
7030 // Use a MockHostResolver (which by default maps all hosts to
7031 // 127.0.0.1).
7032 MockHostResolver host_resolver;
7033 TestURLRequestContext context(true);
7034 context.set_host_resolver(&host_resolver);
7035 context.set_transport_security_state(&transport_security_state);
7036 context.set_network_delegate(&network_delegate);
7037 context.set_cert_verifier(&cert_verifier);
7038 context.set_cert_transparency_verifier(&ct_verifier);
7039 context.set_ct_policy_enforcer(&ct_policy_enforcer);
7040 context.Init();
7041
7042 // Now send a request to trigger the header processing.
7043 TestDelegate d;
7044 GURL url = https_test_server.GetURL("/expect-ct-header-multiple.html");
7045 std::unique_ptr<URLRequest> request(context.CreateRequest(
7046 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7047 request->Start();
7048 base::RunLoop().Run();
7049
7050 TransportSecurityState::ExpectCTState state;
7051 ASSERT_TRUE(
7052 transport_security_state.GetDynamicExpectCTState(url.host(), &state));
7053 EXPECT_TRUE(state.enforce);
7054 EXPECT_EQ(GURL("https://example.test"), state.report_uri);
7055}
7056
mmenkefd9d15c2017-06-29 13:45:547057#endif // !defined(OS_IOS)
estark1614475f2016-03-10 03:46:477058
mmenkefd9d15c2017-06-29 13:45:547059#if BUILDFLAG(ENABLE_REPORTING)
juliatuttle2b8dd2d12017-04-12 21:27:417060namespace {
7061
7062class TestReportingService : public ReportingService {
7063 public:
7064 struct Header {
7065 GURL url;
7066 std::string header_value;
7067 };
7068
juliatuttle2b8dd2d12017-04-12 21:27:417069 const std::vector<Header>& headers() { return headers_; }
7070
juliatuttle1d92f0152017-04-28 17:19:217071 // ReportingService implementation:
7072
Chris Watkins7a41d3552017-12-01 02:13:277073 ~TestReportingService() override = default;
juliatuttle1d92f0152017-04-28 17:19:217074
juliatuttle2b8dd2d12017-04-12 21:27:417075 void QueueReport(const GURL& url,
7076 const std::string& group,
7077 const std::string& type,
Julia Tuttle107e30672018-03-29 18:48:427078 std::unique_ptr<const base::Value> body,
7079 int depth) override {
juliatuttle2b8dd2d12017-04-12 21:27:417080 NOTIMPLEMENTED();
7081 }
7082
7083 void ProcessHeader(const GURL& url,
7084 const std::string& header_value) override {
7085 headers_.push_back({url, header_value});
7086 }
7087
Julia Tuttle227a6ff2017-12-19 19:44:247088 void RemoveBrowsingData(int data_type_mask,
7089 const base::RepeatingCallback<bool(const GURL&)>&
7090 origin_filter) override {
juliatuttleaeb1abc2017-05-04 21:14:387091 NOTIMPLEMENTED();
7092 }
7093
Julia Tuttle107e30672018-03-29 18:48:427094 int GetUploadDepth(const URLRequest& request) override {
Julia Tuttle4667c1c2017-12-19 18:27:387095 NOTIMPLEMENTED();
Julia Tuttle107e30672018-03-29 18:48:427096 return 0;
Julia Tuttle4667c1c2017-12-19 18:27:387097 }
7098
Julia Tuttle91a655d2018-01-26 18:03:037099 const ReportingPolicy& GetPolicy() const override {
7100 static ReportingPolicy dummy_policy_;
7101 NOTIMPLEMENTED();
7102 return dummy_policy_;
7103 }
7104
juliatuttle2b8dd2d12017-04-12 21:27:417105 private:
7106 std::vector<Header> headers_;
7107};
7108
7109std::unique_ptr<test_server::HttpResponse> SendReportToHeader(
7110 const test_server::HttpRequest& request) {
7111 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7112 new test_server::BasicHttpResponse);
7113 http_response->set_code(HTTP_OK);
7114 http_response->AddCustomHeader("Report-To", "foo");
7115 http_response->AddCustomHeader("Report-To", "bar");
7116 return std::move(http_response);
7117}
7118
7119} // namespace
7120
7121TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderNoService) {
Julia Tuttle7005a2a2017-12-08 21:01:187122 http_test_server()->RegisterRequestHandler(
7123 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417124 ASSERT_TRUE(http_test_server()->Start());
7125 GURL request_url = http_test_server()->GetURL("/");
7126
7127 TestNetworkDelegate network_delegate;
7128 TestURLRequestContext context(true);
7129 context.set_network_delegate(&network_delegate);
7130 context.Init();
7131
7132 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167133 std::unique_ptr<URLRequest> request(context.CreateRequest(
7134 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417135 request->Start();
7136 base::RunLoop().Run();
7137}
7138
7139TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderHTTP) {
Julia Tuttle7005a2a2017-12-08 21:01:187140 http_test_server()->RegisterRequestHandler(
7141 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417142 ASSERT_TRUE(http_test_server()->Start());
7143 GURL request_url = http_test_server()->GetURL("/");
7144
7145 TestNetworkDelegate network_delegate;
7146 TestReportingService reporting_service;
7147 TestURLRequestContext context(true);
7148 context.set_network_delegate(&network_delegate);
7149 context.set_reporting_service(&reporting_service);
7150 context.Init();
7151
7152 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167153 std::unique_ptr<URLRequest> request(context.CreateRequest(
7154 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417155 request->Start();
7156 base::RunLoop().Run();
7157
7158 EXPECT_TRUE(reporting_service.headers().empty());
7159}
7160
7161TEST_F(URLRequestTestHTTP, ProcessReportToHeaderHTTPS) {
7162 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187163 https_test_server.RegisterRequestHandler(
7164 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417165 ASSERT_TRUE(https_test_server.Start());
7166 GURL request_url = https_test_server.GetURL("/");
7167
7168 TestNetworkDelegate network_delegate;
7169 TestReportingService reporting_service;
7170 TestURLRequestContext context(true);
7171 context.set_network_delegate(&network_delegate);
7172 context.set_reporting_service(&reporting_service);
7173 context.Init();
7174
7175 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167176 std::unique_ptr<URLRequest> request(context.CreateRequest(
7177 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417178 request->Start();
7179 base::RunLoop().Run();
7180
7181 ASSERT_EQ(1u, reporting_service.headers().size());
7182 EXPECT_EQ(request_url, reporting_service.headers()[0].url);
7183 EXPECT_EQ("foo, bar", reporting_service.headers()[0].header_value);
7184}
7185
Julia Tuttlef9b74062017-07-27 14:44:057186TEST_F(URLRequestTestHTTP, DontProcessReportToHeaderInvalidHttps) {
juliatuttle2b8dd2d12017-04-12 21:27:417187 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7188 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187189 https_test_server.RegisterRequestHandler(
7190 base::BindRepeating(&SendReportToHeader));
juliatuttle2b8dd2d12017-04-12 21:27:417191 ASSERT_TRUE(https_test_server.Start());
7192 GURL request_url = https_test_server.GetURL("/");
7193
7194 TestNetworkDelegate network_delegate;
7195 TestReportingService reporting_service;
7196 TestURLRequestContext context(true);
7197 context.set_network_delegate(&network_delegate);
7198 context.set_reporting_service(&reporting_service);
7199 context.Init();
7200
7201 TestDelegate d;
7202 d.set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:167203 std::unique_ptr<URLRequest> request(context.CreateRequest(
7204 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
juliatuttle2b8dd2d12017-04-12 21:27:417205 request->Start();
7206 base::RunLoop().Run();
7207
7208 EXPECT_TRUE(d.have_certificate_errors());
7209 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
7210 EXPECT_TRUE(reporting_service.headers().empty());
7211}
Julia Tuttlefadc26d2017-10-13 18:12:297212
7213// Network Error Logging is dependent on the Reporting API, so only run NEL
7214// tests if Reporting is enabled in the build.
tommycli59a63432015-11-06 00:10:557215
Julia Tuttlef9b74062017-07-27 14:44:057216namespace {
7217
Julia Tuttlecba7d222018-02-23 19:37:277218class TestNetworkErrorLoggingService : public NetworkErrorLoggingService {
Julia Tuttlef9b74062017-07-27 14:44:057219 public:
7220 struct Header {
Chris Watkins7a41d3552017-12-01 02:13:277221 Header() = default;
7222 ~Header() = default;
Julia Tuttlef9b74062017-07-27 14:44:057223
7224 url::Origin origin;
7225 std::string value;
7226 };
7227
Julia Tuttlef9b74062017-07-27 14:44:057228 const std::vector<Header>& headers() { return headers_; }
Douglas Creager1f56bbe2018-02-17 03:58:407229 const std::vector<RequestDetails>& errors() { return errors_; }
Julia Tuttlef9b74062017-07-27 14:44:057230
Julia Tuttlecba7d222018-02-23 19:37:277231 // NetworkErrorLoggingService implementation:
Julia Tuttlef9b74062017-07-27 14:44:057232
Julia Tuttlecba7d222018-02-23 19:37:277233 ~TestNetworkErrorLoggingService() override = default;
Julia Tuttlef9b74062017-07-27 14:44:057234
7235 void OnHeader(const url::Origin& origin, const std::string& value) override {
7236 Header header;
7237 header.origin = origin;
7238 header.value = value;
7239 headers_.push_back(header);
7240 }
7241
Douglas Creager1f56bbe2018-02-17 03:58:407242 void OnRequest(const RequestDetails& details) override {
Julia Tuttleb0d45472017-09-25 20:14:437243 errors_.push_back(details);
Julia Tuttlef9b74062017-07-27 14:44:057244 }
7245
Julia Tuttlea059db82018-01-04 18:46:437246 void RemoveBrowsingData(const base::RepeatingCallback<bool(const GURL&)>&
7247 origin_filter) override {
7248 NOTREACHED();
7249 }
7250
Julia Tuttlef9b74062017-07-27 14:44:057251 private:
7252 std::vector<Header> headers_;
Douglas Creager1f56bbe2018-02-17 03:58:407253 std::vector<RequestDetails> errors_;
Julia Tuttlef9b74062017-07-27 14:44:057254};
7255
7256std::unique_ptr<test_server::HttpResponse> SendNelHeader(
7257 const test_server::HttpRequest& request) {
7258 std::unique_ptr<test_server::BasicHttpResponse> http_response(
7259 new test_server::BasicHttpResponse);
7260 http_response->set_code(HTTP_OK);
Julia Tuttlecba7d222018-02-23 19:37:277261 http_response->AddCustomHeader(NetworkErrorLoggingService::kHeaderName,
Julia Tuttlef9b74062017-07-27 14:44:057262 "foo");
7263 return std::move(http_response);
7264}
7265
Julia Tuttle7005a2a2017-12-08 21:01:187266std::unique_ptr<test_server::HttpResponse> SendEmptyResponse(
7267 const test_server::HttpRequest& request) {
Gyuyoung Kimb480aba2018-01-27 07:00:047268 return std::make_unique<test_server::RawHttpResponse>("", "");
Julia Tuttle7005a2a2017-12-08 21:01:187269}
7270
Julia Tuttlef9b74062017-07-27 14:44:057271} // namespace
7272
7273TEST_F(URLRequestTestHTTP, DontProcessNelHeaderNoDelegate) {
Julia Tuttle7005a2a2017-12-08 21:01:187274 http_test_server()->RegisterRequestHandler(
7275 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057276 ASSERT_TRUE(http_test_server()->Start());
7277 GURL request_url = http_test_server()->GetURL("/");
7278
7279 TestNetworkDelegate network_delegate;
7280 TestURLRequestContext context(true);
7281 context.set_network_delegate(&network_delegate);
7282 context.Init();
7283
7284 TestDelegate d;
7285 std::unique_ptr<URLRequest> request(context.CreateRequest(
7286 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7287 request->Start();
7288 base::RunLoop().Run();
7289}
7290
7291TEST_F(URLRequestTestHTTP, DontProcessNelHeaderHttp) {
Julia Tuttle7005a2a2017-12-08 21:01:187292 http_test_server()->RegisterRequestHandler(
7293 base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057294 ASSERT_TRUE(http_test_server()->Start());
7295 GURL request_url = http_test_server()->GetURL("/");
7296
7297 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277298 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057299 TestURLRequestContext context(true);
7300 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277301 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057302 context.Init();
7303
7304 TestDelegate d;
7305 std::unique_ptr<URLRequest> request(context.CreateRequest(
7306 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7307 request->Start();
7308 base::RunLoop().Run();
7309
Julia Tuttlecba7d222018-02-23 19:37:277310 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057311}
7312
7313TEST_F(URLRequestTestHTTP, ProcessNelHeaderHttps) {
7314 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
Julia Tuttle7005a2a2017-12-08 21:01:187315 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057316 ASSERT_TRUE(https_test_server.Start());
7317 GURL request_url = https_test_server.GetURL("/");
7318
7319 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277320 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057321 TestURLRequestContext context(true);
7322 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277323 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057324 context.Init();
7325
7326 TestDelegate d;
7327 std::unique_ptr<URLRequest> request(context.CreateRequest(
7328 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7329 request->Start();
7330 base::RunLoop().Run();
7331
Julia Tuttlecba7d222018-02-23 19:37:277332 ASSERT_EQ(1u, nel_service.headers().size());
7333 EXPECT_EQ(url::Origin::Create(request_url), nel_service.headers()[0].origin);
7334 EXPECT_EQ("foo", nel_service.headers()[0].value);
Julia Tuttlef9b74062017-07-27 14:44:057335}
7336
7337TEST_F(URLRequestTestHTTP, DontProcessNelHeaderInvalidHttps) {
7338 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7339 https_test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
Julia Tuttle7005a2a2017-12-08 21:01:187340 https_test_server.RegisterRequestHandler(base::BindRepeating(&SendNelHeader));
Julia Tuttlef9b74062017-07-27 14:44:057341 ASSERT_TRUE(https_test_server.Start());
7342 GURL request_url = https_test_server.GetURL("/");
7343
7344 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277345 TestNetworkErrorLoggingService nel_service;
Julia Tuttlef9b74062017-07-27 14:44:057346 TestURLRequestContext context(true);
7347 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277348 context.set_network_error_logging_service(&nel_service);
Julia Tuttlef9b74062017-07-27 14:44:057349 context.Init();
7350
7351 TestDelegate d;
7352 d.set_allow_certificate_errors(true);
7353 std::unique_ptr<URLRequest> request(context.CreateRequest(
7354 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7355 request->Start();
7356 base::RunLoop().Run();
7357
7358 EXPECT_TRUE(d.have_certificate_errors());
7359 EXPECT_TRUE(IsCertStatusError(request->ssl_info().cert_status));
Julia Tuttlecba7d222018-02-23 19:37:277360 EXPECT_TRUE(nel_service.headers().empty());
Julia Tuttlef9b74062017-07-27 14:44:057361}
7362
Julia Tuttlefadc26d2017-10-13 18:12:297363TEST_F(URLRequestTestHTTP, DontForwardErrorToNelNoDelegate) {
7364 URLRequestFailedJob::AddUrlHandler();
7365
7366 GURL request_url =
7367 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7368
7369 TestNetworkDelegate network_delegate;
7370 TestURLRequestContext context(true);
7371 context.set_network_delegate(&network_delegate);
7372 context.Init();
7373
7374 TestDelegate d;
7375 std::unique_ptr<URLRequest> request(context.CreateRequest(
7376 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7377 request->Start();
7378 base::RunLoop().Run();
7379
7380 URLRequestFilter::GetInstance()->ClearHandlers();
7381}
7382
7383// TODO(juliatuttle): Figure out whether this restriction should be in place,
7384// and either implement it or remove this test.
7385TEST_F(URLRequestTestHTTP, DISABLED_DontForwardErrorToNelHttp) {
7386 URLRequestFailedJob::AddUrlHandler();
7387
7388 GURL request_url =
7389 URLRequestFailedJob::GetMockHttpUrl(ERR_CONNECTION_REFUSED);
7390
7391 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277392 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297393 TestURLRequestContext context(true);
7394 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277395 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297396 context.Init();
7397
7398 TestDelegate d;
7399 std::unique_ptr<URLRequest> request(context.CreateRequest(
7400 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7401 request->Start();
7402 base::RunLoop().Run();
7403
Julia Tuttlecba7d222018-02-23 19:37:277404 EXPECT_TRUE(nel_service.errors().empty());
Julia Tuttlefadc26d2017-10-13 18:12:297405
7406 URLRequestFilter::GetInstance()->ClearHandlers();
7407}
7408
Julia Tuttle7005a2a2017-12-08 21:01:187409TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Mock) {
Julia Tuttlefadc26d2017-10-13 18:12:297410 URLRequestFailedJob::AddUrlHandler();
7411
7412 GURL request_url =
7413 URLRequestFailedJob::GetMockHttpsUrl(ERR_CONNECTION_REFUSED);
7414
7415 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277416 TestNetworkErrorLoggingService nel_service;
Julia Tuttlefadc26d2017-10-13 18:12:297417 TestURLRequestContext context(true);
7418 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277419 context.set_network_error_logging_service(&nel_service);
Julia Tuttlefadc26d2017-10-13 18:12:297420 context.Init();
7421
7422 TestDelegate d;
7423 std::unique_ptr<URLRequest> request(context.CreateRequest(
7424 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7425 request->Start();
7426 base::RunLoop().Run();
7427
Julia Tuttlecba7d222018-02-23 19:37:277428 ASSERT_EQ(1u, nel_service.errors().size());
7429 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7430 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7431 EXPECT_EQ(ERR_CONNECTION_REFUSED, nel_service.errors()[0].type);
Julia Tuttlefadc26d2017-10-13 18:12:297432
7433 URLRequestFilter::GetInstance()->ClearHandlers();
7434}
7435
Julia Tuttle7005a2a2017-12-08 21:01:187436// Also test with a real server, to exercise interactions with
7437// URLRequestHttpJob.
7438TEST_F(URLRequestTestHTTP, ForwardErrorToNelHttps_Real) {
7439 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
7440 https_test_server.RegisterRequestHandler(
7441 base::BindRepeating(&SendEmptyResponse));
7442 ASSERT_TRUE(https_test_server.Start());
7443 GURL request_url = https_test_server.GetURL("/");
7444
7445 TestNetworkDelegate network_delegate;
Julia Tuttlecba7d222018-02-23 19:37:277446 TestNetworkErrorLoggingService nel_service;
Julia Tuttle7005a2a2017-12-08 21:01:187447 TestURLRequestContext context(true);
7448 context.set_network_delegate(&network_delegate);
Julia Tuttlecba7d222018-02-23 19:37:277449 context.set_network_error_logging_service(&nel_service);
Julia Tuttle7005a2a2017-12-08 21:01:187450 context.Init();
7451
7452 TestDelegate d;
7453 std::unique_ptr<URLRequest> request(context.CreateRequest(
7454 request_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
7455 request->Start();
7456 base::RunLoop().Run();
7457
Julia Tuttlecba7d222018-02-23 19:37:277458 ASSERT_EQ(1u, nel_service.errors().size());
7459 EXPECT_EQ(request_url, nel_service.errors()[0].uri);
7460 EXPECT_EQ(0, nel_service.errors()[0].status_code);
7461 EXPECT_EQ(ERR_EMPTY_RESPONSE, nel_service.errors()[0].type);
Julia Tuttle7005a2a2017-12-08 21:01:187462}
7463
Julia Tuttlefadc26d2017-10-13 18:12:297464#endif // BUILDFLAG(ENABLE_REPORTING)
7465
[email protected]316c1e5e2012-09-12 15:17:447466TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:557467 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447468
7469 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367470 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557471 http_test_server()->GetURL("/content-type-normalization.html"),
rhalavatib7bd7c792017-04-27 05:25:167472 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197473 req->Start();
[email protected]255620da2013-08-19 13:14:297474 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447475
7476 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197477 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447478 EXPECT_EQ("text/html", mime_type);
7479
7480 std::string charset;
[email protected]f7022f32014-08-21 16:32:197481 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:447482 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:197483 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:447484}
7485
[email protected]02494ec2014-05-07 15:05:297486TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:347487 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:347488 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:347489 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:027490 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347491
7492 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507493 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:347494}
7495
brettwa1228ebb2016-10-28 03:51:347496#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:297497TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
7498 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
7499 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:457500 FileProtocolHandler file_protocol_handler(
7501 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:297502 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
7503
7504 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:507505 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:297506}
7507
[email protected]588614c22013-08-16 00:09:027508TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:557509 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447510
7511 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367512 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557513 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167514 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197515 req->Start();
[email protected]255620da2013-08-19 13:14:297516 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447517
maksim.sisovb53724b52016-09-16 05:30:507518 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307519
7520 // The redirect should have been rejected before reporting it to the caller.
7521 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447522}
brettwa1228ebb2016-10-28 03:51:347523#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:447524
[email protected]588614c22013-08-16 00:09:027525TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:557526 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:027527
7528 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367529 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557530 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167531 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197532 req->Start();
fdoray5eeb7642016-06-22 16:11:287533 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:027534
maksim.sisovb53724b52016-09-16 05:30:507535 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307536
7537 // The redirect should have been rejected before reporting it to the
7538 // caller. See https://crbug.com/723796
7539 EXPECT_EQ(0, d.received_redirect_count());
[email protected]588614c22013-08-16 00:09:027540}
7541
davidbend894710b2017-06-06 19:28:307542// Test that redirects to invalid URLs are rejected. See
7543// https://crbug.com/462272.
[email protected]316c1e5e2012-09-12 15:17:447544TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:557545 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447546
7547 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367548 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557549 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
rhalavatib7bd7c792017-04-27 05:25:167550 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197551 req->Start();
[email protected]255620da2013-08-19 13:14:297552 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447553
davidbend894710b2017-06-06 19:28:307554 EXPECT_EQ(1, d.response_started_count());
7555 EXPECT_EQ(ERR_INVALID_REDIRECT, d.request_status());
7556
7557 // The redirect should have been rejected before reporting it to the caller.
7558 EXPECT_EQ(0, d.received_redirect_count());
[email protected]316c1e5e2012-09-12 15:17:447559}
7560
[email protected]e50efea2014-03-24 18:41:007561// Make sure redirects are cached, despite not reading their bodies.
7562TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:557563 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007564 GURL redirect_url =
tommycli59a63432015-11-06 00:10:557565 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:007566
7567 {
7568 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167569 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7570 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197571 req->Start();
[email protected]e50efea2014-03-24 18:41:007572 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507573 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007574 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:557575 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007576 }
7577
7578 {
7579 TestDelegate d;
7580 d.set_quit_on_redirect(true);
rhalavatib7bd7c792017-04-27 05:25:167581 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7582 redirect_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197583 req->Start();
[email protected]e50efea2014-03-24 18:41:007584 base::RunLoop().Run();
7585
7586 EXPECT_EQ(1, d.received_redirect_count());
7587 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197588 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007589
[email protected]f7022f32014-08-21 16:32:197590 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:007591 base::RunLoop().Run();
7592 EXPECT_EQ(1, d.received_redirect_count());
7593 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507594 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:557595 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:007596 }
7597}
7598
7599// Make sure a request isn't cached when a NetworkDelegate forces a redirect
7600// when the headers are read, since the body won't have been read.
7601TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:557602 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:007603 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:557604 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:007605
7606 {
7607 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:557608 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:007609 default_network_delegate_.set_redirect_on_headers_received_url(
7610 redirect_to_url);
7611
7612 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167613 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7614 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197615 req->Start();
[email protected]e50efea2014-03-24 18:41:007616 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507617 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:007618 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197619 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:007620 }
7621
7622 {
7623 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167624 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7625 initial_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197626 req->Start();
[email protected]e50efea2014-03-24 18:41:007627 base::RunLoop().Run();
7628
maksim.sisovb53724b52016-09-16 05:30:507629 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197630 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:007631 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197632 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:007633 }
7634}
7635
[email protected]5f714132014-03-26 10:41:167636// Tests that redirection to an unsafe URL is allowed when it has been marked as
7637// safe.
7638TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:557639 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167640
7641 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
7642 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7643 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7644
7645 TestDelegate d;
7646 {
danakj8522a25b2016-04-16 00:17:367647 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167648 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7649 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167650
[email protected]f7022f32014-08-21 16:32:197651 r->Start();
[email protected]5f714132014-03-26 10:41:167652 base::RunLoop().Run();
7653
maksim.sisovb53724b52016-09-16 05:30:507654 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197655 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:197656 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:167657 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
7658 }
7659}
7660
7661// Tests that a redirect to a different unsafe URL is blocked, even after adding
7662// some other URL to the whitelist.
7663TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:557664 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167665
7666 GURL unsafe_url("data:text/html,something");
7667 GURL different_unsafe_url("data:text/html,something-else");
7668 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7669 default_network_delegate_.set_allowed_unsafe_redirect_url(
7670 different_unsafe_url);
7671
7672 TestDelegate d;
7673 {
danakj8522a25b2016-04-16 00:17:367674 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167675 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d,
7676 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167677
[email protected]f7022f32014-08-21 16:32:197678 r->Start();
[email protected]5f714132014-03-26 10:41:167679 base::RunLoop().Run();
7680
maksim.sisovb53724b52016-09-16 05:30:507681 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
davidbend894710b2017-06-06 19:28:307682
7683 // The redirect should have been rejected before reporting it to the caller.
7684 EXPECT_EQ(0, d.received_redirect_count());
[email protected]5f714132014-03-26 10:41:167685 }
7686}
7687
[email protected]5f714132014-03-26 10:41:167688// Redirects from an URL with fragment to an unsafe URL with fragment should
7689// be allowed, and the reference fragment of the target URL should be preserved.
7690TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:557691 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167692
tommycli59a63432015-11-06 00:10:557693 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:167694 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7695 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
7696
7697 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
7698 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7699
7700 TestDelegate d;
7701 {
rhalavatib7bd7c792017-04-27 05:25:167702 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7703 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167704
[email protected]f7022f32014-08-21 16:32:197705 r->Start();
[email protected]5f714132014-03-26 10:41:167706 base::RunLoop().Run();
7707
[email protected]f7022f32014-08-21 16:32:197708 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507709 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197710 EXPECT_EQ(original_url, r->original_url());
7711 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:167712 }
7713}
7714
7715// When a delegate has specified a safe redirect URL, but it does not match the
7716// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:147717TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:557718 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:167719
tommycli59a63432015-11-06 00:10:557720 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167721 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:557722 GURL redirect_url(http_test_server()->GetURL("/target"));
7723 GURL expected_redirect_url(
7724 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:167725
7726 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7727 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
7728
7729 TestDelegate d;
7730 {
rhalavatib7bd7c792017-04-27 05:25:167731 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7732 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]5f714132014-03-26 10:41:167733
[email protected]f7022f32014-08-21 16:32:197734 r->Start();
[email protected]5f714132014-03-26 10:41:167735 base::RunLoop().Run();
7736
[email protected]f7022f32014-08-21 16:32:197737 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507738 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197739 EXPECT_EQ(original_url, r->original_url());
7740 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:167741 }
7742}
7743
[email protected]f878230e2014-04-03 15:36:147744// When a delegate has specified a safe redirect URL, assume that the redirect
7745// URL should not be changed. In particular, the reference fragment should not
7746// be modified.
7747TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557748 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147749
tommycli59a63432015-11-06 00:10:557750 GURL original_url(
7751 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:147752 GURL redirect_url("data:text/html,expect-no-reference-fragment");
7753
7754 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
7755 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
7756
7757 TestDelegate d;
7758 {
rhalavatib7bd7c792017-04-27 05:25:167759 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7760 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147761
[email protected]f7022f32014-08-21 16:32:197762 r->Start();
[email protected]f878230e2014-04-03 15:36:147763 base::RunLoop().Run();
7764
[email protected]f7022f32014-08-21 16:32:197765 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507766 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197767 EXPECT_EQ(original_url, r->original_url());
7768 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147769 }
7770}
7771
7772// When a URLRequestRedirectJob is created, the redirection must be followed and
7773// the reference fragment of the target URL must not be modified.
7774TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:557775 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147776
tommycli59a63432015-11-06 00:10:557777 GURL original_url(
7778 http_test_server()->GetURL("/original#should-not-be-appended"));
7779 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:147780
7781 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:167782 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
7783 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:147784
danakj8522a25b2016-04-16 00:17:367785 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:197786 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:427787 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7788 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:147789
[email protected]f7022f32014-08-21 16:32:197790 r->Start();
[email protected]f878230e2014-04-03 15:36:147791 base::RunLoop().Run();
7792
maksim.sisovb53724b52016-09-16 05:30:507793 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197794 EXPECT_EQ(original_url, r->original_url());
7795 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:147796}
7797
lizeb5120f6dc2016-02-19 09:29:447798TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
7799 ASSERT_TRUE(http_test_server()->Start());
7800
7801 const std::string referrer("foobar://totally.legit.referrer");
7802 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367803 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167804 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7805 TRAFFIC_ANNOTATION_FOR_TESTS));
lizeb5120f6dc2016-02-19 09:29:447806 req->SetReferrer(referrer);
7807 req->Start();
7808 base::RunLoop().Run();
7809
7810 EXPECT_EQ(std::string("None"), d.data_received());
7811}
7812
[email protected]316c1e5e2012-09-12 15:17:447813TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:557814 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447815
7816 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367817 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167818 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7819 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197820 req->SetReferrer("http://user:[email protected]/");
7821 req->Start();
[email protected]255620da2013-08-19 13:14:297822 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447823
7824 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
7825}
7826
[email protected]99ecf6e2013-04-10 22:46:137827TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:557828 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137829
7830 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367831 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167832 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7833 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197834 req->SetReferrer("http://foo.com/test#fragment");
7835 req->Start();
[email protected]255620da2013-08-19 13:14:297836 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137837
7838 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
7839}
7840
7841TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:557842 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:137843
7844 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367845 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167846 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d,
7847 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197848 req->SetReferrer("http://foo.com/test#fragment");
7849 req->SetReferrer("");
7850 req->Start();
[email protected]255620da2013-08-19 13:14:297851 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:137852
7853 EXPECT_EQ(std::string("None"), d.data_received());
7854}
7855
[email protected]316c1e5e2012-09-12 15:17:447856TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:557857 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447858
7859 TestDelegate d;
7860 {
7861 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:367862 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167863 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7864 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197865 req->Start();
[email protected]255620da2013-08-19 13:14:297866 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447867
7868 EXPECT_EQ(1, d.response_started_count());
7869 EXPECT_EQ(0, d.bytes_received());
7870 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507871 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447872 }
7873}
7874
7875TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557876 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447877
7878 TestDelegate d;
7879 {
7880 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557881 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167882 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7883 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047884
[email protected]f7022f32014-08-21 16:32:197885 req->Start();
[email protected]255620da2013-08-19 13:14:297886 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447887
7888 EXPECT_EQ(1, d.received_redirect_count());
Shivani Sharmac18f9762017-10-23 16:43:237889 EXPECT_TRUE(d.have_full_request_headers());
7890 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7891 d.ClearFullRequestHeaders();
[email protected]316c1e5e2012-09-12 15:17:447892
[email protected]f7022f32014-08-21 16:32:197893 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297894 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447895
7896 EXPECT_EQ(1, d.response_started_count());
7897 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507898 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447899
[email protected]6cdfd7f2013-02-08 20:40:157900 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:447901 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477902 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447903 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7904
7905 std::string contents;
[email protected]82f84b92013-08-30 18:23:507906 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447907 EXPECT_EQ(contents, d.data_received());
7908 }
7909}
7910
[email protected]79e1fd62013-06-20 06:50:047911TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557912 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047913
7914 TestDelegate d;
7915 {
7916 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557917 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
rhalavatib7bd7c792017-04-27 05:25:167918 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
7919 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]79e1fd62013-06-20 06:50:047920
7921 EXPECT_FALSE(d.have_full_request_headers());
7922
[email protected]f7022f32014-08-21 16:32:197923 req->Start();
[email protected]255620da2013-08-19 13:14:297924 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047925
7926 EXPECT_EQ(1, d.received_redirect_count());
[email protected]79e1fd62013-06-20 06:50:047927
[email protected]f7022f32014-08-21 16:32:197928 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297929 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047930
tommycli59a63432015-11-06 00:10:557931 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047932 EXPECT_EQ(1, d.response_started_count());
7933 EXPECT_TRUE(d.have_full_request_headers());
7934 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7935 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507936 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:047937
7938 base::FilePath path;
7939 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477940 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047941 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7942
7943 std::string contents;
[email protected]82f84b92013-08-30 18:23:507944 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047945 EXPECT_EQ(contents, d.data_received());
7946 }
7947}
7948
[email protected]316c1e5e2012-09-12 15:17:447949TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557950 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447951
7952 TestDelegate d;
7953 {
7954 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:367955 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:167956 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
7957 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:197958 req->Start();
[email protected]255620da2013-08-19 13:14:297959 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447960
7961 EXPECT_EQ(1, d.received_redirect_count());
7962
[email protected]f7022f32014-08-21 16:32:197963 req->Cancel();
[email protected]255620da2013-08-19 13:14:297964 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447965
7966 EXPECT_EQ(1, d.response_started_count());
7967 EXPECT_EQ(0, d.bytes_received());
7968 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507969 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447970 }
7971}
7972
7973TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557974 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447975
[email protected]3b23a222013-05-15 21:33:257976 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447977 {
7978 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367979 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557980 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167981 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447982 HttpRequestHeaders headers;
7983 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197984 req->SetExtraRequestHeaders(headers);
7985 req->Start();
[email protected]255620da2013-08-19 13:14:297986 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257987
7988 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197989 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257990 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447991 }
7992
[email protected]3b23a222013-05-15 21:33:257993 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447994 {
7995 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367996 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557997 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:167998 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:447999 HttpRequestHeaders headers;
8000 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:198001 req->SetExtraRequestHeaders(headers);
8002 req->Start();
[email protected]255620da2013-08-19 13:14:298003 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448004
[email protected]f7022f32014-08-21 16:32:198005 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258006
8007 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198008 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258009 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:448010 }
8011
[email protected]3b23a222013-05-15 21:33:258012 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:448013 {
8014 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368015 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558016 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168017 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448018 HttpRequestHeaders headers;
8019 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:198020 req->SetExtraRequestHeaders(headers);
8021 req->Start();
[email protected]255620da2013-08-19 13:14:298022 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448023
[email protected]f7022f32014-08-21 16:32:198024 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:258025
8026 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198027 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258028 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:448029 }
8030}
8031
8032TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:558033 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448034
8035 // populate the cache
8036 {
8037 TestDelegate d;
8038 d.set_credentials(AuthCredentials(kUser, kSecret));
8039
danakj8522a25b2016-04-16 00:17:368040 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168041 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8042 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198043 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448044
[email protected]255620da2013-08-19 13:14:298045 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448046
8047 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8048 }
8049
8050 // repeat request with end-to-end validation. since auth-basic results in a
8051 // cachable page, we expect this test to result in a 304. in which case, the
8052 // response should be fetched from the cache.
8053 {
8054 TestDelegate d;
8055 d.set_credentials(AuthCredentials(kUser, kSecret));
8056
danakj8522a25b2016-04-16 00:17:368057 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168058 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8059 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198060 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8061 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448062
[email protected]255620da2013-08-19 13:14:298063 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448064
8065 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8066
8067 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198068 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:448069 }
8070}
8071
8072// Check that Set-Cookie headers in 401 responses are respected.
8073// http://crbug.com/6450
8074TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:558075 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448076
8077 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:558078 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:448079
8080 // Request a page that will give a 401 containing a Set-Cookie header.
8081 // Verify that when the transaction is restarted, it includes the new cookie.
8082 {
[email protected]ceefd7fd2012-11-29 00:36:248083 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448084 TestURLRequestContext context(true);
8085 context.set_network_delegate(&network_delegate);
8086 context.Init();
8087
8088 TestDelegate d;
8089 d.set_credentials(AuthCredentials(kUser, kSecret));
8090
danakj8522a25b2016-04-16 00:17:368091 std::unique_ptr<URLRequest> r(
rhalavatib7bd7c792017-04-27 05:25:168092 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d,
8093 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198094 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448095
[email protected]255620da2013-08-19 13:14:298096 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448097
8098 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8099
8100 // Make sure we sent the cookie in the restarted transaction.
8101 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8102 != std::string::npos);
8103 }
8104
8105 // Same test as above, except this time the restart is initiated earlier
8106 // (without user intervention since identity is embedded in the URL).
8107 {
[email protected]ceefd7fd2012-11-29 00:36:248108 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448109 TestURLRequestContext context(true);
8110 context.set_network_delegate(&network_delegate);
8111 context.Init();
8112
8113 TestDelegate d;
8114
8115 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:188116 replacements.SetUsernameStr("user2");
8117 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:448118 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
8119
rhalavatib7bd7c792017-04-27 05:25:168120 std::unique_ptr<URLRequest> r(context.CreateRequest(
8121 url_with_identity, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198122 r->Start();
[email protected]316c1e5e2012-09-12 15:17:448123
[email protected]255620da2013-08-19 13:14:298124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448125
8126 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
8127
8128 // Make sure we sent the cookie in the restarted transaction.
8129 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
8130 != std::string::npos);
8131 }
8132}
8133
[email protected]58e32bb2013-01-21 18:23:258134// Tests that load timing works as expected with auth and the cache.
8135TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:558136 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:258137
8138 // populate the cache
8139 {
8140 TestDelegate d;
8141 d.set_credentials(AuthCredentials(kUser, kSecret));
8142
danakj8522a25b2016-04-16 00:17:368143 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168144 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8145 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198146 r->Start();
[email protected]58e32bb2013-01-21 18:23:258147
[email protected]255620da2013-08-19 13:14:298148 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258149
8150 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8151
8152 LoadTimingInfo load_timing_info_before_auth;
8153 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
8154 &load_timing_info_before_auth));
8155 TestLoadTimingNotReused(load_timing_info_before_auth,
8156 CONNECT_TIMING_HAS_DNS_TIMES);
8157
8158 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198159 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:258160 // The test server does not support keep alive sockets, so the second
8161 // request with auth should use a new socket.
8162 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
8163 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
8164 load_timing_info.socket_log_id);
8165 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
8166 load_timing_info.connect_timing.connect_start);
8167 }
8168
[email protected]3b23a222013-05-15 21:33:258169 // Repeat request with end-to-end validation. Since auth-basic results in a
8170 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:258171 // response should be fetched from the cache.
8172 {
8173 TestDelegate d;
8174 d.set_credentials(AuthCredentials(kUser, kSecret));
8175
danakj8522a25b2016-04-16 00:17:368176 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168177 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d,
8178 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198179 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
8180 r->Start();
[email protected]58e32bb2013-01-21 18:23:258181
[email protected]255620da2013-08-19 13:14:298182 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:258183
8184 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
8185
8186 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:198187 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:258188
[email protected]3b23a222013-05-15 21:33:258189 // Since there was a request that went over the wire, the load timing
8190 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:258191 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198192 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258193 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:258194 }
8195}
8196
[email protected]316c1e5e2012-09-12 15:17:448197// In this test, we do a POST which the server will 302 redirect.
8198// The subsequent transaction should use GET, and should not send the
8199// Content-Type header.
8200// http://code.google.com/p/chromium/issues/detail?id=843
8201TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:558202 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448203
8204 const char kData[] = "hello world";
8205
8206 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368207 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168208 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
8209 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198210 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078211 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448212
8213 // Set headers (some of which are specific to the POST).
8214 HttpRequestHeaders headers;
8215 headers.AddHeadersFromString(
8216 "Content-Type: multipart/form-data; "
8217 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
8218 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
8219 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
8220 "Accept-Language: en-US,en\r\n"
8221 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
8222 "Content-Length: 11\r\n"
8223 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:198224 req->SetExtraRequestHeaders(headers);
8225 req->Start();
[email protected]255620da2013-08-19 13:14:298226 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448227
8228 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:198229 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:448230 EXPECT_EQ("text/html", mime_type);
8231
8232 const std::string& data = d.data_received();
8233
8234 // Check that the post-specific headers were stripped:
8235 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
8236 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
Yutaka Hirano957d722f2017-08-31 08:40:498237 EXPECT_FALSE(ContainsString(data, "Origin:"));
[email protected]316c1e5e2012-09-12 15:17:448238
8239 // These extra request headers should not have been stripped.
8240 EXPECT_TRUE(ContainsString(data, "Accept:"));
8241 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
8242 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
8243}
8244
jww5fe460ff2015-03-28 00:22:518245// The following tests check that we handle mutating the request for HTTP
8246// redirects as expected.
8247// See https://crbug.com/56373, https://crbug.com/102130, and
8248// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:448249
8250TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:558251 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448252
tommycli59a63432015-11-06 00:10:558253 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:518254 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558255 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:448256
8257 HTTPRedirectMethodTest(url, "POST", "GET", true);
8258 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8259 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518260
8261 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8262 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498263 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8264 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8265 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408266 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8267 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448268}
8269
8270TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:558271 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448272
tommycli59a63432015-11-06 00:10:558273 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:518274 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558275 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:448276
8277 HTTPRedirectMethodTest(url, "POST", "GET", true);
8278 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8279 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518280
8281 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8282 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Yutaka Hirano957d722f2017-08-31 08:40:498283 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8284 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8285 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408286 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8287 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448288}
8289
8290TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:558291 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448292
tommycli59a63432015-11-06 00:10:558293 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:518294 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558295 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:448296
8297 HTTPRedirectMethodTest(url, "POST", "GET", true);
8298 HTTPRedirectMethodTest(url, "PUT", "GET", true);
8299 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518300
Alex Clarke1e08882b32017-10-06 14:22:408301 HTTPRedirectOriginHeaderTest(url, "CONNECT", "GET", std::string());
8302 HTTPRedirectOriginHeaderTest(https_redirect_url, "CONNECT", "GET",
8303 std::string());
8304 HTTPRedirectOriginHeaderTest(url, "DELETE", "GET", std::string());
8305 HTTPRedirectOriginHeaderTest(https_redirect_url, "DELETE", "GET",
8306 std::string());
jww5fe460ff2015-03-28 00:22:518307 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8308 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
Alex Clarke1e08882b32017-10-06 14:22:408309 HTTPRedirectOriginHeaderTest(url, "HEAD", "HEAD", url.GetOrigin().spec());
8310 HTTPRedirectOriginHeaderTest(https_redirect_url, "HEAD", "HEAD", "null");
8311 HTTPRedirectOriginHeaderTest(url, "OPTIONS", "GET", std::string());
8312 HTTPRedirectOriginHeaderTest(https_redirect_url, "OPTIONS", "GET",
8313 std::string());
Yutaka Hirano957d722f2017-08-31 08:40:498314 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
8315 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
8316 std::string());
Alex Clarke1e08882b32017-10-06 14:22:408317 HTTPRedirectOriginHeaderTest(url, "PUT", "GET", std::string());
8318 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "GET", std::string());
[email protected]316c1e5e2012-09-12 15:17:448319}
8320
8321TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:558322 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448323
tommycli59a63432015-11-06 00:10:558324 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:518325 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558326 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:448327
8328 HTTPRedirectMethodTest(url, "POST", "POST", true);
8329 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8330 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518331
8332 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8333 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8334 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8335 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408336 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8337 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]316c1e5e2012-09-12 15:17:448338}
8339
[email protected]0a17aab32014-04-24 03:32:378340TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:558341 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378342
tommycli59a63432015-11-06 00:10:558343 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:518344 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:558345 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:378346
8347 HTTPRedirectMethodTest(url, "POST", "POST", true);
8348 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
8349 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:518350
8351 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
8352 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
8353 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
8354 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
Alex Clarke1e08882b32017-10-06 14:22:408355 HTTPRedirectOriginHeaderTest(url, "PUT", "PUT", url.GetOrigin().spec());
8356 HTTPRedirectOriginHeaderTest(https_redirect_url, "PUT", "PUT", "null");
[email protected]0a17aab32014-04-24 03:32:378357}
8358
8359// Make sure that 308 responses without bodies are not treated as redirects.
8360// Certain legacy apis that pre-date the response code expect this behavior
8361// (Like Google Drive).
8362TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:558363 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:378364
8365 TestDelegate d;
tommycli59a63432015-11-06 00:10:558366 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:378367
rhalavatib7bd7c792017-04-27 05:25:168368 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
8369 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]0a17aab32014-04-24 03:32:378370
[email protected]f7022f32014-08-21 16:32:198371 request->Start();
[email protected]0a17aab32014-04-24 03:32:378372 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:508373 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:378374 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:198375 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:378376 EXPECT_EQ("This is not a redirect.", d.data_received());
8377}
8378
[email protected]f878230e2014-04-03 15:36:148379TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:558380 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:148381
tommycli59a63432015-11-06 00:10:558382 GURL original_url(
8383 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
8384 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:148385
8386 TestDelegate d;
8387 {
rhalavatib7bd7c792017-04-27 05:25:168388 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8389 original_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f878230e2014-04-03 15:36:148390
[email protected]f7022f32014-08-21 16:32:198391 r->Start();
[email protected]f878230e2014-04-03 15:36:148392 base::RunLoop().Run();
8393
[email protected]f7022f32014-08-21 16:32:198394 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508395 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:198396 EXPECT_EQ(original_url, r->original_url());
8397 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:148398 }
8399}
8400
[email protected]cba24642014-08-15 20:49:598401TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558402 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598403
tommycli59a63432015-11-06 00:10:558404 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598405 GURL first_party_url("http://example.com");
8406
8407 TestDelegate d;
8408 {
rhalavatib7bd7c792017-04-27 05:25:168409 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8410 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468411 r->set_site_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:598412
[email protected]f7022f32014-08-21 16:32:198413 r->Start();
[email protected]cba24642014-08-15 20:49:598414 base::RunLoop().Run();
8415
[email protected]f7022f32014-08-21 16:32:198416 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508417 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468418 EXPECT_EQ(first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598419 }
8420}
8421
8422TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:558423 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:598424
tommycli59a63432015-11-06 00:10:558425 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:598426 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:558427 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:598428
8429 TestDelegate d;
8430 {
rhalavatib7bd7c792017-04-27 05:25:168431 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8432 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
Mike Westb85da8ed2017-08-10 14:16:468433 r->set_site_for_cookies(original_first_party_url);
[email protected]f7022f32014-08-21 16:32:198434 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:598435 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
8436
[email protected]f7022f32014-08-21 16:32:198437 r->Start();
[email protected]cba24642014-08-15 20:49:598438 base::RunLoop().Run();
8439
[email protected]f7022f32014-08-21 16:32:198440 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:508441 EXPECT_EQ(OK, d.request_status());
Mike Westb85da8ed2017-08-10 14:16:468442 EXPECT_EQ(expected_first_party_url, r->site_for_cookies());
[email protected]cba24642014-08-15 20:49:598443 }
8444}
8445
[email protected]316c1e5e2012-09-12 15:17:448446TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:558447 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448448
8449 const char kData[] = "hello world";
8450
8451 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368452 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168453 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8454 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198455 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078456 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448457 HttpRequestHeaders headers;
8458 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328459 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198460 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448461
danakj8522a25b2016-04-16 00:17:368462 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558463 req.get(), &default_network_delegate_,
8464 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428465 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8466 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448467
[email protected]f7022f32014-08-21 16:32:198468 req->Start();
[email protected]255620da2013-08-19 13:14:298469 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198470 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:448471}
8472
8473TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:558474 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448475
8476 const char kData[] = "hello world";
8477
8478 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368479 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168480 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8481 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198482 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078483 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:448484 HttpRequestHeaders headers;
8485 headers.SetHeader(HttpRequestHeaders::kContentLength,
Brett Wilson5accd242017-11-30 22:07:328486 base::NumberToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:198487 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:448488
danakj8522a25b2016-04-16 00:17:368489 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558490 req.get(), &default_network_delegate_,
8491 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:098492 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:428493 "Very Good Reason"));
8494 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:448495
[email protected]f7022f32014-08-21 16:32:198496 req->Start();
[email protected]255620da2013-08-19 13:14:298497 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198498 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:448499 EXPECT_EQ(kData, d.data_received());
8500}
8501
8502// Check that default A-L header is sent.
8503TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558504 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448505
[email protected]8790210c2013-12-02 05:29:538506 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:248507 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448508 TestURLRequestContext context(true);
8509 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:438510 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448511 context.Init();
8512
8513 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368514 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558515 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168516 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198517 req->Start();
[email protected]255620da2013-08-19 13:14:298518 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448519 EXPECT_EQ("en", d.data_received());
8520}
8521
8522// Check that an empty A-L header is not sent. http://crbug.com/77365.
8523TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558524 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448525
[email protected]8790210c2013-12-02 05:29:538526 std::string empty_string; // Avoid most vexing parse on line below.
8527 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:248528 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:448529 TestURLRequestContext context(true);
8530 context.set_network_delegate(&network_delegate);
8531 context.Init();
8532 // We override the language after initialization because empty entries
8533 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:438534 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:448535
8536 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368537 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:558538 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168539 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198540 req->Start();
[email protected]255620da2013-08-19 13:14:298541 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448542 EXPECT_EQ("None", d.data_received());
8543}
8544
8545// Check that if request overrides the A-L header, the default is not appended.
8546// See http://crbug.com/20894
8547TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:558548 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448549
8550 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368551 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558552 http_test_server()->GetURL("/echoheader?Accept-Language"),
rhalavatib7bd7c792017-04-27 05:25:168553 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448554 HttpRequestHeaders headers;
8555 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:198556 req->SetExtraRequestHeaders(headers);
8557 req->Start();
[email protected]255620da2013-08-19 13:14:298558 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448559 EXPECT_EQ(std::string("ru"), d.data_received());
8560}
8561
8562// Check that default A-E header is sent.
8563TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558564 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448565
8566 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368567 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558568 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168569 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448570 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:198571 req->SetExtraRequestHeaders(headers);
8572 req->Start();
[email protected]255620da2013-08-19 13:14:298573 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448574 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
8575}
8576
8577// Check that if request overrides the A-E header, the default is not appended.
8578// See http://crbug.com/47381
8579TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:558580 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448581
8582 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368583 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558584 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
rhalavatib7bd7c792017-04-27 05:25:168585 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448586 HttpRequestHeaders headers;
8587 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:198588 req->SetExtraRequestHeaders(headers);
8589 req->Start();
[email protected]255620da2013-08-19 13:14:298590 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448591 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
8592 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
8593}
8594
[email protected]84f05432013-03-15 01:00:128595// Check that setting the A-C header sends the proper header.
8596TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:558597 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448598
8599 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368600 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558601 http_test_server()->GetURL("/echoheader?Accept-Charset"),
rhalavatib7bd7c792017-04-27 05:25:168602 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448603 HttpRequestHeaders headers;
8604 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:198605 req->SetExtraRequestHeaders(headers);
8606 req->Start();
[email protected]255620da2013-08-19 13:14:298607 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448608 EXPECT_EQ(std::string("koi-8r"), d.data_received());
8609}
8610
8611// Check that default User-Agent header is sent.
8612TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:558613 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448614
8615 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368616 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558617 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168618 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198619 req->Start();
[email protected]255620da2013-08-19 13:14:298620 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:198621 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:378622 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448623}
8624
8625// Check that if request overrides the User-Agent header,
8626// the default is not appended.
marqf14fff8d2015-12-02 15:52:298627// TODO(crbug.com/564656) This test is flaky on iOS.
8628#if defined(OS_IOS)
8629#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
8630#else
8631#define MAYBE_OverrideUserAgent OverrideUserAgent
8632#endif
8633TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:558634 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:448635
8636 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368637 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558638 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168639 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:448640 HttpRequestHeaders headers;
8641 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:198642 req->SetExtraRequestHeaders(headers);
8643 req->Start();
[email protected]255620da2013-08-19 13:14:298644 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:358645 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448646}
8647
[email protected]ee4c30d2012-11-07 15:08:438648// Check that a NULL HttpUserAgentSettings causes the corresponding empty
8649// User-Agent header to be sent but does not send the Accept-Language and
8650// Accept-Charset headers.
8651TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:558652 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:438653
[email protected]ceefd7fd2012-11-29 00:36:248654 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:438655 TestURLRequestContext context(true);
8656 context.set_network_delegate(&network_delegate);
8657 context.Init();
8658 // We override the HttpUserAgentSettings after initialization because empty
8659 // entries get overridden by Init().
8660 context.set_http_user_agent_settings(NULL);
8661
8662 struct {
8663 const char* request;
8664 const char* expected_response;
tommycli59a63432015-11-06 00:10:558665 } tests[] = {{"/echoheader?Accept-Language", "None"},
8666 {"/echoheader?Accept-Charset", "None"},
8667 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:438668
viettrungluue4a8b882014-10-16 06:17:388669 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:438670 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368671 std::unique_ptr<URLRequest> req(context.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168672 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d,
8673 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198674 req->Start();
[email protected]255620da2013-08-19 13:14:298675 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:438676 EXPECT_EQ(tests[i].expected_response, d.data_received())
8677 << " Request = \"" << tests[i].request << "\"";
8678 }
8679}
8680
[email protected]5033ab82013-03-22 20:17:468681// Make sure that URLRequest passes on its priority updates to
8682// newly-created jobs after the first one.
8683TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:558684 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:468685
8686 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368687 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168688 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
8689 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198690 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:468691
danakj8522a25b2016-04-16 00:17:368692 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:558693 req.get(), &default_network_delegate_,
8694 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:428695 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
8696 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:468697
[email protected]f7022f32014-08-21 16:32:198698 req->SetPriority(LOW);
8699 req->Start();
8700 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:468701
mmenkeed0498b2015-12-08 23:20:428702 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:368703 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:428704 req.get(), &default_network_delegate_, &job_priority));
8705 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:468706
8707 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:298708 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:428709 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:468710}
8711
[email protected]80abdad2014-03-15 00:20:548712// Check that creating a network request while entering/exiting suspend mode
8713// fails as it should. This is the only case where an HttpTransactionFactory
8714// does not return an HttpTransaction.
8715TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
8716 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:368717 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:178718 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:548719 network_layer->OnSuspend();
8720
dchengc7eeda422015-12-26 03:56:488721 HttpCache http_cache(std::move(network_layer),
zhongyi3ceab9f2017-02-04 02:06:038722 HttpCache::DefaultBackend::InMemory(0),
zhongyi4928bd52017-02-08 02:16:278723 false /* is_main_cache */);
[email protected]80abdad2014-03-15 00:20:548724
8725 TestURLRequestContext context(true);
8726 context.set_http_transaction_factory(&http_cache);
8727 context.Init();
8728
8729 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368730 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168731 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8732 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:198733 req->Start();
[email protected]80abdad2014-03-15 00:20:548734 base::RunLoop().Run();
8735
8736 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:508737 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:548738}
8739
mmenke2281f3762015-11-02 20:38:178740namespace {
[email protected]80abdad2014-03-15 00:20:548741
mmenke2281f3762015-11-02 20:38:178742// HttpTransactionFactory that synchronously fails to create transactions.
8743class FailingHttpTransactionFactory : public HttpTransactionFactory {
8744 public:
8745 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
8746 : network_session_(network_session) {}
8747
Chris Watkins7a41d3552017-12-01 02:13:278748 ~FailingHttpTransactionFactory() override = default;
mmenke2281f3762015-11-02 20:38:178749
8750 // HttpTransactionFactory methods:
8751 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:368752 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:178753 return ERR_FAILED;
8754 }
8755
8756 HttpCache* GetCache() override { return nullptr; }
8757
8758 HttpNetworkSession* GetSession() override { return network_session_; }
8759
8760 private:
8761 HttpNetworkSession* network_session_;
8762
8763 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
8764};
8765
8766} // namespace
8767
8768// Check that when a request that fails to create an HttpTransaction can be
8769// cancelled while the failure notification is pending, and doesn't send two
8770// failure notifications.
8771//
8772// This currently only happens when in suspend mode and there's no cache, but
8773// just use a special HttpTransactionFactory, to avoid depending on those
8774// behaviors.
8775TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
8776 FailingHttpTransactionFactory http_transaction_factory(
8777 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:548778 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:178779 context.set_http_transaction_factory(&http_transaction_factory);
8780 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:548781 context.Init();
8782
8783 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368784 std::unique_ptr<URLRequest> req(
rhalavatib7bd7c792017-04-27 05:25:168785 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d,
8786 TRAFFIC_ANNOTATION_FOR_TESTS));
mmenke2281f3762015-11-02 20:38:178787 // Don't send cookies (Collecting cookies is asynchronous, and need request to
8788 // try to create an HttpNetworkTransaction synchronously on start).
8789 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:198790 req->Start();
mmenke2281f3762015-11-02 20:38:178791 req->Cancel();
[email protected]80abdad2014-03-15 00:20:548792 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:178793 // Run pending error task, if there is one.
8794 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:548795
8796 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:178797 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508798 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:178799
8800 // NetworkDelegate should see the cancellation, but not the error.
8801 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
8802 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:548803}
8804
ttuttlec0c828492015-05-15 01:25:558805TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:558806 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558807
8808 TestDelegate d;
tommycli59a63432015-11-06 00:10:558809 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168810 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8811 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558812
8813 req->Start();
8814 base::RunLoop().Run();
8815
8816 EXPECT_TRUE(req->response_info().network_accessed);
8817}
8818
8819TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:558820 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558821
8822 // Populate the cache.
8823 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368824 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168825 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d,
8826 TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:558827 req->Start();
8828 base::RunLoop().Run();
8829
maksim.sisovb53724b52016-09-16 05:30:508830 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558831 EXPECT_TRUE(req->response_info().network_accessed);
8832 EXPECT_FALSE(req->response_info().was_cached);
8833
tommycli59a63432015-11-06 00:10:558834 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
rhalavatib7bd7c792017-04-27 05:25:168835 DEFAULT_PRIORITY, &d,
8836 TRAFFIC_ANNOTATION_FOR_TESTS);
ttuttlec0c828492015-05-15 01:25:558837 req->Start();
8838 base::RunLoop().Run();
8839
maksim.sisovb53724b52016-09-16 05:30:508840 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:558841 EXPECT_FALSE(req->response_info().network_accessed);
8842 EXPECT_TRUE(req->response_info().was_cached);
8843}
8844
8845TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:558846 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:558847
8848 TestDelegate d;
tommycli59a63432015-11-06 00:10:558849 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168850 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8851 test_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
jkarlina067deed2016-10-27 14:48:338852 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:558853
8854 req->Start();
8855 base::RunLoop().Run();
8856
8857 EXPECT_FALSE(req->response_info().network_accessed);
8858}
8859
rdsmithbf8c3c12016-11-18 18:16:248860// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088861// correctly in the absence of contention.
8862TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8863 ASSERT_TRUE(http_test_server()->Start());
8864
8865 TestDelegate d;
8866 GURL test_url(http_test_server()->GetURL("/"));
rhalavatib7bd7c792017-04-27 05:25:168867 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
8868 test_url, THROTTLED, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rdsmith5eb6fbc2016-10-21 17:36:088869 req->Start();
8870 base::RunLoop().Run();
8871
8872 EXPECT_TRUE(req->status().is_success());
8873}
8874
ricea3a1c71f2016-06-17 10:05:268875TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8876 ASSERT_TRUE(http_test_server()->Start());
8877
8878 TestDelegate d;
8879 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168880 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
8881 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268882 req->Start();
8883 base::RunLoop().Run();
8884
8885 EXPECT_EQ(5, req->GetRawBodyBytes());
8886}
8887
8888TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8889 ASSERT_TRUE(http_test_server()->Start());
8890
8891 TestDelegate d;
8892 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168893 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d,
8894 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:268895 req->Start();
8896 base::RunLoop().Run();
8897
8898 EXPECT_EQ(30, req->GetRawBodyBytes());
8899}
8900
jamd3f5a3c2016-10-27 18:52:028901// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8902// the delegate isn't called back synchronously.
8903TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8904 ASSERT_TRUE(http_test_server()->Start());
8905 default_network_delegate_.set_before_start_transaction_fails();
8906
8907 TestDelegate d;
8908 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168909 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d,
8910 TRAFFIC_ANNOTATION_FOR_TESTS));
jamd3f5a3c2016-10-27 18:52:028911 req->Start();
8912 DCHECK(!d.response_completed());
8913 base::RunLoop().Run();
8914 DCHECK(d.response_completed());
8915 EXPECT_EQ(ERR_FAILED, d.request_status());
8916}
8917
bengr1bf8e942014-11-07 01:36:508918class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
8919 public:
8920 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
8921 // ideally remove the dependency on URLRequestTestJob, and maybe move these
8922 // tests into the factory tests.
8923 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
8924 }
8925
8926 void SetUpFactory() override {
8927 interceptor_ = new MockURLRequestInterceptor();
8928 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:368929 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:508930 }
8931
8932 MockURLRequestInterceptor* interceptor() const {
8933 return interceptor_;
8934 }
8935
8936 private:
8937 MockURLRequestInterceptor* interceptor_;
8938};
8939
8940TEST_F(URLRequestInterceptorTestHTTP,
8941 NetworkDelegateNotificationOnRedirectIntercept) {
8942 interceptor()->set_intercept_redirect(true);
8943 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8944 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8945
tommycli59a63432015-11-06 00:10:558946 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508947
8948 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368949 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:168950 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d,
8951 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508952 req->Start();
8953 base::RunLoop().Run();
8954
8955 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8956 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:508957 int status = d.request_status();
8958 EXPECT_EQ(OK, status);
8959 if (status == OK)
bengr1bf8e942014-11-07 01:36:508960 EXPECT_EQ(200, req->response_headers()->response_code());
8961
8962 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8963 EXPECT_EQ(1, d.response_started_count());
8964 EXPECT_EQ(0, d.received_redirect_count());
8965
8966 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008967 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508968 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8969}
8970
8971TEST_F(URLRequestInterceptorTestHTTP,
8972 NetworkDelegateNotificationOnErrorIntercept) {
8973 // Intercept that error and respond with an OK response.
8974 interceptor()->set_intercept_final_response(true);
8975 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8976 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8977 default_network_delegate()->set_can_be_intercepted_on_error(true);
8978
tommycli59a63432015-11-06 00:10:558979 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508980
8981 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368982 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558983 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:168984 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:508985 req->set_method("GET");
8986 req->Start();
8987 base::RunLoop().Run();
8988
8989 EXPECT_TRUE(interceptor()->did_intercept_final());
8990
8991 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508992 int status = d.request_status();
8993 EXPECT_EQ(OK, status);
8994 if (status == OK)
bengr1bf8e942014-11-07 01:36:508995 EXPECT_EQ(200, req->response_headers()->response_code());
8996 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8997 EXPECT_EQ(1, d.response_started_count());
8998 EXPECT_EQ(0, d.received_redirect_count());
8999
9000 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009001 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509002 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
9003}
9004
9005TEST_F(URLRequestInterceptorTestHTTP,
9006 NetworkDelegateNotificationOnResponseIntercept) {
9007 // Intercept that error and respond with an OK response.
9008 interceptor()->set_intercept_final_response(true);
9009
9010 // Intercept with a real URLRequestHttpJob.
9011 interceptor()->set_use_url_request_http_job(true);
9012
tommycli59a63432015-11-06 00:10:559013 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:509014
9015 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369016 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169017 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d,
9018 TRAFFIC_ANNOTATION_FOR_TESTS));
bengr1bf8e942014-11-07 01:36:509019 req->set_method("GET");
9020 req->Start();
9021 base::RunLoop().Run();
9022
9023 EXPECT_TRUE(interceptor()->did_intercept_final());
9024
9025 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:509026 int status = d.request_status();
9027 EXPECT_EQ(OK, status);
9028 if (status == OK)
bengr1bf8e942014-11-07 01:36:509029 EXPECT_EQ(200, req->response_headers()->response_code());
9030 EXPECT_EQ("hello", d.data_received());
9031 EXPECT_EQ(1, d.response_started_count());
9032 EXPECT_EQ(0, d.received_redirect_count());
9033
9034 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:009035 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:509036 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
9037}
9038
mkwst0c5eab872014-11-21 14:18:549039class URLRequestTestReferrerPolicy : public URLRequestTest {
9040 public:
Chris Watkins7a41d3552017-12-01 02:13:279041 URLRequestTestReferrerPolicy() = default;
mkwst0c5eab872014-11-21 14:18:549042
tommycli59a63432015-11-06 00:10:559043 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
9044 origin_server_.reset(new EmbeddedTestServer(type));
9045 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
9046 origin_server_->AddDefaultHandlers(
9047 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9048 } else {
9049 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9050 }
mkwst0c5eab872014-11-21 14:18:549051 ASSERT_TRUE(origin_server_->Start());
9052 }
9053
tommycli59a63432015-11-06 00:10:559054 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
9055 net::EmbeddedTestServer::Type dest_type) {
9056 origin_server_.reset(new EmbeddedTestServer(origin_type));
9057 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9058 origin_server_->AddDefaultHandlers(
9059 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9060 } else {
9061 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9062 }
mkwst0c5eab872014-11-21 14:18:549063 ASSERT_TRUE(origin_server_->Start());
9064
tommycli59a63432015-11-06 00:10:559065 destination_server_.reset(new EmbeddedTestServer(dest_type));
9066 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
9067 destination_server_->AddDefaultHandlers(
9068 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9069 } else {
9070 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
9071 }
mkwst0c5eab872014-11-21 14:18:549072 ASSERT_TRUE(destination_server_->Start());
9073 }
9074
9075 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
9076 const GURL& referrer,
9077 const GURL& expected) {
9078 // Create and execute the request: we'll only have a |destination_server_|
9079 // if the origins are meant to be distinct. Otherwise, we'll use the
9080 // |origin_server_| for both endpoints.
9081 GURL destination_url =
tommycli59a63432015-11-06 00:10:559082 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
9083 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:549084 GURL origin_url =
tommycli59a63432015-11-06 00:10:559085 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:549086
9087 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:169088 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
9089 origin_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
mkwst0c5eab872014-11-21 14:18:549090 req->set_referrer_policy(policy);
9091 req->SetReferrer(referrer.spec());
9092 req->Start();
9093 base::RunLoop().Run();
9094
9095 EXPECT_EQ(1, d.response_started_count());
9096 EXPECT_EQ(1, d.received_redirect_count());
9097 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:509098 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:549099 EXPECT_EQ(200, req->response_headers()->response_code());
9100
9101 EXPECT_EQ(expected.spec(), req->referrer());
9102 if (expected.is_empty())
9103 EXPECT_EQ("None", d.data_received());
9104 else
9105 EXPECT_EQ(expected.spec(), d.data_received());
9106 }
9107
tommycli59a63432015-11-06 00:10:559108 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:549109
9110 private:
danakj8522a25b2016-04-16 00:17:369111 std::unique_ptr<EmbeddedTestServer> origin_server_;
9112 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:549113};
9114
9115TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:559116 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:549117
estarkc8ccba82017-06-13 22:37:409118 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549119 VerifyReferrerAfterRedirect(
9120 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409121 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549122
9123 VerifyReferrerAfterRedirect(
9124 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409125 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549126
9127 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409128 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549129
estarkc8ccba82017-06-13 22:37:409130 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9131 referrer);
9132
9133 // The original referrer set on the request is expected to obey the referrer
9134 // policy and already be stripped to the origin; thus this test case just
9135 // checks that this policy doesn't cause the referrer to change when following
9136 // a redirect.
9137 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9138 referrer.GetOrigin());
9139
9140 VerifyReferrerAfterRedirect(
9141 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9142 referrer);
9143
9144 // The original referrer set on the request is expected to obey the referrer
9145 // policy and already be stripped to the origin; thus this test case just
9146 // checks that this policy doesn't cause the referrer to change when following
9147 // a redirect.
9148 VerifyReferrerAfterRedirect(
9149 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9150 referrer.GetOrigin(), referrer.GetOrigin());
9151
9152 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549153}
9154
tommycli59a63432015-11-06 00:10:559155TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
9156 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9157 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409158 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549159
9160 VerifyReferrerAfterRedirect(
9161 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409162 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549163
9164 VerifyReferrerAfterRedirect(
9165 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409166 referrer, referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549167
9168 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409169 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
9170 referrer.GetOrigin());
mkwst0c5eab872014-11-21 14:18:549171
estarkc8ccba82017-06-13 22:37:409172 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9173 referrer);
9174
9175 // The original referrer set on the request is expected to obey the referrer
9176 // policy and already be stripped to the origin; thus this test case just
9177 // checks that this policy doesn't cause the referrer to change when following
9178 // a redirect.
9179 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9180 referrer.GetOrigin());
9181
9182 VerifyReferrerAfterRedirect(
9183 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9184
9185 // The original referrer set on the request is expected to obey the referrer
9186 // policy and already be stripped to the origin; thus this test case just
9187 // checks that this policy doesn't cause the referrer to change when following
9188 // a redirect.
9189 VerifyReferrerAfterRedirect(
9190 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9191 referrer.GetOrigin(), referrer.GetOrigin());
9192
9193 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549194}
9195
9196TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:559197 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409198 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549199
9200 VerifyReferrerAfterRedirect(
9201 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409202 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549203
9204 VerifyReferrerAfterRedirect(
9205 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409206 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549207
9208 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409209 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549210
estarkc8ccba82017-06-13 22:37:409211 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9212 referrer);
9213
9214 // The original referrer set on the request is expected to obey the referrer
9215 // policy and already be stripped to the origin; thus this test case just
9216 // checks that this policy doesn't cause the referrer to change when following
9217 // a redirect.
9218 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9219 referrer.GetOrigin());
9220
9221 VerifyReferrerAfterRedirect(
9222 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer,
9223 referrer);
9224
9225 // The original referrer set on the request is expected to obey the referrer
9226 // policy and already be stripped to the origin; thus this test case just
9227 // checks that this policy doesn't cause the referrer to change when following
9228 // a redirect.
9229 VerifyReferrerAfterRedirect(
9230 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9231 referrer.GetOrigin(), referrer.GetOrigin());
9232
9233 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549234}
9235
tommycli59a63432015-11-06 00:10:559236TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
9237 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9238 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409239 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549240
9241 VerifyReferrerAfterRedirect(
9242 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409243 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549244
9245 VerifyReferrerAfterRedirect(
9246 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409247 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549248
9249 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409250 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559251 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549252
estarkc8ccba82017-06-13 22:37:409253 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9254 referrer);
9255
9256 // The original referrer set on the request is expected to obey the referrer
9257 // policy and already be stripped to the origin; thus this test case just
9258 // checks that this policy doesn't cause the referrer to change when following
9259 // a redirect.
9260 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9261 referrer.GetOrigin());
9262
9263 VerifyReferrerAfterRedirect(
9264 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9265
9266 // The original referrer set on the request is expected to obey the referrer
9267 // policy and already be stripped to the origin; thus this test case just
9268 // checks that this policy doesn't cause the referrer to change when following
9269 // a redirect.
9270 VerifyReferrerAfterRedirect(
9271 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9272 referrer.GetOrigin(), referrer.GetOrigin());
9273
9274 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549275}
9276
tommycli59a63432015-11-06 00:10:559277TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
9278 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
9279 net::EmbeddedTestServer::TYPE_HTTPS);
estarkc8ccba82017-06-13 22:37:409280 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549281
9282 VerifyReferrerAfterRedirect(
9283 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409284 referrer, referrer);
mkwst0c5eab872014-11-21 14:18:549285
9286 VerifyReferrerAfterRedirect(
9287 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409288 referrer, origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549289
9290 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409291 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559292 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549293
estarkc8ccba82017-06-13 22:37:409294 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9295 referrer);
9296
9297 // The original referrer set on the request is expected to obey the referrer
9298 // policy and already be stripped to the origin; thus this test case just
9299 // checks that this policy doesn't cause the referrer to change when following
9300 // a redirect.
9301 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9302 referrer.GetOrigin());
9303
9304 VerifyReferrerAfterRedirect(
9305 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9306
9307 // The original referrer set on the request is expected to obey the referrer
9308 // policy and already be stripped to the origin; thus this test case just
9309 // checks that this policy doesn't cause the referrer to change when following
9310 // a redirect.
9311 VerifyReferrerAfterRedirect(
9312 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9313 referrer.GetOrigin(), referrer.GetOrigin());
9314
9315 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549316}
9317
tommycli59a63432015-11-06 00:10:559318TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
9319 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
9320 net::EmbeddedTestServer::TYPE_HTTP);
estarkc8ccba82017-06-13 22:37:409321 GURL referrer = origin_server()->GetURL("/path/to/file.html");
mkwst0c5eab872014-11-21 14:18:549322
9323 VerifyReferrerAfterRedirect(
9324 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
estarkc8ccba82017-06-13 22:37:409325 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549326
9327 VerifyReferrerAfterRedirect(
9328 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
estarkc8ccba82017-06-13 22:37:409329 referrer, GURL());
mkwst0c5eab872014-11-21 14:18:549330
9331 VerifyReferrerAfterRedirect(
estarkc8ccba82017-06-13 22:37:409332 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN, referrer,
tommycli59a63432015-11-06 00:10:559333 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:549334
estarkc8ccba82017-06-13 22:37:409335 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER, referrer,
9336 referrer);
9337
9338 // The original referrer set on the request is expected to obey the referrer
9339 // policy and already be stripped to the origin; thus this test case just
9340 // checks that this policy doesn't cause the referrer to change when following
9341 // a redirect.
9342 VerifyReferrerAfterRedirect(URLRequest::ORIGIN, referrer.GetOrigin(),
9343 referrer.GetOrigin());
9344
9345 VerifyReferrerAfterRedirect(
9346 URLRequest::CLEAR_REFERRER_ON_TRANSITION_CROSS_ORIGIN, referrer, GURL());
9347
9348 // The original referrer set on the request is expected to obey the referrer
9349 // policy and already be stripped to the origin, though it should be
9350 // subsequently cleared during the downgrading redirect.
9351 VerifyReferrerAfterRedirect(
9352 URLRequest::ORIGIN_CLEAR_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
9353 referrer.GetOrigin(), GURL());
9354
9355 VerifyReferrerAfterRedirect(URLRequest::NO_REFERRER, GURL(), GURL());
mkwst0c5eab872014-11-21 14:18:549356}
9357
[email protected]73e0bba2009-02-19 22:57:099358class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:509359 public:
fdorayf33fede2017-05-11 21:18:109360 HTTPSRequestTest() : default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:099361 default_context_.set_network_delegate(&default_network_delegate_);
9362 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:509363 }
Martijn Croonenb1383da2017-10-11 11:56:359364 ~HTTPSRequestTest() override {
9365 SetTransportSecurityStateSourceForTesting(nullptr);
9366 }
[email protected]87a09a92011-07-14 15:50:509367
9368 protected:
[email protected]ceefd7fd2012-11-29 00:36:249369 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:099370 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:469371};
9372
[email protected]c044616e2013-02-20 02:01:269373TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:559374 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9375 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229376 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119377 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:469378
[email protected]ea224582008-12-07 20:25:469379 TestDelegate d;
9380 {
danakj8522a25b2016-04-16 00:17:369381 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169382 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9383 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199384 r->Start();
9385 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:469386
[email protected]255620da2013-08-19 13:14:299387 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:469388
9389 EXPECT_EQ(1, d.response_started_count());
9390 EXPECT_FALSE(d.received_data_before_response());
9391 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199392 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:199393 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199394 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:199395 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199396 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:469397 }
[email protected]ea224582008-12-07 20:25:469398}
9399
[email protected]5774ada2010-07-15 06:30:549400TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:559401 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9402 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9403 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229404 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119405 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339406
9407 bool err_allowed = true;
9408 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9409 TestDelegate d;
9410 {
9411 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369412 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169413 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9414 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339415
[email protected]f7022f32014-08-21 16:32:199416 r->Start();
9417 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339418
[email protected]255620da2013-08-19 13:14:299419 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339420
9421 EXPECT_EQ(1, d.response_started_count());
9422 EXPECT_FALSE(d.received_data_before_response());
9423 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179424 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339425 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199426 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179427 } else {
[email protected]bacff652009-03-31 17:50:339428 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179429 }
[email protected]bacff652009-03-31 17:50:339430 }
9431 }
9432}
9433
[email protected]5774ada2010-07-15 06:30:549434TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:559435 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9436 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
9437 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229438 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:119439 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:339440
9441 // Iterate from false to true, just so that we do the opposite of the
9442 // previous test in order to increase test coverage.
9443 bool err_allowed = false;
9444 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
9445 TestDelegate d;
9446 {
9447 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:369448 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169449 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9450 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]bacff652009-03-31 17:50:339451
[email protected]f7022f32014-08-21 16:32:199452 r->Start();
9453 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:339454
[email protected]255620da2013-08-19 13:14:299455 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:339456
9457 EXPECT_EQ(1, d.response_started_count());
9458 EXPECT_FALSE(d.received_data_before_response());
9459 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:179460 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:339461 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:199462 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:179463 } else {
[email protected]bacff652009-03-31 17:50:339464 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:179465 }
[email protected]bacff652009-03-31 17:50:339466 }
9467 }
9468}
[email protected]73e0bba2009-02-19 22:57:099469
tommycli59a63432015-11-06 00:10:559470// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
9471// security state. (see http://crbug.com/550977).
9472#if !defined(OS_IOS)
Martijn Croonenb1383da2017-10-11 11:56:359473// This tests that a load of a domain with preloaded HSTS and HPKP with a
9474// certificate error sets the |certificate_errors_are_fatal| flag correctly.
9475// This flag will cause the interstitial to be fatal.
[email protected]316c1e5e2012-09-12 15:17:449476TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359477 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9478
tommycli59a63432015-11-06 00:10:559479 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9480 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9481 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449482 ASSERT_TRUE(test_server.Start());
9483
Martijn Croonenb1383da2017-10-11 11:56:359484 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9485 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9486 // means that we have to use a MockHostResolver in order to direct
9487 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9488 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449489
9490 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249491 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449492 TestURLRequestContext context(true);
9493 context.set_network_delegate(&network_delegate);
9494 context.set_host_resolver(&host_resolver);
9495 TransportSecurityState transport_security_state;
9496 context.set_transport_security_state(&transport_security_state);
9497 context.Init();
9498
9499 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369500 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359501 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369502 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169503 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449504
[email protected]f7022f32014-08-21 16:32:199505 r->Start();
9506 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449507
[email protected]255620da2013-08-19 13:14:299508 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449509
9510 EXPECT_EQ(1, d.response_started_count());
9511 EXPECT_FALSE(d.received_data_before_response());
9512 EXPECT_TRUE(d.have_certificate_errors());
9513 EXPECT_TRUE(d.certificate_errors_are_fatal());
9514}
9515
9516// This tests that cached HTTPS page loads do not cause any updates to the
9517// TransportSecurityState.
9518TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
Martijn Croonenb1383da2017-10-11 11:56:359519 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
9520
[email protected]316c1e5e2012-09-12 15:17:449521 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
9522 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:559523 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9524 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
9525 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:449526 ASSERT_TRUE(test_server.Start());
9527
Martijn Croonenb1383da2017-10-11 11:56:359528 // We require that the URL be hsts-hpkp-preloaded.test. This is a test domain
9529 // that has a preloaded HSTS+HPKP entry in the TransportSecurityState. This
9530 // means that we have to use a MockHostResolver in order to direct
9531 // hsts-hpkp-preloaded.test to the testserver. By default, MockHostResolver
9532 // maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:449533
9534 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:249535 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:449536 TestURLRequestContext context(true);
9537 context.set_network_delegate(&network_delegate);
9538 context.set_host_resolver(&host_resolver);
9539 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:269540
martijnc0d6b622015-06-30 19:14:409541 TransportSecurityState::STSState static_sts_state;
9542 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269543 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359544 "hsts-hpkp-preloaded.test", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:449545 context.set_transport_security_state(&transport_security_state);
9546 context.Init();
9547
martijnc0d6b622015-06-30 19:14:409548 TransportSecurityState::STSState dynamic_sts_state;
9549 TransportSecurityState::PKPState dynamic_pkp_state;
Martijn Croonenb1383da2017-10-11 11:56:359550 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
9551 "hsts-hpkp-preloaded.test", &dynamic_sts_state));
9552 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
9553 "hsts-hpkp-preloaded.test", &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269554
[email protected]316c1e5e2012-09-12 15:17:449555 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369556 std::unique_ptr<URLRequest> r(context.CreateRequest(
Martijn Croonenb1383da2017-10-11 11:56:359557 GURL(base::StringPrintf("https://hsts-hpkp-preloaded.test:%d",
davidben151423e2015-03-23 18:48:369558 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169559 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449560
[email protected]f7022f32014-08-21 16:32:199561 r->Start();
9562 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449563
[email protected]255620da2013-08-19 13:14:299564 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449565
9566 EXPECT_EQ(1, d.response_started_count());
9567 EXPECT_FALSE(d.received_data_before_response());
9568 EXPECT_TRUE(d.have_certificate_errors());
9569 EXPECT_TRUE(d.certificate_errors_are_fatal());
9570
[email protected]9e6968d2014-05-07 21:46:269571 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:409572 TransportSecurityState::STSState new_static_sts_state;
9573 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:269574 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Martijn Croonenb1383da2017-10-11 11:56:359575 "hsts-hpkp-preloaded.test", &new_static_sts_state,
9576 &new_static_pkp_state));
martijnc0d6b622015-06-30 19:14:409577 TransportSecurityState::STSState new_dynamic_sts_state;
9578 TransportSecurityState::PKPState new_dynamic_pkp_state;
9579 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
Martijn Croonenb1383da2017-10-11 11:56:359580 "hsts-hpkp-preloaded.test", &new_dynamic_sts_state));
martijnc0d6b622015-06-30 19:14:409581 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
Martijn Croonenb1383da2017-10-11 11:56:359582 "hsts-hpkp-preloaded.test", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:269583
martijnc0d6b622015-06-30 19:14:409584 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
9585 EXPECT_EQ(new_static_sts_state.include_subdomains,
9586 static_sts_state.include_subdomains);
9587 EXPECT_EQ(new_static_pkp_state.include_subdomains,
9588 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:489589 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
9590 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
9591 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:449592}
9593
[email protected]8ccc69f2012-11-28 19:52:149594// Make sure HSTS preserves a POST request's method and body.
9595TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
9596 static const char kData[] = "hello world";
9597
tommycli59a63432015-11-06 00:10:559598 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9599 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229600 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:149601 ASSERT_TRUE(test_server.Start());
9602
9603
9604 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9605 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:559606 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:229607 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:149608 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:149609
9610 // Force https for www.somewhere.com.
9611 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:209612 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
9613 bool include_subdomains = false;
9614 transport_security_state.AddHSTS("www.somewhere.com", expiry,
9615 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:149616
9617 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9618
9619 TestURLRequestContext context(true);
9620 context.set_host_resolver(&host_resolver);
9621 context.set_transport_security_state(&transport_security_state);
9622 context.set_network_delegate(&network_delegate);
9623 context.Init();
9624
9625 TestDelegate d;
9626 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
9627 // cause a certificate error. Ignore the error.
9628 d.set_allow_certificate_errors(true);
9629
danakj8522a25b2016-04-16 00:17:369630 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:199631 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:369632 test_server.host_port_pair().port())),
rhalavatib7bd7c792017-04-27 05:25:169633 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:199634 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:079635 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:149636
[email protected]f7022f32014-08-21 16:32:199637 req->Start();
[email protected]255620da2013-08-19 13:14:299638 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:149639
[email protected]f7022f32014-08-21 16:32:199640 EXPECT_EQ("https", req->url().scheme());
9641 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:149642 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:409643
9644 LoadTimingInfo load_timing_info;
9645 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
9646 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
9647 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:149648}
9649
rob4e0be1f2014-09-11 23:40:229650// Make sure that the CORS headers are added to cross-origin HSTS redirects.
9651TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
9652 static const char kOriginHeaderValue[] = "http://www.example.com";
9653
tommycli59a63432015-11-06 00:10:559654 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9655 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:229656 ASSERT_TRUE(test_server.Start());
9657
9658 // Per spec, TransportSecurityState expects a domain name, rather than an IP
9659 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:559660 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
9661 // default.
rob4e0be1f2014-09-11 23:40:229662 MockHostResolver host_resolver;
9663
9664 TransportSecurityState transport_security_state;
9665 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
9666 bool include_subdomains = false;
9667 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
9668
9669 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
9670
9671 MockCertVerifier cert_verifier;
9672 cert_verifier.set_default_result(OK);
9673
9674 TestURLRequestContext context(true);
9675 context.set_host_resolver(&host_resolver);
9676 context.set_transport_security_state(&transport_security_state);
9677 context.set_network_delegate(&network_delegate);
9678 context.set_cert_verifier(&cert_verifier);
9679 context.Init();
9680
9681 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
9682 test_server.host_port_pair().port()));
9683 url::Replacements<char> replacements;
9684 const char kNewScheme[] = "https";
9685 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
9686 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
9687
9688 TestDelegate d;
9689 // Quit on redirect to allow response header inspection upon redirect.
9690 d.set_quit_on_redirect(true);
9691
rhalavatib7bd7c792017-04-27 05:25:169692 std::unique_ptr<URLRequest> req(context.CreateRequest(
9693 hsts_http_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
rob4e0be1f2014-09-11 23:40:229694 // Set Origin header to simulate a cross-origin request.
9695 HttpRequestHeaders request_headers;
9696 request_headers.SetHeader("Origin", kOriginHeaderValue);
9697 req->SetExtraRequestHeaders(request_headers);
9698
9699 req->Start();
9700 base::RunLoop().Run();
9701
9702 EXPECT_EQ(1, d.received_redirect_count());
9703
9704 const HttpResponseHeaders* headers = req->response_headers();
9705 std::string redirect_location;
9706 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9707 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9708
9709 std::string received_cors_header;
9710 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9711 &received_cors_header));
9712 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9713}
9714
[email protected]316c1e5e2012-09-12 15:17:449715namespace {
9716
9717class SSLClientAuthTestDelegate : public TestDelegate {
9718 public:
9719 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
9720 }
dchengb03027d2014-10-21 12:00:209721 void OnCertificateRequested(URLRequest* request,
9722 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449723 on_certificate_requested_count_++;
Gabriel Charette53a9ef812017-07-26 12:36:239724 base::RunLoop::QuitCurrentWhenIdleDeprecated();
[email protected]316c1e5e2012-09-12 15:17:449725 }
9726 int on_certificate_requested_count() {
9727 return on_certificate_requested_count_;
9728 }
9729 private:
9730 int on_certificate_requested_count_;
9731};
9732
David Benjamin76a40ad2018-02-24 22:22:089733class TestSSLPrivateKey : public SSLPrivateKey {
9734 public:
9735 explicit TestSSLPrivateKey(scoped_refptr<SSLPrivateKey> key)
9736 : key_(std::move(key)) {}
9737
9738 void set_fail_signing(bool fail_signing) { fail_signing_ = fail_signing; }
9739 int sign_count() const { return sign_count_; }
9740
9741 std::vector<uint16_t> GetAlgorithmPreferences() override {
9742 return key_->GetAlgorithmPreferences();
9743 }
9744 void Sign(uint16_t algorithm,
9745 base::span<const uint8_t> input,
David Benjamin8f2d2c12018-02-27 00:08:269746 SignCallback callback) override {
David Benjamin76a40ad2018-02-24 22:22:089747 sign_count_++;
9748 if (fail_signing_) {
9749 base::ThreadTaskRunnerHandle::Get()->PostTask(
David Benjamin8f2d2c12018-02-27 00:08:269750 FROM_HERE, base::BindOnce(std::move(callback),
9751 ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED,
9752 std::vector<uint8_t>()));
David Benjamin76a40ad2018-02-24 22:22:089753 } else {
David Benjamin8f2d2c12018-02-27 00:08:269754 key_->Sign(algorithm, input, std::move(callback));
David Benjamin76a40ad2018-02-24 22:22:089755 }
9756 }
9757
9758 private:
9759 ~TestSSLPrivateKey() override = default;
9760
9761 scoped_refptr<SSLPrivateKey> key_;
9762 bool fail_signing_ = false;
9763 int sign_count_ = 0;
9764};
9765
[email protected]316c1e5e2012-09-12 15:17:449766} // namespace
9767
9768// TODO(davidben): Test the rest of the code. Specifically,
9769// - Filtering which certificates to select.
[email protected]316c1e5e2012-09-12 15:17:449770// - Getting a certificate request in an SSL renegotiation sending the
9771// HTTP request.
David Benjamin76a40ad2018-02-24 22:22:089772TEST_F(HTTPSRequestTest, ClientAuthNoCertificate) {
tommycli59a63432015-11-06 00:10:559773 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9774 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129775 ssl_config.client_cert_type =
9776 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
David Benjamin76a40ad2018-02-24 22:22:089777 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
tommycli59a63432015-11-06 00:10:559778 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229779 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449780 ASSERT_TRUE(test_server.Start());
9781
9782 SSLClientAuthTestDelegate d;
9783 {
danakj8522a25b2016-04-16 00:17:369784 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:169785 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9786 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:449787
[email protected]f7022f32014-08-21 16:32:199788 r->Start();
9789 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449790
[email protected]255620da2013-08-19 13:14:299791 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449792
9793 EXPECT_EQ(1, d.on_certificate_requested_count());
9794 EXPECT_FALSE(d.received_data_before_response());
9795 EXPECT_EQ(0, d.bytes_received());
9796
9797 // Send no certificate.
9798 // TODO(davidben): Get temporary client cert import (with keys) working on
9799 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549800 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449801
[email protected]255620da2013-08-19 13:14:299802 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449803
David Benjamin76a40ad2018-02-24 22:22:089804 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:449805 EXPECT_EQ(1, d.response_started_count());
9806 EXPECT_FALSE(d.received_data_before_response());
9807 EXPECT_NE(0, d.bytes_received());
9808 }
9809}
9810
David Benjamin76a40ad2018-02-24 22:22:089811TEST_F(HTTPSRequestTest, ClientAuth) {
9812 std::unique_ptr<FakeClientCertIdentity> identity =
9813 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9814 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9815 ASSERT_TRUE(identity);
9816 scoped_refptr<TestSSLPrivateKey> private_key =
9817 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9818
9819 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9820 net::SSLServerConfig ssl_config;
9821 ssl_config.client_cert_type =
9822 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9823 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9824 test_server.AddDefaultHandlers(
9825 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9826 ASSERT_TRUE(test_server.Start());
9827
9828 {
9829 SSLClientAuthTestDelegate d;
9830 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9831 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9832 TRAFFIC_ANNOTATION_FOR_TESTS));
9833
9834 r->Start();
9835 EXPECT_TRUE(r->is_pending());
9836
9837 base::RunLoop().Run();
9838
9839 EXPECT_EQ(1, d.on_certificate_requested_count());
9840 EXPECT_FALSE(d.received_data_before_response());
9841 EXPECT_EQ(0, d.bytes_received());
9842
9843 // Send a certificate.
9844 r->ContinueWithCertificate(identity->certificate(), private_key);
9845
9846 base::RunLoop().Run();
9847
9848 EXPECT_EQ(OK, d.request_status());
9849 EXPECT_EQ(1, d.response_started_count());
9850 EXPECT_FALSE(d.received_data_before_response());
9851 EXPECT_NE(0, d.bytes_received());
9852
9853 // The private key should have been used.
9854 EXPECT_EQ(1, private_key->sign_count());
9855 }
9856
9857 // Close all connections and clear the session cache to force a new handshake.
9858 default_context_.http_transaction_factory()
9859 ->GetSession()
9860 ->CloseAllConnections();
9861 SSLClientSocket::ClearSessionCache();
9862
9863 // Connecting again should not call OnCertificateRequested. The identity is
9864 // taken from the client auth cache.
9865 {
9866 SSLClientAuthTestDelegate d;
9867 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9868 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9869 TRAFFIC_ANNOTATION_FOR_TESTS));
9870
9871 r->Start();
9872 EXPECT_TRUE(r->is_pending());
9873
9874 base::RunLoop().Run();
9875
9876 EXPECT_EQ(OK, d.request_status());
9877 EXPECT_EQ(0, d.on_certificate_requested_count());
9878 EXPECT_FALSE(d.received_data_before_response());
9879 EXPECT_EQ(1, d.response_started_count());
9880 EXPECT_FALSE(d.received_data_before_response());
9881 EXPECT_NE(0, d.bytes_received());
9882
9883 // The private key should have been used.
9884 EXPECT_EQ(2, private_key->sign_count());
9885 }
9886}
9887
9888// Test that private keys that fail to sign anything get evicted from the cache.
9889TEST_F(HTTPSRequestTest, ClientAuthFailSigning) {
9890 std::unique_ptr<FakeClientCertIdentity> identity =
9891 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9892 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9893 ASSERT_TRUE(identity);
9894 scoped_refptr<TestSSLPrivateKey> private_key =
9895 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9896 private_key->set_fail_signing(true);
9897
9898 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9899 net::SSLServerConfig ssl_config;
9900 ssl_config.client_cert_type =
9901 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9902 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9903 test_server.AddDefaultHandlers(
9904 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9905 ASSERT_TRUE(test_server.Start());
9906
9907 {
9908 SSLClientAuthTestDelegate d;
9909 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9910 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9911 TRAFFIC_ANNOTATION_FOR_TESTS));
9912
9913 r->Start();
9914 EXPECT_TRUE(r->is_pending());
9915 base::RunLoop().Run();
9916
9917 EXPECT_EQ(1, d.on_certificate_requested_count());
9918 EXPECT_FALSE(d.received_data_before_response());
9919 EXPECT_EQ(0, d.bytes_received());
9920
9921 // Send a certificate.
9922 r->ContinueWithCertificate(identity->certificate(), private_key);
9923 base::RunLoop().Run();
9924
9925 // The private key cannot sign anything, so we report an error.
9926 EXPECT_EQ(ERR_SSL_CLIENT_AUTH_SIGNATURE_FAILED, d.request_status());
9927 EXPECT_EQ(1, d.response_started_count());
9928 EXPECT_FALSE(d.received_data_before_response());
9929 EXPECT_EQ(0, d.bytes_received());
9930
9931 // The private key should have been used.
9932 EXPECT_EQ(1, private_key->sign_count());
9933 }
9934
9935 // Close all connections and clear the session cache to force a new handshake.
9936 default_context_.http_transaction_factory()
9937 ->GetSession()
9938 ->CloseAllConnections();
9939 SSLClientSocket::ClearSessionCache();
9940
9941 // The bad identity should have been evicted from the cache, so connecting
9942 // again should call OnCertificateRequested again.
9943 {
9944 SSLClientAuthTestDelegate d;
9945 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9946 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9947 TRAFFIC_ANNOTATION_FOR_TESTS));
9948
9949 r->Start();
9950 EXPECT_TRUE(r->is_pending());
9951
9952 base::RunLoop().Run();
9953
9954 EXPECT_EQ(1, d.on_certificate_requested_count());
9955 EXPECT_FALSE(d.received_data_before_response());
9956 EXPECT_EQ(0, d.bytes_received());
9957
9958 // There should have been no additional uses of the private key.
9959 EXPECT_EQ(1, private_key->sign_count());
9960 }
9961}
9962
9963// Test that cached private keys that fail to sign anything trigger a
9964// retry. This is so we handle unplugged smartcards
9965// gracefully. https://crbug.com/813022.
9966TEST_F(HTTPSRequestTest, ClientAuthFailSigningRetry) {
9967 std::unique_ptr<FakeClientCertIdentity> identity =
9968 FakeClientCertIdentity::CreateFromCertAndKeyFiles(
9969 GetTestCertsDirectory(), "client_1.pem", "client_1.pk8");
9970 ASSERT_TRUE(identity);
9971 scoped_refptr<TestSSLPrivateKey> private_key =
9972 base::MakeRefCounted<TestSSLPrivateKey>(identity->ssl_private_key());
9973
9974 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9975 net::SSLServerConfig ssl_config;
9976 ssl_config.client_cert_type =
9977 SSLServerConfig::ClientCertType::REQUIRE_CLIENT_CERT;
9978 test_server.SetSSLConfig(EmbeddedTestServer::CERT_OK, ssl_config);
9979 test_server.AddDefaultHandlers(
9980 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9981 ASSERT_TRUE(test_server.Start());
9982
9983 // Connect with a client certificate to put it in the client auth cache.
9984 {
9985 SSLClientAuthTestDelegate d;
9986 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
9987 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
9988 TRAFFIC_ANNOTATION_FOR_TESTS));
9989
9990 r->Start();
9991 EXPECT_TRUE(r->is_pending());
9992
9993 base::RunLoop().Run();
9994
9995 EXPECT_EQ(1, d.on_certificate_requested_count());
9996 EXPECT_FALSE(d.received_data_before_response());
9997 EXPECT_EQ(0, d.bytes_received());
9998
9999 r->ContinueWithCertificate(identity->certificate(), private_key);
10000 base::RunLoop().Run();
10001
10002 EXPECT_EQ(OK, d.request_status());
10003 EXPECT_EQ(1, d.response_started_count());
10004 EXPECT_FALSE(d.received_data_before_response());
10005 EXPECT_NE(0, d.bytes_received());
10006
10007 // The private key should have been used.
10008 EXPECT_EQ(1, private_key->sign_count());
10009 }
10010
10011 // Close all connections and clear the session cache to force a new handshake.
10012 default_context_.http_transaction_factory()
10013 ->GetSession()
10014 ->CloseAllConnections();
10015 SSLClientSocket::ClearSessionCache();
10016
10017 // Cause the private key to fail. Connecting again should attempt to use it,
10018 // notice the failure, and then request a new identity via
10019 // OnCertificateRequested.
10020 private_key->set_fail_signing(true);
10021
10022 {
10023 SSLClientAuthTestDelegate d;
10024 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
10025 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
10026 TRAFFIC_ANNOTATION_FOR_TESTS));
10027
10028 r->Start();
10029 EXPECT_TRUE(r->is_pending());
10030
10031 base::RunLoop().Run();
10032
10033 // There was an additional signing call on the private key (the one which
10034 // failed).
10035 EXPECT_EQ(2, private_key->sign_count());
10036
10037 // That caused another OnCertificateRequested call.
10038 EXPECT_EQ(1, d.on_certificate_requested_count());
10039 EXPECT_FALSE(d.received_data_before_response());
10040 EXPECT_EQ(0, d.bytes_received());
10041 }
10042}
10043
[email protected]316c1e5e2012-09-12 15:17:4410044TEST_F(HTTPSRequestTest, ResumeTest) {
10045 // Test that we attempt a session resume when making two connections to the
10046 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:2210047 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410048 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210049 SpawnedTestServer test_server(
10050 SpawnedTestServer::TYPE_HTTPS,
10051 ssl_options,
10052 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410053 ASSERT_TRUE(test_server.Start());
10054
10055 SSLClientSocket::ClearSessionCache();
10056
10057 {
10058 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610059 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610060 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10061 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410062
[email protected]f7022f32014-08-21 16:32:1910063 r->Start();
10064 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410065
[email protected]255620da2013-08-19 13:14:2910066 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410067
10068 EXPECT_EQ(1, d.response_started_count());
10069 }
10070
10071 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10072 CloseAllConnections();
10073
10074 {
10075 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610076 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610077 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10078 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410079
[email protected]f7022f32014-08-21 16:32:1910080 r->Start();
10081 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410082
[email protected]255620da2013-08-19 13:14:2910083 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410084
10085 // The response will look like;
10086 // insert abc
10087 // lookup abc
10088 // insert xyz
10089 //
10090 // With a newline at the end which makes the split think that there are
10091 // four lines.
10092
10093 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:2910094 std::vector<std::string> lines = base::SplitString(
10095 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410096 ASSERT_EQ(4u, lines.size()) << d.data_received();
10097
10098 std::string session_id;
10099
10100 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910101 std::vector<std::string> parts = base::SplitString(
10102 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:4410103 ASSERT_EQ(2u, parts.size());
10104 if (i == 0) {
10105 EXPECT_EQ("insert", parts[0]);
10106 session_id = parts[1];
10107 } else {
10108 EXPECT_EQ("lookup", parts[0]);
10109 EXPECT_EQ(session_id, parts[1]);
10110 }
10111 }
10112 }
10113}
10114
Adam Langley32352ad2014-10-14 22:31:0010115// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
10116// the result of fetching "ssl-session-cache" from the test server, indicates
10117// that exactly two different sessions were inserted, with no lookups etc.
10118static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:2910119 std::vector<std::string> lines = base::SplitString(
10120 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010121 ASSERT_EQ(3u, lines.size()) << session_info;
10122
10123 std::string session_id;
10124 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:2910125 std::vector<std::string> parts = base::SplitString(
10126 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:0010127 ASSERT_EQ(2u, parts.size());
10128 EXPECT_EQ("insert", parts[0]);
10129 if (i == 0) {
10130 session_id = parts[1];
10131 } else {
10132 EXPECT_NE(session_id, parts[1]);
10133 }
10134 }
10135}
10136
[email protected]316c1e5e2012-09-12 15:17:4410137TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
10138 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
10139 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:2210140 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:4410141 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:2210142 SpawnedTestServer test_server(
10143 SpawnedTestServer::TYPE_HTTPS,
10144 ssl_options,
10145 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:4410146 ASSERT_TRUE(test_server.Start());
10147
10148 SSLClientSocket::ClearSessionCache();
10149
10150 {
10151 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610152 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610153 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10154 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410155
[email protected]f7022f32014-08-21 16:32:1910156 r->Start();
10157 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410158
[email protected]255620da2013-08-19 13:14:2910159 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410160
10161 EXPECT_EQ(1, d.response_started_count());
10162 }
10163
10164 // Now create a new HttpCache with a different ssl_session_cache_shard value.
mmenke6ddfbea2017-05-31 21:48:4110165 HttpNetworkSession::Context session_context;
10166 session_context.host_resolver = default_context_.host_resolver();
10167 session_context.cert_verifier = default_context_.cert_verifier();
10168 session_context.transport_security_state =
10169 default_context_.transport_security_state();
10170 session_context.cert_transparency_verifier =
rsleevid6de8302016-06-21 01:33:2010171 default_context_.cert_transparency_verifier();
mmenke6ddfbea2017-05-31 21:48:4110172 session_context.ct_policy_enforcer = default_context_.ct_policy_enforcer();
Lily Houghton8c2f97d2018-01-22 05:06:5910173 session_context.proxy_resolution_service = default_context_.proxy_resolution_service();
mmenke6ddfbea2017-05-31 21:48:4110174 session_context.ssl_config_service = default_context_.ssl_config_service();
10175 session_context.http_auth_handler_factory =
[email protected]316c1e5e2012-09-12 15:17:4410176 default_context_.http_auth_handler_factory();
mmenke6ddfbea2017-05-31 21:48:4110177 session_context.http_server_properties =
10178 default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:4410179
mmenke6ddfbea2017-05-31 21:48:4110180 HttpNetworkSession network_session(HttpNetworkSession::Params(),
10181 session_context);
zhongyi4928bd52017-02-08 02:16:2710182 std::unique_ptr<HttpCache> cache(
10183 new HttpCache(&network_session, HttpCache::DefaultBackend::InMemory(0),
10184 false /* is_main_cache */));
[email protected]316c1e5e2012-09-12 15:17:4410185
10186 default_context_.set_http_transaction_factory(cache.get());
10187
10188 {
10189 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610190 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610191 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10192 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]316c1e5e2012-09-12 15:17:4410193
[email protected]f7022f32014-08-21 16:32:1910194 r->Start();
10195 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:4410196
[email protected]255620da2013-08-19 13:14:2910197 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:4410198
10199 // The response will look like;
10200 // insert abc
10201 // insert xyz
10202 //
10203 // With a newline at the end which makes the split think that there are
10204 // three lines.
10205
10206 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010207 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:4410208 }
10209}
10210
[email protected]48d2b7c52014-06-27 01:16:5510211class HTTPSFallbackTest : public testing::Test {
10212 public:
fdorayf33fede2017-05-11 21:18:1010213 HTTPSFallbackTest() : context_(true) {
davidben095ebb52017-04-12 22:23:3410214 ssl_config_service_ = new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5610215 false /* online revocation checking */,
davidben095ebb52017-04-12 22:23:3410216 false /* require rev. checking for local anchors */,
10217 false /* token binding enabled */);
10218 context_.set_ssl_config_service(ssl_config_service_.get());
10219 }
Chris Watkins7a41d3552017-12-01 02:13:2710220 ~HTTPSFallbackTest() override = default;
[email protected]48d2b7c52014-06-27 01:16:5510221
10222 protected:
davidben095ebb52017-04-12 22:23:3410223 TestSSLConfigService* ssl_config_service() {
10224 return ssl_config_service_.get();
10225 }
10226
[email protected]48d2b7c52014-06-27 01:16:5510227 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
10228 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:0010229 context_.Init();
10230 delegate_.set_allow_certificate_errors(true);
10231
[email protected]48d2b7c52014-06-27 01:16:5510232 SpawnedTestServer test_server(
10233 SpawnedTestServer::TYPE_HTTPS,
10234 ssl_options,
10235 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10236 ASSERT_TRUE(test_server.Start());
10237
tommycli59a63432015-11-06 00:10:5510238 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
rhalavatib7bd7c792017-04-27 05:25:1610239 &delegate_, TRAFFIC_ANNOTATION_FOR_TESTS);
[email protected]48d2b7c52014-06-27 01:16:5510240 request_->Start();
10241
10242 base::RunLoop().Run();
10243 }
10244
davidben095ebb52017-04-12 22:23:3410245 void ExpectConnection(int version) {
10246 EXPECT_EQ(1, delegate_.response_started_count());
10247 EXPECT_NE(0, delegate_.bytes_received());
10248 EXPECT_EQ(version, SSLConnectionStatusToVersion(
10249 request_->ssl_info().connection_status));
10250 }
10251
[email protected]48d2b7c52014-06-27 01:16:5510252 void ExpectFailure(int error) {
10253 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:5010254 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:5510255 }
10256
10257 private:
10258 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:4710259 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610260 std::unique_ptr<URLRequest> request_;
davidben095ebb52017-04-12 22:23:3410261 scoped_refptr<TestSSLConfigService> ssl_config_service_;
[email protected]48d2b7c52014-06-27 01:16:5510262};
10263
davidbenb127ca82015-06-15 19:05:4210264// Tests the TLS 1.0 fallback doesn't happen.
10265TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:5510266 SpawnedTestServer::SSLOptions ssl_options(
10267 SpawnedTestServer::SSLOptions::CERT_OK);
10268 ssl_options.tls_intolerant =
10269 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
10270
10271 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:5510272 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:4210273}
10274
davidben5a312152016-06-27 22:11:4710275// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:5510276TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:4210277 SpawnedTestServer::SSLOptions ssl_options(
10278 SpawnedTestServer::SSLOptions::CERT_OK);
10279 ssl_options.tls_intolerant =
10280 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
10281
10282 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:5510283 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
10284}
10285
davidben095ebb52017-04-12 22:23:3410286// Tests that TLS 1.3 interference results in a dedicated error code.
10287TEST_F(HTTPSFallbackTest, TLSv1_3Interference) {
10288 SpawnedTestServer::SSLOptions ssl_options(
10289 SpawnedTestServer::SSLOptions::CERT_OK);
10290 ssl_options.tls_intolerant =
10291 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10292 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_3);
10293
10294 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10295 ExpectFailure(ERR_SSL_VERSION_INTERFERENCE);
10296}
10297
10298// Tests that disabling TLS 1.3 leaves TLS 1.3 interference unnoticed.
10299TEST_F(HTTPSFallbackTest, TLSv1_3InterferenceDisableVersion) {
10300 SpawnedTestServer::SSLOptions ssl_options(
10301 SpawnedTestServer::SSLOptions::CERT_OK);
10302 ssl_options.tls_intolerant =
10303 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_3;
10304 ssl_config_service()->set_max_version(SSL_PROTOCOL_VERSION_TLS1_2);
10305
10306 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
10307 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_2);
10308}
10309
[email protected]a8fed1742013-12-27 02:14:2410310class HTTPSSessionTest : public testing::Test {
10311 public:
fdorayf33fede2017-05-11 21:18:1010312 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:5910313 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410314
10315 default_context_.set_network_delegate(&default_network_delegate_);
10316 default_context_.set_cert_verifier(&cert_verifier_);
10317 default_context_.Init();
10318 }
Chris Watkins7a41d3552017-12-01 02:13:2710319 ~HTTPSSessionTest() override = default;
[email protected]a8fed1742013-12-27 02:14:2410320
10321 protected:
10322 MockCertVerifier cert_verifier_;
10323 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
10324 TestURLRequestContext default_context_;
10325};
10326
10327// Tests that session resumption is not attempted if an invalid certificate
10328// is presented.
10329TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
10330 SpawnedTestServer::SSLOptions ssl_options;
10331 ssl_options.record_resume = true;
10332 SpawnedTestServer test_server(
10333 SpawnedTestServer::TYPE_HTTPS,
10334 ssl_options,
10335 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10336 ASSERT_TRUE(test_server.Start());
10337
10338 SSLClientSocket::ClearSessionCache();
10339
10340 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:5910341 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:2410342 {
10343 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610344 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610345 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10346 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410347
[email protected]f7022f32014-08-21 16:32:1910348 r->Start();
10349 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410350
10351 base::RunLoop().Run();
10352
10353 EXPECT_EQ(1, d.response_started_count());
10354 }
10355
10356 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
10357 CloseAllConnections();
10358
10359 // Now change the certificate to be acceptable (so that the response is
10360 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:5910361 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:2410362 {
10363 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610364 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1610365 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d,
10366 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]a8fed1742013-12-27 02:14:2410367
[email protected]f7022f32014-08-21 16:32:1910368 r->Start();
10369 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:2410370
10371 base::RunLoop().Run();
10372
10373 // The response will look like;
10374 // insert abc
10375 // insert xyz
10376 //
10377 // With a newline at the end which makes the split think that there are
10378 // three lines.
10379 //
10380 // If a session was presented (eg: a bug), then the response would look
10381 // like;
10382 // insert abc
10383 // lookup abc
10384 // insert xyz
10385
10386 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:0010387 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:2410388 }
10389}
10390
[email protected]dffe8242012-03-20 15:14:2710391// This the fingerprint of the "Testing CA" certificate used by the testserver.
10392// See net/data/ssl/certificates/ocsp-test-root.pem.
David Benjamin9cedc3a52017-08-20 21:30:5810393static const SHA256HashValue kOCSPTestCertFingerprint = {{
10394 0x0c, 0xa9, 0x05, 0x11, 0xb0, 0xa2, 0xc0, 0x1d, 0x40, 0x6a, 0x99,
10395 0x04, 0x21, 0x36, 0x45, 0x3f, 0x59, 0x12, 0x5c, 0x80, 0x64, 0x2d,
10396 0x46, 0x6a, 0x3b, 0x78, 0x9e, 0x84, 0xea, 0x54, 0x0f, 0x8b,
mattm3b4376f12016-10-03 21:07:1510397}};
[email protected]dffe8242012-03-20 15:14:2710398
[email protected]51523f52013-07-31 21:57:2810399// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
10400// testserver.
mattm0b12a6f2016-11-29 19:57:1610401static const SHA256HashValue kOCSPTestCertSPKI = {{
10402 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
10403 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
10404 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
10405}};
[email protected]51523f52013-07-31 21:57:2810406
[email protected]dffe8242012-03-20 15:14:2710407// This is the policy OID contained in the certificates that testserver
10408// generates.
10409static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
10410
10411class HTTPSOCSPTest : public HTTPSRequestTest {
10412 public:
10413 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:0910414 : context_(true),
[email protected]b6f2de32012-08-17 04:35:0810415 ev_test_policy_(
10416 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
10417 kOCSPTestCertFingerprint,
10418 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:0210419 }
10420
dcheng67be2b1f2014-10-27 21:47:2910421 void SetUp() override {
rsleevid6de8302016-06-21 01:33:2010422 context_.SetCTPolicyEnforcer(
Jeremy Roman0579ed62017-08-29 15:56:1910423 std::make_unique<AllowAnyCertCTPolicyEnforcer>());
rsleevid6de8302016-06-21 01:33:2010424 SetupContext();
[email protected]ef2bf422012-05-11 03:27:0910425 context_.Init();
[email protected]dffe8242012-03-20 15:14:2710426
[email protected]cba24642014-08-15 20:49:5910427 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:2010428 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:4210429 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:5010430 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:2710431
Matt Muellerfb271992018-01-30 18:10:4810432#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510433 SetGlobalCertNetFetcherForTesting(net::CreateCertNetFetcher(&context_));
10434#endif
10435
svaldez2135be52016-04-20 16:34:5310436#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:0910437 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:2710438#endif
10439 }
10440
dadrian612337a2016-07-20 22:36:5810441 void DoConnectionWithDelegate(
10442 const SpawnedTestServer::SSLOptions& ssl_options,
10443 TestDelegate* delegate,
10444 SSLInfo* out_ssl_info) {
10445 // Always overwrite |out_ssl_info|.
10446 out_ssl_info->Reset();
10447
[email protected]ce7d0cbc2013-05-03 18:57:2210448 SpawnedTestServer test_server(
10449 SpawnedTestServer::TYPE_HTTPS,
10450 ssl_options,
10451 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:2710452 ASSERT_TRUE(test_server.Start());
10453
dadrian612337a2016-07-20 22:36:5810454 delegate->set_allow_certificate_errors(true);
rhalavatib7bd7c792017-04-27 05:25:1610455 std::unique_ptr<URLRequest> r(
10456 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
10457 delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1910458 r->Start();
[email protected]dffe8242012-03-20 15:14:2710459
[email protected]255620da2013-08-19 13:14:2910460 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:5810461 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:2710462
dadrian612337a2016-07-20 22:36:5810463 *out_ssl_info = r->ssl_info();
10464 }
10465
10466 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
10467 CertStatus* out_cert_status) {
10468 // Always overwrite |out_cert_status|.
10469 *out_cert_status = 0;
10470
10471 TestDelegate d;
10472 SSLInfo ssl_info;
10473 ASSERT_NO_FATAL_FAILURE(
10474 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
10475
10476 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:2710477 }
10478
dcheng67be2b1f2014-10-27 21:47:2910479 ~HTTPSOCSPTest() override {
Matt Muellerfb271992018-01-30 18:10:4810480#if defined(OS_ANDROID) || defined(USE_BUILTIN_CERT_VERIFIER)
Eric Romanefddd0a2017-10-10 02:14:2510481 ShutdownGlobalCertNetFetcher();
10482#endif
10483
svaldez2135be52016-04-20 16:34:5310484#if defined(USE_NSS_CERTS)
Matt Muellera17ffaf2018-03-28 20:08:1810485 SetURLRequestContextForNSSHttpIO(nullptr);
[email protected]dffe8242012-03-20 15:14:2710486#endif
10487 }
10488
[email protected]a13234c2012-03-20 21:45:0210489 protected:
rsleevid6de8302016-06-21 01:33:2010490 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
10491 public:
10492 AllowAnyCertCTPolicyEnforcer() = default;
10493 ~AllowAnyCertCTPolicyEnforcer() override = default;
10494
Emily Stark627238f2017-11-29 03:29:5410495 ct::CTPolicyCompliance CheckCompliance(
rsleevid6de8302016-06-21 01:33:2010496 X509Certificate* cert,
10497 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:2010498 const NetLogWithSource& net_log) override {
Emily Stark627238f2017-11-29 03:29:5410499 return ct::CTPolicyCompliance::CT_POLICY_COMPLIES_VIA_SCTS;
rsleevid6de8302016-06-21 01:33:2010500 }
rsleevid6de8302016-06-21 01:33:2010501 };
[email protected]a13234c2012-03-20 21:45:0210502 // SetupContext configures the URLRequestContext that will be used for making
10503 // connetions to testserver. This can be overridden in test subclasses for
10504 // different behaviour.
rsleevid6de8302016-06-21 01:33:2010505 virtual void SetupContext() {
Ryan Sleevi5b4702a2018-04-06 22:23:5610506 context_.set_ssl_config_service(
10507 new TestSSLConfigService(true /* online revocation checking */,
10508 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1410509 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5610510 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210511 }
10512
danakj8522a25b2016-04-16 00:17:3610513 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:0910514 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:3610515 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:2710516};
10517
[email protected]a13234c2012-03-20 21:45:0210518static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:2010519#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:0210520 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
10521 // have that ability on other platforms.
Eric Roman1b628daa2017-10-19 19:52:0410522 // TODO(eroman): Should this also be the return value for
10523 // CertVerifyProcBuiltin?
[email protected]a13234c2012-03-20 21:45:0210524 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
10525#else
10526 return 0;
10527#endif
10528}
10529
[email protected]3a86a712013-07-30 07:16:2010530// SystemSupportsHardFailRevocationChecking returns true iff the current
10531// operating system supports revocation checking and can distinguish between
10532// situations where a given certificate lacks any revocation information (eg:
10533// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
10534// revocation information cannot be obtained (eg: the CRL was unreachable).
10535// If it does not, then tests which rely on 'hard fail' behaviour should be
10536// skipped.
10537static bool SystemSupportsHardFailRevocationChecking() {
Eric Roman1b628daa2017-10-19 19:52:0410538#if defined(OS_WIN) || defined(USE_NSS_CERTS) || \
10539 defined(USE_BUILTIN_CERT_VERIFIER)
[email protected]3a86a712013-07-30 07:16:2010540 return true;
10541#else
10542 return false;
10543#endif
10544}
10545
[email protected]a13234c2012-03-20 21:45:0210546// SystemUsesChromiumEVMetadata returns true iff the current operating system
10547// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
10548// several tests are effected because our testing EV certificate won't be
10549// recognised as EV.
10550static bool SystemUsesChromiumEVMetadata() {
Eric Roman5f8d9d22017-10-17 02:32:5210551#if defined(PLATFORM_USES_CHROMIUM_EV_METADATA)
[email protected]05454a432012-03-20 20:04:0110552 return true;
Eric Roman5f8d9d22017-10-17 02:32:5210553#else
10554 return false;
[email protected]05454a432012-03-20 20:04:0110555#endif
10556}
10557
mattmaf868e72016-09-23 23:25:2010558// Returns the expected CertStatus for tests that expect an online revocation
10559// check failure as a result of checking a test EV cert, which will not
10560// actually trigger an online revocation check on some platforms.
10561static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
10562 if (SystemUsesChromiumEVMetadata()) {
10563 return ExpectedCertStatusForFailedOnlineRevocationCheck();
10564 } else {
10565 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
10566 // be enabled, and thus there will not be a revocation check to fail.
10567 return 0u;
10568 }
10569}
10570
[email protected]b6f2de32012-08-17 04:35:0810571static bool SystemSupportsOCSP() {
Sergey Ulanovee7c8db2017-12-08 00:18:3910572#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:0210573 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
10574 return false;
10575#else
10576 return true;
10577#endif
10578}
10579
davidbend1fb2f12014-11-08 02:51:0010580static bool SystemSupportsOCSPStapling() {
Eric Roman1b628daa2017-10-19 19:52:0410581#if defined(USE_NSS_CERTS) || defined(OS_WIN) || \
10582 defined(USE_BUILTIN_CERT_VERIFIER)
mathpc992e602015-10-21 20:34:0310583 return true;
mathpc992e602015-10-21 20:34:0310584#else
10585 return false;
10586#endif
davidbend1fb2f12014-11-08 02:51:0010587}
10588
[email protected]dffe8242012-03-20 15:14:2710589TEST_F(HTTPSOCSPTest, Valid) {
10590 if (!SystemSupportsOCSP()) {
10591 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10592 return;
10593 }
10594
[email protected]ce7d0cbc2013-05-03 18:57:2210595 SpawnedTestServer::SSLOptions ssl_options(
10596 SpawnedTestServer::SSLOptions::CERT_AUTO);
10597 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:2710598
[email protected]924e9f92012-12-16 22:00:5310599 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210600 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710601
10602 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10603
[email protected]a13234c2012-03-20 21:45:0210604 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10605 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:2710606
10607 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10608}
10609
10610TEST_F(HTTPSOCSPTest, Revoked) {
10611 if (!SystemSupportsOCSP()) {
10612 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10613 return;
10614 }
10615
[email protected]ce7d0cbc2013-05-03 18:57:2210616 SpawnedTestServer::SSLOptions ssl_options(
10617 SpawnedTestServer::SSLOptions::CERT_AUTO);
10618 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:2710619
10620 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210621 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710622
[email protected]dffe8242012-03-20 15:14:2710623 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:2710624 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10625 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10626}
10627
10628TEST_F(HTTPSOCSPTest, Invalid) {
10629 if (!SystemSupportsOCSP()) {
10630 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10631 return;
10632 }
10633
[email protected]ce7d0cbc2013-05-03 18:57:2210634 SpawnedTestServer::SSLOptions ssl_options(
10635 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810636 ssl_options.ocsp_status =
10637 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:2710638
[email protected]924e9f92012-12-16 22:00:5310639 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210640 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:2710641
Eric Roman1b628daa2017-10-19 19:52:0410642#if defined(USE_BUILTIN_CERT_VERIFIER)
10643 // TODO(649017): This test uses soft-fail revocation checking, but returns an
10644 // invalid OCSP response (can't parse). CertVerifyProcBuiltin currently
10645 // doesn't consider this a candidate for soft-fail (only considers
10646 // network-level failures as skippable).
10647 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
10648 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
10649#else
[email protected]a13234c2012-03-20 21:45:0210650 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:2710651 cert_status & CERT_STATUS_ALL_ERRORS);
Eric Roman1b628daa2017-10-19 19:52:0410652#endif
[email protected]dffe8242012-03-20 15:14:2710653
10654 // Without a positive OCSP response, we shouldn't show the EV status.
10655 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10656 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10657}
[email protected]a13234c2012-03-20 21:45:0210658
davidbend1fb2f12014-11-08 02:51:0010659TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:0310660 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010661 LOG(WARNING)
10662 << "Skipping test because system doesn't support OCSP stapling";
10663 return;
10664 }
10665
10666 SpawnedTestServer::SSLOptions ssl_options(
10667 SpawnedTestServer::SSLOptions::CERT_AUTO);
10668 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10669 ssl_options.staple_ocsp_response = true;
10670 ssl_options.ocsp_server_unavailable = true;
10671
10672 CertStatus cert_status;
10673 DoConnection(ssl_options, &cert_status);
10674
10675 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10676
10677 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10678 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10679
10680 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10681}
10682
davidben6c3191b2014-11-21 22:38:0410683// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:4810684#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:0410685#define MAYBE_RevokedStapled DISABLED_RevokedStapled
10686#else
10687#define MAYBE_RevokedStapled RevokedStapled
10688#endif
10689TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:0310690 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:0010691 LOG(WARNING)
10692 << "Skipping test because system doesn't support OCSP stapling";
10693 return;
10694 }
10695
10696 SpawnedTestServer::SSLOptions ssl_options(
10697 SpawnedTestServer::SSLOptions::CERT_AUTO);
10698 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10699 ssl_options.staple_ocsp_response = true;
10700 ssl_options.ocsp_server_unavailable = true;
10701
10702 CertStatus cert_status;
10703 DoConnection(ssl_options, &cert_status);
10704
10705 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10706 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10707 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10708}
10709
dadriand476e652016-07-26 21:33:2410710TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
Martijn Croonenb1383da2017-10-11 11:56:3510711 SetTransportSecurityStateSourceForTesting(&test_default::kHSTSSource);
10712
dadriand476e652016-07-26 21:33:2410713 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10714 https_test_server.SetSSLConfig(
10715 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10716 https_test_server.ServeFilesFromSourceDirectory(
10717 base::FilePath(kTestFilePath));
10718 ASSERT_TRUE(https_test_server.Start());
10719
10720 // Set up a MockCertVerifier to accept the certificate that the server sends,
10721 // but not provide any OCSP information.
10722 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10723 ASSERT_TRUE(cert);
10724 MockCertVerifier cert_verifier;
10725 CertVerifyResult verify_result;
10726 verify_result.verified_cert = cert;
10727 verify_result.is_issued_by_known_root = true;
10728 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10729 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10730
10731 // Catch the Expect-Staple report.
10732 TransportSecurityState transport_security_state;
10733 MockCertificateReportSender mock_report_sender;
10734 transport_security_state.SetReportSender(&mock_report_sender);
10735
10736 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10737 // that the request can be sent to a site on the Expect-Staple preload list.
10738 MockHostResolver host_resolver;
10739 TestNetworkDelegate network_delegate;
10740 TestURLRequestContext context(true);
10741 context.set_host_resolver(&host_resolver);
10742 context.set_transport_security_state(&transport_security_state);
10743 context.set_network_delegate(&network_delegate);
10744 context.set_cert_verifier(&cert_verifier);
10745 context.Init();
10746
10747 // Now send a request to trigger the violation.
10748 TestDelegate d;
10749 GURL url = https_test_server.GetURL("/");
10750 GURL::Replacements replace_host;
10751 replace_host.SetHostStr(kExpectStapleStaticHostname);
10752 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610753 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10754 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410755 violating_request->Start();
10756 base::RunLoop().Run();
10757
10758 // Confirm a report was sent.
10759 EXPECT_FALSE(mock_report_sender.latest_report().empty());
10760 EXPECT_EQ(GURL(kExpectStapleReportURI),
10761 mock_report_sender.latest_report_uri());
10762}
10763
estark13e0b312016-12-22 23:52:3210764// Tests that Expect-Staple reports are not sent for connections on which there
10765// is a certificate error.
10766TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
10767 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10768 https_test_server.SetSSLConfig(
10769 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10770 https_test_server.ServeFilesFromSourceDirectory(
10771 base::FilePath(kTestFilePath));
10772 ASSERT_TRUE(https_test_server.Start());
10773
10774 // Set up a MockCertVerifier to report an error for the certificate
10775 // and indicate that there was no stapled OCSP response.
10776 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10777 ASSERT_TRUE(cert);
10778 MockCertVerifier cert_verifier;
10779 CertVerifyResult verify_result;
10780 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
10781 verify_result.verified_cert = cert;
10782 verify_result.is_issued_by_known_root = true;
10783 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
10784 cert_verifier.AddResultForCert(cert.get(), verify_result,
10785 ERR_CERT_DATE_INVALID);
10786
10787 // Set up a mock report sender so that the test can check that an
10788 // Expect-Staple report is not sent.
10789 TransportSecurityState transport_security_state;
10790 MockCertificateReportSender mock_report_sender;
10791 transport_security_state.SetReportSender(&mock_report_sender);
10792
10793 TestNetworkDelegate network_delegate;
10794 TestURLRequestContext context(true);
10795
10796 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10797 MockHostResolver host_resolver;
10798 context.set_host_resolver(&host_resolver);
10799
10800 context.set_transport_security_state(&transport_security_state);
10801 context.set_network_delegate(&network_delegate);
10802 context.set_cert_verifier(&cert_verifier);
10803 context.Init();
10804
10805 // Make a connection to |kExpectStapleStaticHostname|. Because the
10806 // |verify_result| used with the |cert_verifier| will indicate a certificate
10807 // error, an Expect-Staple report should not be sent.
10808 TestDelegate d;
10809 GURL url = https_test_server.GetURL("/");
10810 GURL::Replacements replace_host;
10811 replace_host.SetHostStr(kExpectStapleStaticHostname);
10812 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610813 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
10814 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210815 violating_request->Start();
10816 base::RunLoop().Run();
10817
10818 // Confirm a report was not sent.
10819 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10820 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10821}
10822
dadriand476e652016-07-26 21:33:2410823TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
10824 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10825 https_test_server.SetSSLConfig(
10826 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10827 https_test_server.ServeFilesFromSourceDirectory(
10828 base::FilePath(kTestFilePath));
10829 ASSERT_TRUE(https_test_server.Start());
10830
10831 // Set up a MockCertVerifier to accept the certificate that the server sends,
10832 // and provide GOOD revocation status.
10833 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10834 ASSERT_TRUE(cert);
10835 MockCertVerifier cert_verifier;
10836 CertVerifyResult verify_result;
10837 verify_result.verified_cert = cert;
10838 verify_result.is_issued_by_known_root = true;
10839 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
10840 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
10841 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10842
10843 // Catch the Expect-Staple report.
10844 TransportSecurityState transport_security_state;
10845 MockCertificateReportSender mock_report_sender;
10846 transport_security_state.SetReportSender(&mock_report_sender);
10847
10848 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
10849 // that the request can be sent to a site on the Expect-Staple preload list.
10850 MockHostResolver host_resolver;
10851 TestNetworkDelegate network_delegate;
10852 TestURLRequestContext context(true);
10853 context.set_host_resolver(&host_resolver);
10854 context.set_transport_security_state(&transport_security_state);
10855 context.set_network_delegate(&network_delegate);
10856 context.set_cert_verifier(&cert_verifier);
10857 context.Init();
10858
10859 // This request should not not trigger an Expect-Staple violation.
10860 TestDelegate d;
10861 GURL url = https_test_server.GetURL("/");
10862 GURL::Replacements replace_host;
10863 replace_host.SetHostStr(kExpectStapleStaticHostname);
10864 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610865 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10866 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
dadriand476e652016-07-26 21:33:2410867 ok_request->Start();
10868 base::RunLoop().Run();
10869
10870 // Check that no report was sent.
10871 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10872 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10873}
10874
estark13e0b312016-12-22 23:52:3210875// Tests that an Expect-Staple report is not sent when OCSP details are not
10876// checked on the connection.
10877TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
10878 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
10879 https_test_server.SetSSLConfig(
10880 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
10881 https_test_server.ServeFilesFromSourceDirectory(
10882 base::FilePath(kTestFilePath));
10883 ASSERT_TRUE(https_test_server.Start());
10884
10885 // Set up a MockCertVerifier to accept the certificate that the server sends,
10886 // and set |ocsp_result| to indicate that OCSP stapling details were not
10887 // checked on the connection.
10888 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
10889 ASSERT_TRUE(cert);
10890 MockCertVerifier cert_verifier;
10891 CertVerifyResult verify_result;
10892 verify_result.verified_cert = cert;
10893 verify_result.is_issued_by_known_root = true;
10894 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
10895 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
10896
10897 // Set up a mock report sender so that the test can check that an
10898 // Expect-Staple report is not sent.
10899 TransportSecurityState transport_security_state;
10900 MockCertificateReportSender mock_report_sender;
10901 transport_security_state.SetReportSender(&mock_report_sender);
10902
10903 TestNetworkDelegate network_delegate;
10904 TestURLRequestContext context(true);
10905
10906 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
10907 MockHostResolver host_resolver;
10908 context.set_host_resolver(&host_resolver);
10909
10910 context.set_transport_security_state(&transport_security_state);
10911 context.set_network_delegate(&network_delegate);
10912 context.set_cert_verifier(&cert_verifier);
10913 context.Init();
10914
10915 // Make a connection to |kExpectStapleStaticHostname|. Because the
10916 // |verify_result| used with the |cert_verifier| will indicate that OCSP
10917 // stapling details were not checked on the connection, an Expect-Staple
10918 // report should not be sent.
10919 TestDelegate d;
10920 GURL url = https_test_server.GetURL("/");
10921 GURL::Replacements replace_host;
10922 replace_host.SetHostStr(kExpectStapleStaticHostname);
10923 url = url.ReplaceComponents(replace_host);
rhalavatib7bd7c792017-04-27 05:25:1610924 std::unique_ptr<URLRequest> ok_request(context.CreateRequest(
10925 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
estark13e0b312016-12-22 23:52:3210926 ok_request->Start();
10927 base::RunLoop().Run();
10928
10929 // Check that no report was sent.
10930 EXPECT_TRUE(mock_report_sender.latest_report().empty());
10931 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
10932}
10933
dadrian612337a2016-07-20 22:36:5810934static const struct OCSPVerifyTestData {
10935 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
10936 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
10937 OCSPVerifyResult::ResponseStatus response_status;
10938 bool has_revocation_status;
10939 OCSPRevocationStatus cert_status;
10940} kOCSPVerifyData[] = {
Eric Roman8673b812017-09-20 18:57:3110941 // 0
dadrian612337a2016-07-20 22:36:5810942 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10943 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10944 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10945 OCSPVerifyResult::PROVIDED,
10946 true,
10947 OCSPRevocationStatus::GOOD},
10948
Eric Roman8673b812017-09-20 18:57:3110949 // 1
dadrian612337a2016-07-20 22:36:5810950 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10951 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10952 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10953 OCSPVerifyResult::INVALID_DATE,
10954 false,
10955 OCSPRevocationStatus::UNKNOWN},
10956
Eric Roman8673b812017-09-20 18:57:3110957 // 2
dadrian612337a2016-07-20 22:36:5810958 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10959 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10960 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10961 OCSPVerifyResult::INVALID_DATE,
10962 false,
10963 OCSPRevocationStatus::UNKNOWN},
10964
Eric Roman8673b812017-09-20 18:57:3110965 // 3
dadrian612337a2016-07-20 22:36:5810966 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10967 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10968 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10969 OCSPVerifyResult::INVALID_DATE,
10970 false,
10971 OCSPRevocationStatus::UNKNOWN},
10972
Eric Roman8673b812017-09-20 18:57:3110973 // 4
dadrian612337a2016-07-20 22:36:5810974 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10975 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10976 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10977 OCSPVerifyResult::INVALID_DATE,
10978 false,
10979 OCSPRevocationStatus::UNKNOWN},
10980
Eric Roman8673b812017-09-20 18:57:3110981 // 5
dadrian612337a2016-07-20 22:36:5810982 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
10983 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10984 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10985 OCSPVerifyResult::ERROR_RESPONSE,
10986 false,
10987 OCSPRevocationStatus::UNKNOWN},
10988
Eric Roman8673b812017-09-20 18:57:3110989 // 6
dadrian612337a2016-07-20 22:36:5810990 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
10991 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10992 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10993 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
10994 false,
10995 OCSPRevocationStatus::UNKNOWN},
10996
Eric Roman8673b812017-09-20 18:57:3110997 // 7
dadrian612337a2016-07-20 22:36:5810998 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
10999 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11000 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11001 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
11002 false,
11003 OCSPRevocationStatus::UNKNOWN},
11004
Eric Roman8673b812017-09-20 18:57:3111005 // 8
dadrian612337a2016-07-20 22:36:5811006 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11007 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11008 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11009 OCSPVerifyResult::INVALID_DATE,
11010 false,
11011 OCSPRevocationStatus::UNKNOWN},
11012
Eric Roman8673b812017-09-20 18:57:3111013 // 9
dadrian612337a2016-07-20 22:36:5811014 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11015 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11016 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11017 OCSPVerifyResult::PROVIDED,
11018 true,
11019 OCSPRevocationStatus::UNKNOWN},
11020
Eric Roman8673b812017-09-20 18:57:3111021 // 10
dadrian612337a2016-07-20 22:36:5811022 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11023 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11024 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11025 OCSPVerifyResult::INVALID_DATE,
11026 false,
11027 OCSPRevocationStatus::UNKNOWN},
11028
Eric Roman8673b812017-09-20 18:57:3111029 // 11
dadrian612337a2016-07-20 22:36:5811030 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11031 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11032 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11033 OCSPVerifyResult::INVALID_DATE,
11034 false,
11035 OCSPRevocationStatus::UNKNOWN},
11036
Eric Roman8673b812017-09-20 18:57:3111037 // 12
dadrian612337a2016-07-20 22:36:5811038 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11039 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11040 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
11041 OCSPVerifyResult::BAD_PRODUCED_AT,
11042 false,
11043 OCSPRevocationStatus::UNKNOWN},
11044
Eric Roman8673b812017-09-20 18:57:3111045 // 13
dadrian612337a2016-07-20 22:36:5811046 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11047 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11048 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11049 OCSPVerifyResult::BAD_PRODUCED_AT,
11050 false,
11051 OCSPRevocationStatus::UNKNOWN},
11052
Eric Roman8673b812017-09-20 18:57:3111053 // 14
dadrian612337a2016-07-20 22:36:5811054 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11055 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11056 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
11057 OCSPVerifyResult::BAD_PRODUCED_AT,
11058 false,
11059 OCSPRevocationStatus::UNKNOWN},
11060
Eric Roman8673b812017-09-20 18:57:3111061 // 15
dadrian612337a2016-07-20 22:36:5811062 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11063 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11064 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11065 OCSPVerifyResult::PROVIDED,
11066 true,
11067 OCSPRevocationStatus::GOOD},
11068
Eric Roman8673b812017-09-20 18:57:3111069 // 16
dadrian612337a2016-07-20 22:36:5811070 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11071 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11072 {SpawnedTestServer::SSLOptions::OCSP_OK,
11073 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11074 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11075 OCSPVerifyResult::PROVIDED,
11076 true,
11077 OCSPRevocationStatus::GOOD},
11078
Eric Roman8673b812017-09-20 18:57:3111079 // 17
dadrian612337a2016-07-20 22:36:5811080 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11081 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11082 {SpawnedTestServer::SSLOptions::OCSP_OK,
11083 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11084 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11085 OCSPVerifyResult::PROVIDED,
11086 true,
11087 OCSPRevocationStatus::GOOD},
11088
Eric Roman8673b812017-09-20 18:57:3111089 // 18
dadrian612337a2016-07-20 22:36:5811090 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11091 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11092 {SpawnedTestServer::SSLOptions::OCSP_OK,
11093 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11094 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11095 OCSPVerifyResult::PROVIDED,
11096 true,
11097 OCSPRevocationStatus::GOOD},
11098
Eric Roman8673b812017-09-20 18:57:3111099 // 19
dadrian612337a2016-07-20 22:36:5811100 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
11101 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
11102 {SpawnedTestServer::SSLOptions::OCSP_OK,
11103 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
11104 {SpawnedTestServer::SSLOptions::OCSP_OK,
11105 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11106 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11107 OCSPVerifyResult::INVALID_DATE,
11108 false,
11109 OCSPRevocationStatus::UNKNOWN},
11110
Eric Roman8673b812017-09-20 18:57:3111111 // 20
dadrian612337a2016-07-20 22:36:5811112 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11113 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11114 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11115 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11116 {SpawnedTestServer::SSLOptions::OCSP_OK,
11117 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11118 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11119 OCSPVerifyResult::PROVIDED,
11120 true,
11121 OCSPRevocationStatus::REVOKED},
11122
Eric Roman8673b812017-09-20 18:57:3111123 // 21
dadrian612337a2016-07-20 22:36:5811124 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11125 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11126 {SpawnedTestServer::SSLOptions::OCSP_OK,
11127 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11128 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11129 OCSPVerifyResult::PROVIDED,
11130 true,
11131 OCSPRevocationStatus::UNKNOWN},
11132
Eric Roman8673b812017-09-20 18:57:3111133 // 22
dadrian612337a2016-07-20 22:36:5811134 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
11135 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
11136 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11137 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
11138 {SpawnedTestServer::SSLOptions::OCSP_OK,
11139 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11140 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11141 OCSPVerifyResult::PROVIDED,
11142 true,
11143 OCSPRevocationStatus::UNKNOWN},
11144
Eric Roman8673b812017-09-20 18:57:3111145 // 23
dadrian612337a2016-07-20 22:36:5811146 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11147 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11148 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11149 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11150 false,
11151 OCSPRevocationStatus::UNKNOWN},
11152
Eric Roman8673b812017-09-20 18:57:3111153 // 24
dadrian612337a2016-07-20 22:36:5811154 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
11155 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
11156 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11157 OCSPVerifyResult::NO_MATCHING_RESPONSE,
11158 false,
11159 OCSPRevocationStatus::UNKNOWN},
11160
Eric Roman8673b812017-09-20 18:57:3111161// These tests fail when using NSS for certificate verification, as NSS fails
11162// and doesn't return the partial path. As a result the OCSP checks being done
11163// at the CertVerifyProc layer cannot access the issuer certificate.
11164#if !defined(USE_NSS_CERTS)
11165 // 25
11166 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11167 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
11168 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11169 OCSPVerifyResult::PROVIDED,
11170 true,
11171 OCSPRevocationStatus::REVOKED},
11172
11173 // 26
11174 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11175 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
11176 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11177 OCSPVerifyResult::INVALID_DATE,
11178 false,
11179 OCSPRevocationStatus::UNKNOWN},
11180
11181 // 27
11182 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
11183 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
11184 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
11185 OCSPVerifyResult::INVALID_DATE,
11186 false,
11187 OCSPRevocationStatus::UNKNOWN},
11188#endif
dadrian612337a2016-07-20 22:36:5811189};
11190
11191class HTTPSOCSPVerifyTest
11192 : public HTTPSOCSPTest,
11193 public testing::WithParamInterface<OCSPVerifyTestData> {};
11194
11195TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
11196 SpawnedTestServer::SSLOptions ssl_options(
11197 SpawnedTestServer::SSLOptions::CERT_AUTO);
11198 OCSPVerifyTestData test = GetParam();
11199
11200 ssl_options.ocsp_responses = test.ocsp_responses;
11201 ssl_options.ocsp_produced = test.ocsp_produced;
11202 ssl_options.staple_ocsp_response = true;
11203
11204 SSLInfo ssl_info;
11205 OCSPErrorTestDelegate delegate;
11206 ASSERT_NO_FATAL_FAILURE(
11207 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
11208
11209 // The SSLInfo must be extracted from |delegate| on error, due to how
11210 // URLRequest caches certificate errors.
11211 if (delegate.have_certificate_errors()) {
11212 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
11213 ssl_info = delegate.ssl_info();
11214 }
11215
11216 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
11217
11218 if (test.has_revocation_status)
11219 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
11220}
11221
11222INSTANTIATE_TEST_CASE_P(OCSPVerify,
11223 HTTPSOCSPVerifyTest,
11224 testing::ValuesIn(kOCSPVerifyData));
11225
mattm0b12a6f2016-11-29 19:57:1611226class HTTPSAIATest : public HTTPSOCSPTest {
11227 public:
11228 void SetupContext() override {
11229 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611230 false /* online revocation checking */,
mattm0b12a6f2016-11-29 19:57:1611231 false /* require rev. checking for local anchors */,
11232 false /* token binding enabled */));
11233 }
11234};
11235
11236TEST_F(HTTPSAIATest, AIAFetching) {
11237 SpawnedTestServer::SSLOptions ssl_options(
11238 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
11239 SpawnedTestServer test_server(
11240 SpawnedTestServer::TYPE_HTTPS, ssl_options,
11241 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
11242 ASSERT_TRUE(test_server.Start());
11243
Ryan Sleevi5b4702a2018-04-06 22:23:5611244 // Unmark the certificate's OID as EV, which will disable revocation
11245 // checking.
11246 ev_test_policy_.reset();
11247
mattm0b12a6f2016-11-29 19:57:1611248 TestDelegate d;
11249 d.set_allow_certificate_errors(true);
11250 std::unique_ptr<URLRequest> r(context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611251 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d,
11252 TRAFFIC_ANNOTATION_FOR_TESTS));
mattm0b12a6f2016-11-29 19:57:1611253
11254 r->Start();
11255 EXPECT_TRUE(r->is_pending());
11256
11257 base::RunLoop().Run();
11258
11259 EXPECT_EQ(1, d.response_started_count());
11260
11261 CertStatus cert_status = r->ssl_info().cert_status;
Matt Muellerfb271992018-01-30 18:10:4811262 EXPECT_EQ(OK, d.request_status());
11263 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11264 ASSERT_TRUE(r->ssl_info().cert);
11265 EXPECT_EQ(2u, r->ssl_info().cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611266 ASSERT_TRUE(r->ssl_info().unverified_cert);
Matt Muellera4193272017-12-07 00:23:3411267 EXPECT_EQ(0u, r->ssl_info().unverified_cert->intermediate_buffers().size());
mattm0b12a6f2016-11-29 19:57:1611268}
11269
[email protected]3a86a712013-07-30 07:16:2011270class HTTPSHardFailTest : public HTTPSOCSPTest {
11271 protected:
rsleevid6de8302016-06-21 01:33:2011272 void SetupContext() override {
11273 context_.set_ssl_config_service(new TestSSLConfigService(
Ryan Sleevi5b4702a2018-04-06 22:23:5611274 false /* online revocation checking */,
11275 true /* require rev. checking for local anchors */,
nharperb7441ef2016-01-25 23:54:1411276 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2011277 }
11278};
11279
[email protected]3a86a712013-07-30 07:16:2011280TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
11281 if (!SystemSupportsOCSP()) {
11282 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11283 return;
11284 }
11285
11286 if (!SystemSupportsHardFailRevocationChecking()) {
11287 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
11288 << "revocation checking";
11289 return;
11290 }
11291
11292 SpawnedTestServer::SSLOptions ssl_options(
11293 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811294 ssl_options.ocsp_status =
11295 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2011296
11297 CertStatus cert_status;
11298 DoConnection(ssl_options, &cert_status);
11299
Eric Roman1b628daa2017-10-19 19:52:0411300#if defined(USE_BUILTIN_CERT_VERIFIER)
11301 // TODO(crbug.com/649017): Should we consider invalid response as
11302 // affirmatively revoked?
11303 EXPECT_EQ(CERT_STATUS_UNABLE_TO_CHECK_REVOCATION,
11304 cert_status & CERT_STATUS_UNABLE_TO_CHECK_REVOCATION);
11305#else
11306 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_REVOKED);
11307#endif
[email protected]3a86a712013-07-30 07:16:2011308
11309 // Without a positive OCSP response, we shouldn't show the EV status.
Eric Roman1b628daa2017-10-19 19:52:0411310 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]3a86a712013-07-30 07:16:2011311 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11312}
11313
[email protected]a13234c2012-03-20 21:45:0211314class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
11315 protected:
rsleevid6de8302016-06-21 01:33:2011316 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611317 context_.set_ssl_config_service(
11318 new TestSSLConfigService(false /* online revocation checking */,
11319 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411320 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611321 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0211322 }
11323};
11324
Eric Romane2243cc62017-10-17 03:59:1311325// Helper class to set the global CRLSet, and on destruction restore the
11326// previously set one.
11327class ScopedSetCRLSet {
11328 public:
11329 ScopedSetCRLSet(scoped_refptr<CRLSet> crl_set) {
11330 prev_crl_set_ = SSLConfigService::GetCRLSet();
11331 SSLConfigService::SetCRLSetForTesting(std::move(crl_set));
11332 }
11333
11334 ~ScopedSetCRLSet() {
11335 SSLConfigService::SetCRLSetForTesting(std::move(prev_crl_set_));
11336 }
11337
11338 private:
11339 scoped_refptr<CRLSet> prev_crl_set_;
11340};
11341
[email protected]a13234c2012-03-20 21:45:0211342TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
11343 if (!SystemSupportsOCSP()) {
11344 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11345 return;
11346 }
11347
[email protected]ce7d0cbc2013-05-03 18:57:2211348 SpawnedTestServer::SSLOptions ssl_options(
11349 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811350 ssl_options.ocsp_status =
11351 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311352 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211353
[email protected]924e9f92012-12-16 22:00:5311354 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211355 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211356
mattmaf868e72016-09-23 23:25:2011357 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211358 cert_status & CERT_STATUS_ALL_ERRORS);
11359
11360 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811361 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11362 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211363}
11364
[email protected]be0fff62013-08-29 23:37:4811365TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
11366 if (!SystemSupportsOCSP()) {
11367 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11368 return;
11369 }
11370
11371 SpawnedTestServer::SSLOptions ssl_options(
11372 SpawnedTestServer::SSLOptions::CERT_AUTO);
11373 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
Eric Romane2243cc62017-10-17 03:59:1311374 ScopedSetCRLSet set_crlset(nullptr);
[email protected]be0fff62013-08-29 23:37:4811375
11376 CertStatus cert_status;
11377 DoConnection(ssl_options, &cert_status);
11378
mattm1a282f52016-11-10 21:49:4211379// Currently only works for Windows and OS X. When using NSS, it's not
11380// possible to determine whether the check failed because of actual
11381// revocation or because there was an OCSP failure.
11382#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4811383 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11384#else
11385 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11386#endif
11387
11388 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11389 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11390 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11391}
11392
[email protected]a13234c2012-03-20 21:45:0211393TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
11394 if (!SystemSupportsOCSP()) {
11395 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11396 return;
11397 }
11398
[email protected]ce7d0cbc2013-05-03 18:57:2211399 SpawnedTestServer::SSLOptions ssl_options(
11400 SpawnedTestServer::SSLOptions::CERT_AUTO);
11401 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
Eric Romane2243cc62017-10-17 03:59:1311402 ScopedSetCRLSet set_crlset(nullptr);
[email protected]a13234c2012-03-20 21:45:0211403
11404 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211405 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211406
11407 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11408
11409 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11410 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0811411 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11412 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211413}
11414
11415TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
11416 if (!SystemSupportsOCSP()) {
11417 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11418 return;
11419 }
11420
[email protected]ce7d0cbc2013-05-03 18:57:2211421 SpawnedTestServer::SSLOptions ssl_options(
11422 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811423 ssl_options.ocsp_status =
11424 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311425 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211426
11427 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211428 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211429
mattmaf868e72016-09-23 23:25:2011430 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0211431 cert_status & CERT_STATUS_ALL_ERRORS);
11432
11433 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0811434 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11435 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211436}
11437
[email protected]51523f52013-07-31 21:57:2811438TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
11439 if (!SystemSupportsOCSP()) {
11440 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11441 return;
11442 }
11443
11444 SpawnedTestServer::SSLOptions ssl_options(
11445 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811446 ssl_options.ocsp_status =
11447 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Adam Langleyea6d6782017-12-05 23:57:3311448 ScopedSetCRLSet set_crlset(
11449 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "", "", {}));
[email protected]51523f52013-07-31 21:57:2811450
11451 CertStatus cert_status;
11452 DoConnection(ssl_options, &cert_status);
11453
11454 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
11455 // revocation check for EV.
11456 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11457 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
11458 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
11459 EXPECT_FALSE(
11460 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
11461}
11462
11463TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
11464 if (!SystemSupportsOCSP()) {
11465 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11466 return;
11467 }
11468
[email protected]ce7d0cbc2013-05-03 18:57:2211469 SpawnedTestServer::SSLOptions ssl_options(
11470 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811471 ssl_options.ocsp_status =
11472 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311473 ScopedSetCRLSet set_crlset(CRLSet::EmptyCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211474
[email protected]51523f52013-07-31 21:57:2811475 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1211476 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211477
[email protected]51523f52013-07-31 21:57:2811478 // Even with a fresh CRLSet, we should still do online revocation checks when
11479 // the certificate chain isn't covered by the CRLSet, which it isn't in this
11480 // test.
mattmaf868e72016-09-23 23:25:2011481 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2811482 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0211483
[email protected]51523f52013-07-31 21:57:2811484 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0211485 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2811486 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0211487}
11488
[email protected]a13234c2012-03-20 21:45:0211489class HTTPSCRLSetTest : public HTTPSOCSPTest {
11490 protected:
rsleevid6de8302016-06-21 01:33:2011491 void SetupContext() override {
Ryan Sleevi5b4702a2018-04-06 22:23:5611492 context_.set_ssl_config_service(
11493 new TestSSLConfigService(false /* online revocation checking */,
11494 false /* require rev. checking for local
nharperb7441ef2016-01-25 23:54:1411495 anchors */,
Ryan Sleevi5b4702a2018-04-06 22:23:5611496 false /* token binding enabled */));
11497 }
11498
11499 void SetUp() override {
11500 HTTPSOCSPTest::SetUp();
11501
11502 // Unmark the certificate's OID as EV, which should disable revocation
11503 // checking (as per the user preference).
11504 ev_test_policy_.reset();
[email protected]a13234c2012-03-20 21:45:0211505 }
11506};
11507
11508TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2211509 SpawnedTestServer::SSLOptions ssl_options(
11510 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5811511 ssl_options.ocsp_status =
11512 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
Eric Romane2243cc62017-10-17 03:59:1311513 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
[email protected]a13234c2012-03-20 21:45:0211514
[email protected]924e9f92012-12-16 22:00:5311515 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1211516 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0211517
11518 // If we're not trying EV verification then, even if the CRLSet has expired,
11519 // we don't fall back to online revocation checks.
11520 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11521 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11522 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11523}
[email protected]51523f52013-07-31 21:57:2811524
Ryan Sleevi5b4702a2018-04-06 22:23:5611525TEST_F(HTTPSCRLSetTest, ExpiredCRLSetAndRevoked) {
11526 // Test that when online revocation checking is disabled, and the leaf
11527 // certificate is not EV, that no revocation checking actually happens.
11528 if (!SystemSupportsOCSP()) {
11529 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
11530 return;
11531 }
11532
11533 SpawnedTestServer::SSLOptions ssl_options(
11534 SpawnedTestServer::SSLOptions::CERT_AUTO);
11535 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
11536 ScopedSetCRLSet set_crlset(CRLSet::ExpiredCRLSetForTesting());
11537
11538 CertStatus cert_status;
11539 DoConnection(ssl_options, &cert_status);
11540
11541 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11542
11543 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
11544 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
11545}
11546
[email protected]51523f52013-07-31 21:57:2811547TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
Eric Romanefddd0a2017-10-10 02:14:2511548#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2811549 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11550 return;
11551#endif
11552
11553 SpawnedTestServer::SSLOptions ssl_options(
11554 SpawnedTestServer::SSLOptions::CERT_AUTO);
11555 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11556 ssl_options.cert_serial = 10;
Eric Romane2243cc62017-10-17 03:59:1311557 ScopedSetCRLSet set_crlset(
Adam Langleyea6d6782017-12-05 23:57:3311558 CRLSet::ForTesting(false, &kOCSPTestCertSPKI, "\x0a", "", {}));
[email protected]51523f52013-07-31 21:57:2811559
11560 CertStatus cert_status = 0;
11561 DoConnection(ssl_options, &cert_status);
11562
11563 // If the certificate is recorded as revoked in the CRLSet, that should be
11564 // reflected without online revocation checking.
11565 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11566 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611567 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
[email protected]51523f52013-07-31 21:57:2811568}
Adam Langleyea6d6782017-12-05 23:57:3311569
11570TEST_F(HTTPSCRLSetTest, CRLSetRevokedBySubject) {
11571#if defined(OS_ANDROID)
11572 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
11573 return;
11574#endif
11575
11576 SpawnedTestServer::SSLOptions ssl_options(
11577 SpawnedTestServer::SSLOptions::CERT_AUTO);
11578 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
11579 static const char kCommonName[] = "Test CN";
11580 ssl_options.cert_common_name = kCommonName;
11581
11582 {
11583 ScopedSetCRLSet set_crlset(
11584 CRLSet::ForTesting(false, nullptr, "", kCommonName, {}));
11585
11586 CertStatus cert_status = 0;
11587 DoConnection(ssl_options, &cert_status);
11588
11589 // If the certificate is recorded as revoked in the CRLSet, that should be
11590 // reflected without online revocation checking.
11591 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
11592 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
Ryan Sleevi5b4702a2018-04-06 22:23:5611593 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
Adam Langleyea6d6782017-12-05 23:57:3311594 }
11595
11596 const uint8_t kTestServerSPKISHA256[32] = {
11597 0xb3, 0x91, 0xac, 0x73, 0x32, 0x54, 0x7f, 0x7b, 0x8a, 0x62, 0x77,
11598 0x73, 0x1d, 0x45, 0x7b, 0x23, 0x46, 0x69, 0xef, 0x6f, 0x05, 0x3d,
11599 0x07, 0x22, 0x15, 0x18, 0xd6, 0x10, 0x8b, 0xa1, 0x49, 0x33,
11600 };
11601 const std::string spki_hash(
11602 reinterpret_cast<const char*>(kTestServerSPKISHA256),
11603 sizeof(kTestServerSPKISHA256));
11604
11605 {
11606 ScopedSetCRLSet set_crlset(
11607 CRLSet::ForTesting(false, nullptr, "", kCommonName, {spki_hash}));
11608
11609 CertStatus cert_status = 0;
11610 DoConnection(ssl_options, &cert_status);
11611
11612 // When the correct SPKI hash is specified, the connection should succeed
11613 // even though the subject is listed in the CRLSet.
11614 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
11615 }
11616}
[email protected]316c1e5e2012-09-12 15:17:4411617#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2711618
Sergey Ulanovc4580e72017-09-13 23:30:1111619#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID) && \
11620 !defined(OS_FUCHSIA)
11621// FTP uses a second TCP connection with the port number allocated dynamically
11622// on the server side, so it would be hard to make RemoteTestServer proxy FTP
11623// connections reliably. FTP tests are disabled on platforms that use
11624// RemoteTestServer. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3111625class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1111626 public:
[email protected]d9fca99a2012-02-24 16:16:2011627 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0511628 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5511629 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4711630 // Can't use |default_context_|'s HostResolver to set up the
11631 // FTPTransactionFactory because it hasn't been created yet.
11632 default_context_.set_host_resolver(&host_resolver_);
11633 }
11634
11635 // URLRequestTest interface:
11636 void SetUpFactory() override {
11637 // Add FTP support to the default URLRequestContext.
11638 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0511639 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4711640 }
11641
11642 std::string GetTestFileContents() {
11643 base::FilePath path;
11644 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
11645 path = path.Append(kTestFilePath);
11646 path = path.AppendASCII(kFtpTestFile);
11647 std::string contents;
11648 EXPECT_TRUE(base::ReadFileToString(path, &contents));
11649 return contents;
[email protected]95409e12010-08-17 20:07:1111650 }
11651
[email protected]b89ca032009-08-31 21:41:3111652 protected:
mmenkecd4c7532016-10-19 18:36:0511653 // Note that this is destroyed before the FtpProtocolHandler that references
11654 // it, which is owned by the parent class. Since no requests are made during
11655 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4711656 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4711657
tommycli59a63432015-11-06 00:10:5511658 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3111659};
11660
[email protected]d2a133182012-08-05 16:44:0811661// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0911662TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0811663 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0811664
11665 TestDelegate d;
11666 {
rhalavatib7bd7c792017-04-27 05:25:1611667 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
11668 url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911669 r->Start();
11670 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0811671
[email protected]255620da2013-08-19 13:14:2911672 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0811673
[email protected]f7022f32014-08-21 16:32:1911674 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5011675 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0811676 }
11677}
11678
mmenke9f2ec60c2015-06-01 20:59:4711679TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5511680 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111681
[email protected]a25e90e2009-09-09 17:05:3711682 TestDelegate d;
11683 {
danakj8522a25b2016-04-16 00:17:3611684 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611685 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d,
11686 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911687 r->Start();
11688 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711689
[email protected]255620da2013-08-19 13:14:2911690 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3711691
[email protected]f7022f32014-08-21 16:32:1911692 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3711693 EXPECT_EQ(1, d.response_started_count());
11694 EXPECT_FALSE(d.received_data_before_response());
11695 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5511696 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911697 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511698 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911699 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3711700 }
11701}
11702
mmenke9f2ec60c2015-06-01 20:59:4711703TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5511704 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111705
[email protected]dd265012009-01-08 20:45:2711706 TestDelegate d;
11707 {
danakj8522a25b2016-04-16 00:17:3611708 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611709 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d,
11710 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911711 r->Start();
11712 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711713
[email protected]255620da2013-08-19 13:14:2911714 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711715
[email protected]f7022f32014-08-21 16:32:1911716 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711717 EXPECT_EQ(1, d.response_started_count());
11718 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711719 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511720 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911721 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511722 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911723 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2711724 }
11725}
11726
mmenke9f2ec60c2015-06-01 20:59:4711727TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5511728 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111729
[email protected]dd265012009-01-08 20:45:2711730 TestDelegate d;
11731 {
danakj8522a25b2016-04-16 00:17:3611732 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511733 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11734 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611735 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911736 r->Start();
11737 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711738
[email protected]255620da2013-08-19 13:14:2911739 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711740
[email protected]f7022f32014-08-21 16:32:1911741 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4711742 EXPECT_EQ(1, d.response_started_count());
11743 EXPECT_FALSE(d.received_data_before_response());
11744 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5511745 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1911746 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5511747 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1911748 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2511749
11750 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1911751 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2511752 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2711753 }
11754}
11755
mmenke9f2ec60c2015-06-01 20:59:4711756TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5511757 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111758
[email protected]dd265012009-01-08 20:45:2711759 TestDelegate d;
11760 {
danakj8522a25b2016-04-16 00:17:3611761 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511762 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11763 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611764 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911765 r->Start();
11766 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711767
[email protected]255620da2013-08-19 13:14:2911768 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711769
[email protected]f7022f32014-08-21 16:32:1911770 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711771 EXPECT_EQ(1, d.response_started_count());
11772 EXPECT_FALSE(d.received_data_before_response());
11773 EXPECT_EQ(d.bytes_received(), 0);
11774 }
11775}
11776
mmenke9f2ec60c2015-06-01 20:59:4711777TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5511778 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111779
[email protected]8b8a197d2009-08-26 15:57:5811780 TestDelegate d;
11781 // Set correct login credentials. The delegate will be asked for them when
11782 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811783 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811784 {
danakj8522a25b2016-04-16 00:17:3611785 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511786 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11787 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611788 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911789 r->Start();
11790 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811791
[email protected]255620da2013-08-19 13:14:2911792 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811793
[email protected]f7022f32014-08-21 16:32:1911794 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811795 EXPECT_EQ(1, d.response_started_count());
11796 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711797 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811798 }
11799}
11800
mmenke9f2ec60c2015-06-01 20:59:4711801TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5511802 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111803
[email protected]dd265012009-01-08 20:45:2711804 TestDelegate d;
11805 {
danakj8522a25b2016-04-16 00:17:3611806 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511807 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11808 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611809 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911810 r->Start();
11811 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711812
[email protected]255620da2013-08-19 13:14:2911813 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2711814
[email protected]f7022f32014-08-21 16:32:1911815 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2711816 EXPECT_EQ(1, d.response_started_count());
11817 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711818 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2711819 }
11820}
[email protected]8b8a197d2009-08-26 15:57:5811821
mmenke9f2ec60c2015-06-01 20:59:4711822TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5511823 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111824
[email protected]8b8a197d2009-08-26 15:57:5811825 TestDelegate d;
11826 // Set correct login credentials. The delegate will be asked for them when
11827 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811828 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5811829 {
danakj8522a25b2016-04-16 00:17:3611830 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511831 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
11832 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611833 DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911834 r->Start();
11835 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811836
[email protected]255620da2013-08-19 13:14:2911837 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5811838
[email protected]f7022f32014-08-21 16:32:1911839 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5811840 EXPECT_EQ(1, d.response_started_count());
11841 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711842 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5811843 }
11844}
[email protected]60a3df52009-09-22 16:13:2411845
mmenke9f2ec60c2015-06-01 20:59:4711846TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5511847 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111848
danakj8522a25b2016-04-16 00:17:3611849 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411850 {
11851 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3611852 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511853 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11854 "chrome"),
rhalavatib7bd7c792017-04-27 05:25:1611855 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911856 r->Start();
11857 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411858
[email protected]255620da2013-08-19 13:14:2911859 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411860
[email protected]f7022f32014-08-21 16:32:1911861 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411862 EXPECT_EQ(1, d->response_started_count());
11863 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711864 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411865 }
11866
11867 d.reset(new TestDelegate);
11868 {
11869 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3611870 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611871 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11872 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911873 r->Start();
11874 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411875
[email protected]255620da2013-08-19 13:14:2911876 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411877
[email protected]f7022f32014-08-21 16:32:1911878 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411879 EXPECT_EQ(1, d->response_started_count());
11880 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711881 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411882 }
11883}
11884
mmenke9f2ec60c2015-06-01 20:59:4711885TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5511886 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1111887
danakj8522a25b2016-04-16 00:17:3611888 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2411889 // Set correct login credentials. The delegate will be asked for them when
11890 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5811891 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2411892 {
danakj8522a25b2016-04-16 00:17:3611893 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5511894 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
11895 "wrong_password"),
rhalavatib7bd7c792017-04-27 05:25:1611896 DEFAULT_PRIORITY, d.get(), TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911897 r->Start();
11898 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411899
[email protected]255620da2013-08-19 13:14:2911900 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411901
[email protected]f7022f32014-08-21 16:32:1911902 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411903 EXPECT_EQ(1, d->response_started_count());
11904 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711905 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411906 }
11907
11908 // Use a new delegate without explicit credentials. The cached ones should be
11909 // used.
11910 d.reset(new TestDelegate);
11911 {
11912 // Don't pass wrong credentials in the URL, they would override valid cached
11913 // ones.
danakj8522a25b2016-04-16 00:17:3611914 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611915 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get(),
11916 TRAFFIC_ANNOTATION_FOR_TESTS));
[email protected]f7022f32014-08-21 16:32:1911917 r->Start();
11918 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411919
[email protected]255620da2013-08-19 13:14:2911920 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2411921
[email protected]f7022f32014-08-21 16:32:1911922 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2411923 EXPECT_EQ(1, d->response_started_count());
11924 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4711925 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2411926 }
11927}
ricea3a1c71f2016-06-17 10:05:2611928
11929TEST_F(URLRequestTestFTP, RawBodyBytes) {
11930 ASSERT_TRUE(ftp_test_server_.Start());
11931
11932 TestDelegate d;
11933 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611934 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d,
11935 TRAFFIC_ANNOTATION_FOR_TESTS));
ricea3a1c71f2016-06-17 10:05:2611936 req->Start();
11937 base::RunLoop().Run();
11938
11939 EXPECT_EQ(6, req->GetRawBodyBytes());
11940}
11941
brettwa1228ebb2016-10-28 03:51:3411942#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5111943
ttuttlec0c828492015-05-15 01:25:5511944TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
11945 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611946 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
11947 GURL("data:,"), DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511948
11949 EXPECT_FALSE(req->response_info().network_accessed);
11950
11951 req->Start();
11952 base::RunLoop().Run();
11953
11954 EXPECT_EQ(1, default_network_delegate_.completed_requests());
11955 EXPECT_FALSE(req->response_info().network_accessed);
11956}
11957
11958TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
11959 MockHostResolver host_resolver;
11960 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
11961 TestURLRequestContext context(true);
11962 context.set_network_delegate(&network_delegate);
11963 context.set_host_resolver(&host_resolver);
11964 host_resolver.rules()->AddSimulatedFailure("*");
11965 context.Init();
11966
11967 TestDelegate d;
rhalavatib7bd7c792017-04-27 05:25:1611968 std::unique_ptr<URLRequest> req(
11969 context.CreateRequest(GURL("http://test_intercept/foo"), DEFAULT_PRIORITY,
11970 &d, TRAFFIC_ANNOTATION_FOR_TESTS));
ttuttlec0c828492015-05-15 01:25:5511971
11972 EXPECT_FALSE(req->response_info().network_accessed);
11973
11974 req->Start();
11975 base::RunLoop().Run();
11976 EXPECT_TRUE(req->response_info().network_accessed);
11977}
11978
mmenkeed0498b2015-12-08 23:20:4211979// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2211980// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4211981TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2211982 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3611983 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
rhalavatib7bd7c792017-04-27 05:25:1611984 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d,
11985 TRAFFIC_ANNOTATION_FOR_TESTS));
alexanderkcd904b52015-07-24 18:57:2211986
danakj8522a25b2016-04-16 00:17:3611987 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2211988 req.get(), &default_network_delegate_,
11989 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4211990 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
11991 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2211992
11993 req->Start();
11994 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2211995 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5011996 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2211997 EXPECT_EQ(0, d.received_redirect_count());
11998}
11999
Andrey Kosyakov2e893e62017-08-31 17:00:5212000TEST_F(URLRequestTestHTTP, HeadersCallbacks) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412001 ASSERT_TRUE(http_test_server()->Start());
12002 TestURLRequestContext context;
12003 GURL url(http_test_server()->GetURL("/cachetime"));
12004 TestDelegate delegate;
12005 HttpRequestHeaders extra_headers;
12006 extra_headers.SetHeader("X-Foo", "bar");
12007
12008 {
Andrey Kosyakov2e893e62017-08-31 17:00:5212009 HttpRawRequestHeaders raw_req_headers;
12010 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12011
Andrey Kosyakov83a6eee2017-08-14 19:20:0412012 std::unique_ptr<URLRequest> r(context.CreateRequest(
12013 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12014 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212015 r->SetRequestHeadersCallback(base::Bind(
12016 &HttpRawRequestHeaders::Assign, base::Unretained(&raw_req_headers)));
12017 r->SetResponseHeadersCallback(base::Bind(
12018 [](scoped_refptr<const HttpResponseHeaders>* left,
12019 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12020 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412021 r->Start();
12022 while (!delegate.response_started_count())
12023 base::RunLoop().RunUntilIdle();
Andrey Kosyakov2e893e62017-08-31 17:00:5212024 EXPECT_FALSE(raw_req_headers.headers().empty());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412025 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212026 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412027 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212028 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412029 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212030 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Connection", &value));
12031 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Host", &value));
12032 EXPECT_EQ("GET /cachetime HTTP/1.1\r\n", raw_req_headers.request_line());
12033 EXPECT_EQ(raw_resp_headers.get(), r->response_headers());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412034 }
12035 {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412036 std::unique_ptr<URLRequest> r(context.CreateRequest(
12037 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12038 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212039 r->SetRequestHeadersCallback(base::Bind([](HttpRawRequestHeaders) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412040 FAIL() << "Callback should not be called unless request is sent";
12041 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212042 r->SetResponseHeadersCallback(
12043 base::Bind([](scoped_refptr<const HttpResponseHeaders>) {
12044 FAIL() << "Callback should not be called unless request is sent";
12045 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412046 r->Start();
12047 base::RunLoop().Run();
12048 EXPECT_TRUE(r->was_cached());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412049 }
12050}
12051
Andrey Kosyakov2e893e62017-08-31 17:00:5212052TEST_F(URLRequestTestHTTP, HeadersCallbacksWithRedirect) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412053 ASSERT_TRUE(http_test_server()->Start());
Andrey Kosyakov2e893e62017-08-31 17:00:5212054 HttpRawRequestHeaders raw_req_headers;
12055 scoped_refptr<const HttpResponseHeaders> raw_resp_headers;
12056
Andrey Kosyakov83a6eee2017-08-14 19:20:0412057 TestURLRequestContext context;
12058 TestDelegate delegate;
12059 HttpRequestHeaders extra_headers;
12060 extra_headers.SetHeader("X-Foo", "bar");
12061 delegate.set_quit_on_redirect(true);
12062 GURL url(http_test_server()->GetURL("/redirect-test.html"));
12063 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12064 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12065 r->SetExtraRequestHeaders(extra_headers);
12066 r->SetRequestHeadersCallback(base::Bind(&HttpRawRequestHeaders::Assign,
Andrey Kosyakov2e893e62017-08-31 17:00:5212067 base::Unretained(&raw_req_headers)));
12068 r->SetResponseHeadersCallback(base::Bind(
12069 [](scoped_refptr<const HttpResponseHeaders>* left,
12070 scoped_refptr<const HttpResponseHeaders> right) { *left = right; },
12071 base::Unretained(&raw_resp_headers)));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412072 r->Start();
12073 base::RunLoop().Run();
12074
12075 ASSERT_EQ(1, delegate.received_redirect_count());
12076 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212077 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412078 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212079 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412080 EXPECT_EQ("gzip, deflate", value);
12081 EXPECT_EQ(1, delegate.received_redirect_count());
Andrey Kosyakov2e893e62017-08-31 17:00:5212082 EXPECT_EQ("GET /redirect-test.html HTTP/1.1\r\n",
12083 raw_req_headers.request_line());
12084 EXPECT_TRUE(raw_resp_headers->HasHeader("Location"));
12085 EXPECT_EQ(302, raw_resp_headers->response_code());
12086 EXPECT_EQ("Redirect", raw_resp_headers->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412087
Andrey Kosyakov2e893e62017-08-31 17:00:5212088 raw_req_headers = HttpRawRequestHeaders();
12089 raw_resp_headers = nullptr;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412090 r->FollowDeferredRedirect();
12091 base::RunLoop().Run();
Andrey Kosyakov2e893e62017-08-31 17:00:5212092 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412093 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212094 EXPECT_TRUE(raw_req_headers.FindHeaderForTest("Accept-Encoding", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412095 EXPECT_EQ("gzip, deflate", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212096 EXPECT_EQ("GET /with-headers.html HTTP/1.1\r\n",
12097 raw_req_headers.request_line());
12098 EXPECT_EQ(r->response_headers(), raw_resp_headers.get());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412099}
12100
Andrey Kosyakov2e893e62017-08-31 17:00:5212101TEST_F(URLRequestTest, HeadersCallbacksConnectFailed) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412102 TestDelegate request_delegate;
12103
12104 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12105 GURL("http://127.0.0.1:9/"), DEFAULT_PRIORITY, &request_delegate,
12106 TRAFFIC_ANNOTATION_FOR_TESTS));
12107 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
12108 FAIL() << "Callback should not be called unless request is sent";
12109 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212110 r->SetResponseHeadersCallback(
12111 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12112 FAIL() << "Callback should not be called unless request is sent";
12113 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412114 r->Start();
12115 base::RunLoop().Run();
12116 EXPECT_FALSE(r->is_pending());
12117}
12118
Andrey Kosyakov2e893e62017-08-31 17:00:5212119TEST_F(URLRequestTestHTTP, HeadersCallbacksAuthRetry) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412120 ASSERT_TRUE(http_test_server()->Start());
12121 GURL url(http_test_server()->GetURL("/auth-basic"));
12122
12123 TestURLRequestContext context;
12124 TestDelegate delegate;
12125
12126 delegate.set_credentials(AuthCredentials(kUser, kSecret));
12127 HttpRequestHeaders extra_headers;
12128 extra_headers.SetHeader("X-Foo", "bar");
12129
Andrey Kosyakov2e893e62017-08-31 17:00:5212130 using ReqHeadersVector = std::vector<std::unique_ptr<HttpRawRequestHeaders>>;
12131 ReqHeadersVector raw_req_headers;
Andrey Kosyakov83a6eee2017-08-14 19:20:0412132
Andrey Kosyakov2e893e62017-08-31 17:00:5212133 using RespHeadersVector =
12134 std::vector<scoped_refptr<const HttpResponseHeaders>>;
12135 RespHeadersVector raw_resp_headers;
12136
12137 auto req_headers_callback = base::Bind(
12138 [](ReqHeadersVector* vec, HttpRawRequestHeaders headers) {
12139 vec->emplace_back(new HttpRawRequestHeaders(std::move(headers)));
12140 },
12141 &raw_req_headers);
12142 auto resp_headers_callback = base::Bind(
12143 [](RespHeadersVector* vec,
12144 scoped_refptr<const HttpResponseHeaders> headers) {
12145 vec->push_back(headers);
12146 },
12147 &raw_resp_headers);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412148 std::unique_ptr<URLRequest> r(context.CreateRequest(
12149 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12150 r->SetExtraRequestHeaders(extra_headers);
Andrey Kosyakov2e893e62017-08-31 17:00:5212151 r->SetRequestHeadersCallback(req_headers_callback);
12152 r->SetResponseHeadersCallback(resp_headers_callback);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412153 r->Start();
12154 base::RunLoop().Run();
12155 EXPECT_FALSE(r->is_pending());
Andrey Kosyakov2e893e62017-08-31 17:00:5212156 ASSERT_EQ(raw_req_headers.size(), 2u);
12157 ASSERT_EQ(raw_resp_headers.size(), 2u);
Andrey Kosyakov83a6eee2017-08-14 19:20:0412158 std::string value;
Andrey Kosyakov2e893e62017-08-31 17:00:5212159 EXPECT_FALSE(raw_req_headers[0]->FindHeaderForTest("Authorization", &value));
12160 EXPECT_TRUE(raw_req_headers[0]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412161 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212162 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("Authorization", &value));
12163 EXPECT_TRUE(raw_req_headers[1]->FindHeaderForTest("X-Foo", &value));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412164 EXPECT_EQ("bar", value);
Andrey Kosyakov2e893e62017-08-31 17:00:5212165 EXPECT_EQ(raw_resp_headers[1], r->response_headers());
12166 EXPECT_NE(raw_resp_headers[0], raw_resp_headers[1]);
12167 EXPECT_EQ(401, raw_resp_headers[0]->response_code());
12168 EXPECT_EQ("Unauthorized", raw_resp_headers[0]->GetStatusText());
12169
12170 std::unique_ptr<URLRequest> r2(context.CreateRequest(
12171 url, DEFAULT_PRIORITY, &delegate, TRAFFIC_ANNOTATION_FOR_TESTS));
12172 r2->SetExtraRequestHeaders(extra_headers);
12173 r2->SetRequestHeadersCallback(req_headers_callback);
12174 r2->SetResponseHeadersCallback(resp_headers_callback);
12175 r2->SetLoadFlags(LOAD_VALIDATE_CACHE);
12176 r2->Start();
12177 base::RunLoop().Run();
12178 EXPECT_FALSE(r2->is_pending());
12179 ASSERT_EQ(raw_req_headers.size(), 3u);
12180 ASSERT_EQ(raw_resp_headers.size(), 3u);
12181 EXPECT_TRUE(raw_req_headers[2]->FindHeaderForTest("If-None-Match", &value));
12182 EXPECT_NE(raw_resp_headers[2].get(), r2->response_headers());
12183 EXPECT_EQ(304, raw_resp_headers[2]->response_code());
12184 EXPECT_EQ("Not Modified", raw_resp_headers[2]->GetStatusText());
Andrey Kosyakov83a6eee2017-08-14 19:20:0412185}
12186
Andrey Kosyakov2e893e62017-08-31 17:00:5212187TEST_F(URLRequestTest, HeadersCallbacksNonHTTP) {
Andrey Kosyakov83a6eee2017-08-14 19:20:0412188 GURL data_url("data:text/html,<html><body>Hello!</body></html>");
12189 TestDelegate d;
12190 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
12191 data_url, DEFAULT_PRIORITY, &d, TRAFFIC_ANNOTATION_FOR_TESTS));
12192 r->SetRequestHeadersCallback(base::Bind([](net::HttpRawRequestHeaders) {
Andrey Kosyakov2e893e62017-08-31 17:00:5212193 FAIL() << "Callback should not be called for non-HTTP schemes";
Andrey Kosyakov83a6eee2017-08-14 19:20:0412194 }));
Andrey Kosyakov2e893e62017-08-31 17:00:5212195 r->SetResponseHeadersCallback(
12196 base::Bind([](scoped_refptr<const net::HttpResponseHeaders>) {
12197 FAIL() << "Callback should not be called for non-HTTP schemes";
12198 }));
Andrey Kosyakov83a6eee2017-08-14 19:20:0412199 r->Start();
12200 base::RunLoop().Run();
12201 EXPECT_FALSE(r->is_pending());
12202}
12203
Paul Jensen60e45532018-02-19 16:04:1812204// Test that URLRequests get properly tagged.
12205#if defined(OS_ANDROID)
12206TEST_F(URLRequestTestHTTP, TestTagging) {
12207 ASSERT_TRUE(http_test_server()->Start());
12208
12209 // The tag under which the system reports untagged traffic.
12210 static const int32_t UNTAGGED_TAG = 0;
12211
12212 uint64_t old_traffic = GetTaggedBytes(UNTAGGED_TAG);
12213
12214 // Untagged traffic should be tagged with tag UNTAGGED_TAG.
12215 TestDelegate delegate;
12216 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
12217 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &delegate,
12218 TRAFFIC_ANNOTATION_FOR_TESTS));
12219 EXPECT_EQ(SocketTag(), req->socket_tag());
12220 req->Start();
12221 base::RunLoop().Run();
12222
12223 EXPECT_GT(GetTaggedBytes(UNTAGGED_TAG), old_traffic);
12224
12225 int32_t tag_val1 = 0x12345678;
12226 SocketTag tag1(SocketTag::UNSET_UID, tag_val1);
12227 old_traffic = GetTaggedBytes(tag_val1);
12228
12229 // Test specific tag value.
12230 req = default_context_.CreateRequest(http_test_server()->GetURL("/"),
12231 DEFAULT_PRIORITY, &delegate,
12232 TRAFFIC_ANNOTATION_FOR_TESTS);
12233 req->set_socket_tag(tag1);
12234 EXPECT_EQ(tag1, req->socket_tag());
12235 req->Start();
12236 base::RunLoop().Run();
12237
12238 EXPECT_GT(GetTaggedBytes(tag_val1), old_traffic);
12239}
12240#endif
12241
[email protected]7461a402011-03-24 23:19:5112242} // namespace net