blob: c10a582ee4e84082c706e993283de038078cd8ad [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
danakj8522a25b2016-04-16 00:17:365#include <memory>
dchengc7eeda422015-12-26 03:56:486#include <utility>
7
danakj8522a25b2016-04-16 00:17:368#include "base/memory/ptr_util.h"
fdoray5eeb7642016-06-22 16:11:289#include "base/run_loop.h"
[email protected]ea224582008-12-07 20:25:4610#include "build/build_config.h"
11
[email protected]9396b252008-09-29 17:29:3812#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:0613#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:0614#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3815#endif
16
tbansalea2fb8c2015-05-22 22:23:0017#include <stdint.h>
18
initial.commit586acc5fe2008-07-26 22:42:5219#include <algorithm>
avibf0746c2015-12-09 19:53:1420#include <limits>
initial.commit586acc5fe2008-07-26 22:42:5221
nharperb7441ef2016-01-25 23:54:1422#include "base/base64url.h"
[email protected]218aa6a12011-09-13 17:38:3823#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5824#include "base/compiler_specific.h"
mmenke9f2ec60c2015-06-01 20:59:4725#include "base/files/file_path.h"
thestigd8df0332014-09-04 06:33:2926#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0727#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2828#include "base/format_macros.h"
estark06e0dac2015-08-07 21:56:0129#include "base/json/json_reader.h"
skyostil4891b25b2015-06-11 11:43:4530#include "base/location.h"
Avi Drissman13fc8932015-12-20 04:40:4631#include "base/macros.h"
[email protected]084262c2011-12-01 21:12:4732#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2233#include "base/message_loop/message_loop.h"
initial.commit586acc5fe2008-07-26 22:42:5234#include "base/path_service.h"
mmenkefb18c772015-09-30 22:22:5035#include "base/power_monitor/power_monitor.h"
36#include "base/power_monitor/power_monitor_source.h"
[email protected]255620da2013-08-19 13:14:2937#include "base/run_loop.h"
skyostil4891b25b2015-06-11 11:43:4538#include "base/single_thread_task_runner.h"
[email protected]4dc3ad4f2013-06-11 07:15:5039#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5540#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2241#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2242#include "base/strings/string_util.h"
43#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0544#include "base/strings/utf_string_conversions.h"
tbansalea2fb8c2015-05-22 22:23:0045#include "base/test/histogram_tester.h"
fdoraya89e673c2017-01-31 21:44:2146#include "base/test/scoped_task_scheduler.h"
gabf767595f2016-05-11 18:50:3547#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0148#include "base/values.h"
mmenkecbc2b712014-10-09 20:29:0749#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0750#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0751#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5252#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2553#include "net/base/load_timing_info.h"
54#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0655#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5256#include "net/base/net_module.h"
[email protected]2ca01e52013-10-31 22:05:1957#include "net/base/request_priority.h"
zhongyi18ddddd2017-02-03 19:06:3658#include "net/base/test_completion_callback.h"
[email protected]f288ef02012-12-15 20:28:2859#include "net/base/upload_bytes_element_reader.h"
60#include "net/base/upload_data_stream.h"
61#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4462#include "net/base/url_util.h"
rsleevid6de8302016-06-21 01:33:2063#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4764#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3665#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1166#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2467#include "net/cert/mock_cert_verifier.h"
zhongyi18ddddd2017-02-03 19:06:3668#include "net/cert/multi_log_ct_verifier.h"
eranmdcec9632016-10-10 14:16:1069#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1170#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4971#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0672#include "net/cookies/cookie_monster.h"
73#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5274#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5375#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3876#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5277#include "net/http/http_cache.h"
78#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1979#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2580#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2181#include "net/http/http_response_headers.h"
zhongyi18ddddd2017-02-03 19:06:3682#include "net/http/http_server_properties_impl.h"
[email protected]e50efea2014-03-24 18:41:0083#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0084#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1985#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5186#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4687#include "net/log/test_net_log_entry.h"
88#include "net/log/test_net_log_util.h"
brettwa1228ebb2016-10-28 03:51:3489#include "net/net_features.h"
tbansalca83c002016-04-28 20:56:2890#include "net/nqe/external_estimate_provider.h"
tbansal2ecbbc72016-10-06 17:15:4791#include "net/proxy/proxy_server.h"
[email protected]63de95b2008-12-10 04:11:2792#include "net/proxy/proxy_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"
98#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:5799#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:55100#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:14101#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:11102#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:36103#include "net/test/embedded_test_server/embedded_test_server.h"
104#include "net/test/embedded_test_server/http_request.h"
105#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:01106#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21107#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43108#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:50109#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:34110#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43111#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52112#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50113#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14114#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50115#include "net/url_request/url_request_intercepting_job_factory.h"
116#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49117#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51118#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47119#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44120#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01121#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52122#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15123#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52124
brettwa1228ebb2016-10-28 03:51:34125#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55126#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29127#include "net/url_request/file_protocol_handler.h"
128#include "net/url_request/url_request_file_dir_job.h"
129#endif
130
brettwa1228ebb2016-10-28 03:51:34131#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47132#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29133#include "net/url_request/ftp_protocol_handler.h"
134#endif
135
[email protected]dffe8242012-03-20 15:14:27136#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48137#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56138#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27139#endif
140
robpercival214763f2016-07-01 23:27:01141using net::test::IsError;
142using net::test::IsOk;
143
[email protected]ad65a3e2013-12-25 18:18:01144using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33145using base::Time;
halton.huoe4e45742014-12-08 07:55:46146using std::string;
[email protected]e1acf6f2008-10-27 20:43:33147
[email protected]7461a402011-03-24 23:19:51148namespace net {
149
initial.commit586acc5fe2008-07-26 22:42:52150namespace {
151
[email protected]42cba2fb2013-03-29 19:58:57152const base::string16 kChrome(ASCIIToUTF16("chrome"));
153const base::string16 kSecret(ASCIIToUTF16("secret"));
154const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44155
mmenke9f2ec60c2015-06-01 20:59:47156const base::FilePath::CharType kTestFilePath[] =
157 FILE_PATH_LITERAL("net/data/url_request_unittest");
158
brettwa1228ebb2016-10-28 03:51:34159#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47160// Test file used in most FTP tests.
161const char kFtpTestFile[] = "BullRunSpeech.txt";
162#endif
163
[email protected]2bba3252013-04-08 19:50:59164// Tests load timing information in the case a fresh connection was used, with
165// no proxy.
[email protected]cba24642014-08-15 20:49:59166void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25167 int connect_timing_flags) {
168 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19169 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25170
171 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
172 EXPECT_FALSE(load_timing_info.request_start.is_null());
173
174 EXPECT_LE(load_timing_info.request_start,
175 load_timing_info.connect_timing.connect_start);
176 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
177 connect_timing_flags);
178 EXPECT_LE(load_timing_info.connect_timing.connect_end,
179 load_timing_info.send_start);
180 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
181 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
182
[email protected]58e32bb2013-01-21 18:23:25183 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
184 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
185}
186
[email protected]2bba3252013-04-08 19:50:59187// Same as above, but with proxy times.
188void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59189 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59190 int connect_timing_flags) {
191 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19192 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59193
194 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
195 EXPECT_FALSE(load_timing_info.request_start.is_null());
196
197 EXPECT_LE(load_timing_info.request_start,
198 load_timing_info.proxy_resolve_start);
199 EXPECT_LE(load_timing_info.proxy_resolve_start,
200 load_timing_info.proxy_resolve_end);
201 EXPECT_LE(load_timing_info.proxy_resolve_end,
202 load_timing_info.connect_timing.connect_start);
203 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
204 connect_timing_flags);
205 EXPECT_LE(load_timing_info.connect_timing.connect_end,
206 load_timing_info.send_start);
207 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
208 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
209}
210
211// Same as above, but with a reused socket and proxy times.
212void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59213 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59214 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19215 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59216
217 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
218 EXPECT_FALSE(load_timing_info.request_start.is_null());
219
220 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
221
222 EXPECT_LE(load_timing_info.request_start,
223 load_timing_info.proxy_resolve_start);
224 EXPECT_LE(load_timing_info.proxy_resolve_start,
225 load_timing_info.proxy_resolve_end);
226 EXPECT_LE(load_timing_info.proxy_resolve_end,
227 load_timing_info.send_start);
228 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
229 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
230}
231
brettwa1228ebb2016-10-28 03:51:34232#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25233// Tests load timing information in the case of a cache hit, when no cache
234// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17235base::StringPiece TestNetResourceProvider(int key) {
236 return "header";
237}
238
239void FillBuffer(char* buffer, size_t len) {
240 static bool called = false;
241 if (!called) {
242 called = true;
243 int seed = static_cast<int>(Time::Now().ToInternalValue());
244 srand(seed);
245 }
246
247 for (size_t i = 0; i < len; i++) {
248 buffer[i] = static_cast<char>(rand());
249 if (!buffer[i])
250 buffer[i] = 'g';
251 }
252}
xunjielia6888202015-04-14 21:34:25253#endif
[email protected]e3a85452013-11-14 01:46:17254
[email protected]3b23a222013-05-15 21:33:25255void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59256 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25257 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19258 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25259
260 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
261 EXPECT_FALSE(load_timing_info.request_start.is_null());
262
263 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
264 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
265 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
266 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
267
268 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
269 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
270}
271
brettwa1228ebb2016-10-28 03:51:34272#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25273// Tests load timing in the case that there is no HTTP response. This can be
274// used to test in the case of errors or non-HTTP requests.
275void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59276 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25277 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19278 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25279
280 // Only the request times should be non-null.
281 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
282 EXPECT_FALSE(load_timing_info.request_start.is_null());
283
284 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
285
286 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
287 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
288 EXPECT_TRUE(load_timing_info.send_start.is_null());
289 EXPECT_TRUE(load_timing_info.send_end.is_null());
290 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
291}
xunjielia6888202015-04-14 21:34:25292#endif
[email protected]58e32bb2013-01-21 18:23:25293
mmenkefb18c772015-09-30 22:22:50294// Test power monitor source that can simulate entering suspend mode. Can't use
295// the one in base/ because it insists on bringing its own MessageLoop.
296class TestPowerMonitorSource : public base::PowerMonitorSource {
297 public:
298 TestPowerMonitorSource() {}
299 ~TestPowerMonitorSource() override {}
300
301 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
302
303 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
304
305 bool IsOnBatteryPowerImpl() override { return false; }
306
307 private:
308 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
309};
310
mmenkeed0498b2015-12-08 23:20:42311// Job that allows monitoring of its priority.
312class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
313 public:
314 // The latest priority of the job is always written to |request_priority_|.
315 PriorityMonitoringURLRequestJob(URLRequest* request,
316 NetworkDelegate* network_delegate,
317 RequestPriority* request_priority)
318 : URLRequestTestJob(request, network_delegate),
319 request_priority_(request_priority) {
320 *request_priority_ = DEFAULT_PRIORITY;
321 }
322
323 void SetPriority(RequestPriority priority) override {
324 *request_priority_ = priority;
325 URLRequestTestJob::SetPriority(priority);
326 }
327
328 private:
329 RequestPriority* const request_priority_;
330};
331
[email protected]71c64f62008-11-15 04:36:51332// Do a case-insensitive search through |haystack| for |needle|.
333bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50334 std::string::const_iterator it = std::search(
335 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
336 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51337 return it != haystack.end();
338}
339
danakj8522a25b2016-04-16 00:17:36340std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
341 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28342 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48343 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23344}
345
[email protected]96adadb2010-08-28 01:16:17346// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51347void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17348 // -1 means unknown. 0 means no encryption.
349 EXPECT_GT(ssl_info.security_bits, 0);
350
351 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14352 uint16_t cipher_suite =
353 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29354 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17355}
356
[email protected]79e1fd62013-06-20 06:50:04357void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
358 const GURL& host_url) {
359 std::string sent_value;
360
361 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
362 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
363
364 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
365 EXPECT_EQ("keep-alive", sent_value);
366}
367
[email protected]dc5a5cf2012-09-26 02:49:30368// A network delegate that allows the user to choose a subset of request stages
369// to block in. When blocking, the delegate can do one of the following:
370// * synchronously return a pre-specified error code, or
371// * asynchronously return that value via an automatically called callback,
372// or
373// * block and wait for the user to do a callback.
374// Additionally, the user may also specify a redirect URL -- then each request
375// with the current URL different from the redirect target will be redirected
376// to that target, in the on-before-URL-request stage, independent of whether
377// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12378class BlockingNetworkDelegate : public TestNetworkDelegate {
379 public:
[email protected]dc5a5cf2012-09-26 02:49:30380 // Stages in which the delegate can block.
381 enum Stage {
[email protected]9045b8822012-01-13 20:35:35382 NOT_BLOCKED = 0,
383 ON_BEFORE_URL_REQUEST = 1 << 0,
384 ON_BEFORE_SEND_HEADERS = 1 << 1,
385 ON_HEADERS_RECEIVED = 1 << 2,
386 ON_AUTH_REQUIRED = 1 << 3
387 };
388
[email protected]dc5a5cf2012-09-26 02:49:30389 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59390 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30391 enum BlockMode {
392 SYNCHRONOUS, // No callback, returns specified return values.
393 AUTO_CALLBACK, // |this| posts a task to run the callback using the
394 // specified return codes.
395 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
396 // |auth_retval_| are ignored. In every blocking stage the
397 // message loop is quit.
rdsmithbf8c3c12016-11-18 18:16:24398 USER_NOTIFY, // User is notified by a provided callback of the
399 // blocking, and synchronously returns instructions
400 // for handling it.
[email protected]dc5a5cf2012-09-26 02:49:30401 };
402
rdsmithbf8c3c12016-11-18 18:16:24403 using NotificationCallback =
404 base::Callback<Error(const CompletionCallback&, const URLRequest*)>;
405
406 using NotificationAuthCallback =
407 base::Callback<NetworkDelegate::AuthRequiredResponse(const AuthCallback&,
408 const URLRequest*)>;
409
[email protected]dc5a5cf2012-09-26 02:49:30410 // Creates a delegate which does not block at all.
411 explicit BlockingNetworkDelegate(BlockMode block_mode);
412
413 // For users to trigger a callback returning |response|.
414 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
415 // Only call if |block_mode_| == USER_CALLBACK.
416 void DoCallback(int response);
417 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
418
419 // Setters.
420 void set_retval(int retval) {
421 ASSERT_NE(USER_CALLBACK, block_mode_);
422 ASSERT_NE(ERR_IO_PENDING, retval);
423 ASSERT_NE(OK, retval);
424 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35425 }
426
[email protected]dc5a5cf2012-09-26 02:49:30427 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
428 // |auth_credentials_| will be passed with the response.
429 void set_auth_retval(AuthRequiredResponse auth_retval) {
430 ASSERT_NE(USER_CALLBACK, block_mode_);
431 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
432 auth_retval_ = auth_retval;
433 }
434 void set_auth_credentials(const AuthCredentials& auth_credentials) {
435 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35436 }
437
[email protected]dc5a5cf2012-09-26 02:49:30438 void set_redirect_url(const GURL& url) {
439 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35440 }
441
[email protected]dc5a5cf2012-09-26 02:49:30442 void set_block_on(int block_on) {
443 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35444 }
445
rdsmithbf8c3c12016-11-18 18:16:24446 // Only valid if |block_mode_| == USER_NOTIFY
447 void set_notification_callback(
448 const NotificationCallback& notification_callback) {
449 notification_callback_ = notification_callback;
450 }
451
452 void set_notification_auth_callback(
453 const NotificationAuthCallback& notification_auth_callback) {
454 notification_auth_callback_ = notification_auth_callback;
455 }
456
[email protected]dc5a5cf2012-09-26 02:49:30457 // Allows the user to check in which state did we block.
458 Stage stage_blocked_for_callback() const {
459 EXPECT_EQ(USER_CALLBACK, block_mode_);
460 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35461 }
462
463 private:
[email protected]dc5a5cf2012-09-26 02:49:30464 void RunCallback(int response, const CompletionCallback& callback);
465 void RunAuthCallback(AuthRequiredResponse response,
466 const AuthCallback& callback);
467
[email protected]9045b8822012-01-13 20:35:35468 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20469 int OnBeforeURLRequest(URLRequest* request,
470 const CompletionCallback& callback,
471 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35472
ryansturm2343cb62016-06-15 01:09:00473 int OnBeforeStartTransaction(URLRequest* request,
474 const CompletionCallback& callback,
475 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35476
dchengb03027d2014-10-21 12:00:20477 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35478 URLRequest* request,
479 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32480 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16481 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13482 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35483
dchengb03027d2014-10-21 12:00:20484 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35485 URLRequest* request,
486 const AuthChallengeInfo& auth_info,
487 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13488 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35489
[email protected]dc5a5cf2012-09-26 02:49:30490 // Resets the callbacks and |stage_blocked_for_callback_|.
491 void Reset();
[email protected]9045b8822012-01-13 20:35:35492
[email protected]dc5a5cf2012-09-26 02:49:30493 // Checks whether we should block in |stage|. If yes, returns an error code
494 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24495 int MaybeBlockStage(Stage stage,
496 const URLRequest* request,
497 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30498
499 // Configuration parameters, can be adjusted by public methods:
500 const BlockMode block_mode_;
501
502 // Values returned on blocking stages when mode is SYNCHRONOUS or
503 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
504 int retval_; // To be returned in non-auth stages.
505 AuthRequiredResponse auth_retval_;
506
[email protected]5f714132014-03-26 10:41:16507 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30508 int block_on_; // Bit mask: in which stages to block.
509
510 // |auth_credentials_| will be copied to |*target_auth_credential_| on
511 // callback.
512 AuthCredentials auth_credentials_;
513 AuthCredentials* target_auth_credentials_;
514
515 // Internal variables, not set by not the user:
516 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
517 // USER_CALLBACK).
518 Stage stage_blocked_for_callback_;
519
520 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35521 CompletionCallback callback_;
522 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30523
rdsmithbf8c3c12016-11-18 18:16:24524 // Callback to request user instructions for blocking.
525 NotificationCallback notification_callback_;
526 NotificationAuthCallback notification_auth_callback_;
527
[email protected]dc5a5cf2012-09-26 02:49:30528 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
529
530 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35531};
532
[email protected]dc5a5cf2012-09-26 02:49:30533BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
534 : block_mode_(block_mode),
535 retval_(OK),
536 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
537 block_on_(0),
538 target_auth_credentials_(NULL),
539 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32540 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30541}
542
543void BlockingNetworkDelegate::DoCallback(int response) {
544 ASSERT_EQ(USER_CALLBACK, block_mode_);
545 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
546 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
547 CompletionCallback callback = callback_;
548 Reset();
549 RunCallback(response, callback);
550}
551
552void BlockingNetworkDelegate::DoAuthCallback(
553 NetworkDelegate::AuthRequiredResponse response) {
554 ASSERT_EQ(USER_CALLBACK, block_mode_);
555 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
556 AuthCallback auth_callback = auth_callback_;
557 Reset();
558 RunAuthCallback(response, auth_callback);
559}
560
561void BlockingNetworkDelegate::RunCallback(int response,
562 const CompletionCallback& callback) {
563 callback.Run(response);
564}
565
566void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
567 const AuthCallback& callback) {
568 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
569 ASSERT_TRUE(target_auth_credentials_ != NULL);
570 *target_auth_credentials_ = auth_credentials_;
571 }
572 callback.Run(response);
573}
574
575int BlockingNetworkDelegate::OnBeforeURLRequest(
576 URLRequest* request,
577 const CompletionCallback& callback,
578 GURL* new_url) {
579 if (redirect_url_ == request->url())
580 return OK; // We've already seen this request and redirected elsewhere.
581
582 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
583
584 if (!redirect_url_.is_empty())
585 *new_url = redirect_url_;
586
rdsmithbf8c3c12016-11-18 18:16:24587 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30588}
589
ryansturm2343cb62016-06-15 01:09:00590int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30591 URLRequest* request,
592 const CompletionCallback& callback,
593 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00594 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30595
rdsmithbf8c3c12016-11-18 18:16:24596 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30597}
598
599int BlockingNetworkDelegate::OnHeadersReceived(
600 URLRequest* request,
601 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32602 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16603 scoped_refptr<HttpResponseHeaders>* override_response_headers,
604 GURL* allowed_unsafe_redirect_url) {
605 TestNetworkDelegate::OnHeadersReceived(request,
606 callback,
607 original_response_headers,
608 override_response_headers,
609 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30610
rdsmithbf8c3c12016-11-18 18:16:24611 return MaybeBlockStage(ON_HEADERS_RECEIVED, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30612}
613
614NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
615 URLRequest* request,
616 const AuthChallengeInfo& auth_info,
617 const AuthCallback& callback,
618 AuthCredentials* credentials) {
619 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
620 credentials);
621 // Check that the user has provided callback for the previous blocked stage.
622 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
623
624 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
625 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
626 }
627
628 target_auth_credentials_ = credentials;
629
630 switch (block_mode_) {
631 case SYNCHRONOUS:
632 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
633 *target_auth_credentials_ = auth_credentials_;
634 return auth_retval_;
635
636 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45637 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30638 FROM_HERE,
639 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
640 weak_factory_.GetWeakPtr(), auth_retval_, callback));
641 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
642
643 case USER_CALLBACK:
644 auth_callback_ = callback;
645 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45646 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17647 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30648 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24649
650 case USER_NOTIFY:
651 // If the callback returns ERR_IO_PENDING, the user has accepted
652 // responsibility for running the callback in the future.
653 return notification_auth_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30654 }
655 NOTREACHED();
656 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
657}
658
659void BlockingNetworkDelegate::Reset() {
660 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
661 stage_blocked_for_callback_ = NOT_BLOCKED;
662 callback_.Reset();
663 auth_callback_.Reset();
664}
665
666int BlockingNetworkDelegate::MaybeBlockStage(
667 BlockingNetworkDelegate::Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24668 const URLRequest* request,
[email protected]dc5a5cf2012-09-26 02:49:30669 const CompletionCallback& callback) {
670 // Check that the user has provided callback for the previous blocked stage.
671 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
672
673 if ((block_on_ & stage) == 0) {
674 return OK;
675 }
676
677 switch (block_mode_) {
678 case SYNCHRONOUS:
679 EXPECT_NE(OK, retval_);
680 return retval_;
681
682 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45683 base::ThreadTaskRunnerHandle::Get()->PostTask(
684 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
685 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30686 return ERR_IO_PENDING;
687
688 case USER_CALLBACK:
689 callback_ = callback;
690 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45691 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17692 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30693 return ERR_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24694
695 case USER_NOTIFY:
696 // If the callback returns ERR_IO_PENDING, the user has accepted
697 // responsibility for running the callback in the future.
698 return notification_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30699 }
700 NOTREACHED();
701 return 0;
702}
703
[email protected]d5a4dd62012-05-23 01:41:04704class TestURLRequestContextWithProxy : public TestURLRequestContext {
705 public:
706 // Does not own |delegate|.
707 TestURLRequestContextWithProxy(const std::string& proxy,
708 NetworkDelegate* delegate)
709 : TestURLRequestContext(true) {
710 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
711 set_network_delegate(delegate);
712 Init();
713 }
dchengb03027d2014-10-21 12:00:20714 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04715};
716
stefanocsbd5be5202016-06-10 03:37:55717// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01718// URI and report to be sent.
719class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55720 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01721 public:
722 MockCertificateReportSender() {}
723 ~MockCertificateReportSender() override {}
724
meacer8c164432016-11-15 03:56:49725 void Send(
726 const GURL& report_uri,
727 base::StringPiece content_type,
728 base::StringPiece report,
729 const base::Callback<void()>& success_callback,
730 const base::Callback<void(const GURL&, int)>& error_callback) override {
estark06e0dac2015-08-07 21:56:01731 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44732 report.CopyToString(&latest_report_);
733 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01734 }
estark06e0dac2015-08-07 21:56:01735 const GURL& latest_report_uri() { return latest_report_uri_; }
736 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44737 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01738
739 private:
740 GURL latest_report_uri_;
741 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44742 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01743};
744
estarkcd39c11f2015-10-19 19:46:36745class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
746 public:
747 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36748};
749
dadrian612337a2016-07-20 22:36:58750// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
751// This is needed because after the certificate failure, the URLRequest will
752// retry the connection, and return a partial SSLInfo with a cached cert status.
753// The partial SSLInfo does not have the OCSP information filled out.
754class OCSPErrorTestDelegate : public TestDelegate {
755 public:
756 void OnSSLCertificateError(URLRequest* request,
757 const SSLInfo& ssl_info,
758 bool fatal) override {
759 ssl_info_ = ssl_info;
760 on_ssl_certificate_error_called_ = true;
761 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
762 }
763
764 bool on_ssl_certificate_error_called() {
765 return on_ssl_certificate_error_called_;
766 }
767
768 SSLInfo ssl_info() { return ssl_info_; }
769
770 private:
771 bool on_ssl_certificate_error_called_ = false;
772 SSLInfo ssl_info_;
773};
774
[email protected]d5a4dd62012-05-23 01:41:04775} // namespace
776
[email protected]a592c0432012-12-01 18:10:29777// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48778class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00779 public:
[email protected]ef2bf422012-05-11 03:27:09780 URLRequestTest() : default_context_(true) {
781 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25782 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50783 job_factory_impl_ = new URLRequestJobFactoryImpl();
784 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50785 }
bengr1bf8e942014-11-07 01:36:50786
dcheng67be2b1f2014-10-27 21:47:29787 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18788 // URLRequestJobs may post clean-up tasks on destruction.
789 base::RunLoop().RunUntilIdle();
790 }
[email protected]87a09a92011-07-14 15:50:50791
dcheng2339883c2014-12-23 00:23:05792 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50793 SetUpFactory();
794 default_context_.set_job_factory(job_factory_.get());
795 default_context_.Init();
796 PlatformTest::SetUp();
797 }
798
799 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20800 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36801 "data", base::WrapUnique(new DataProtocolHandler));
brettwa1228ebb2016-10-28 03:51:34802#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50803 job_factory_impl_->SetProtocolHandler(
ricea2deef682016-09-09 08:04:07804 "file", base::MakeUnique<FileProtocolHandler>(
805 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50806#endif
807 }
808
809 TestNetworkDelegate* default_network_delegate() {
810 return &default_network_delegate_;
811 }
812
813 const TestURLRequestContext& default_context() const {
814 return default_context_;
815 }
816
817
[email protected]3c5ca8c2011-09-29 01:14:51818 // Adds the TestJobInterceptor to the default context.
819 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23820 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20821 job_factory_impl_->SetProtocolHandler("http", nullptr);
822 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36823 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23824 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51825 }
826
[email protected]87a09a92011-07-14 15:50:50827 protected:
vishal.b62985ca92015-04-17 08:45:51828 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24829 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50830 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36831 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09832 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48833};
834
[email protected]316c1e5e2012-09-12 15:17:44835TEST_F(URLRequestTest, AboutBlankTest) {
836 TestDelegate d;
837 {
danakj8522a25b2016-04-16 00:17:36838 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36839 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44840
[email protected]f7022f32014-08-21 16:32:19841 r->Start();
842 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44843
[email protected]255620da2013-08-19 13:14:29844 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44845
[email protected]f7022f32014-08-21 16:32:19846 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44847 EXPECT_FALSE(d.received_data_before_response());
848 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19849 EXPECT_EQ("", r->GetSocketAddress().host());
850 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04851
852 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19853 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44854 }
855}
856
857TEST_F(URLRequestTest, DataURLImageTest) {
858 TestDelegate d;
859 {
860 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36861 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
862 GURL("data:image/png;base64,"
863 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
864 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
865 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
866 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
867 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
868 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
869 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
870 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
871 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
872 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
873 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
874 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
875 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
876 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
877 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
878 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
879 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
880 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
881 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36882 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44883
[email protected]f7022f32014-08-21 16:32:19884 r->Start();
885 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44886
[email protected]255620da2013-08-19 13:14:29887 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44888
[email protected]f7022f32014-08-21 16:32:19889 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44890 EXPECT_FALSE(d.received_data_before_response());
891 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19892 EXPECT_EQ("", r->GetSocketAddress().host());
893 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04894
895 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19896 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44897 }
898}
899
brettwa1228ebb2016-10-28 03:51:34900#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44901TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15902 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04903
904#if defined(OS_ANDROID)
905 // Android devices are not guaranteed to be able to read /proc/self/exe
906 // Use /etc/hosts instead
907 app_path = base::FilePath("/etc/hosts");
908#else
[email protected]316c1e5e2012-09-12 15:17:44909 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04910#endif // OS_ANDROID
911
[email protected]316c1e5e2012-09-12 15:17:44912 GURL app_url = FilePathToFileURL(app_path);
913
914 TestDelegate d;
915 {
danakj8522a25b2016-04-16 00:17:36916 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36917 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44918
[email protected]f7022f32014-08-21 16:32:19919 r->Start();
920 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44921
[email protected]255620da2013-08-19 13:14:29922 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44923
avibf0746c2015-12-09 19:53:14924 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49925 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44926
[email protected]f7022f32014-08-21 16:32:19927 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44928 EXPECT_EQ(1, d.response_started_count());
929 EXPECT_FALSE(d.received_data_before_response());
930 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19931 EXPECT_EQ("", r->GetSocketAddress().host());
932 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04933
934 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19935 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44936 }
937}
938
[email protected]ba40bb762012-12-17 07:11:04939TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15940 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04941 PathService::Get(base::FILE_EXE, &app_path);
942 GURL app_url = FilePathToFileURL(app_path);
943
944 TestDelegate d;
945 {
danakj8522a25b2016-04-16 00:17:36946 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36947 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04948
[email protected]f7022f32014-08-21 16:32:19949 r->Start();
950 EXPECT_TRUE(r->is_pending());
951 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04952 }
[email protected]79e1fd62013-06-20 06:50:04953 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04954 // destroyed.
[email protected]255620da2013-08-19 13:14:29955 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04956}
957
[email protected]316c1e5e2012-09-12 15:17:44958TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
959 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36960 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44961 FillBuffer(buffer.get(), buffer_size);
962
[email protected]6cdfd7f2013-02-08 20:40:15963 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52964 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44965 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30966 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44967
avibf0746c2015-12-09 19:53:14968 int64_t file_size;
[email protected]56285702013-12-04 18:22:49969 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44970
971 const size_t first_byte_position = 500;
972 const size_t last_byte_position = buffer_size - first_byte_position;
973 const size_t content_length = last_byte_position - first_byte_position + 1;
974 std::string partial_buffer_string(buffer.get() + first_byte_position,
975 buffer.get() + last_byte_position + 1);
976
977 TestDelegate d;
978 {
danakj8522a25b2016-04-16 00:17:36979 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36980 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44981
982 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38983 headers.SetHeader(
984 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59985 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38986 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19987 r->SetExtraRequestHeaders(headers);
988 r->Start();
989 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44990
[email protected]255620da2013-08-19 13:14:29991 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19992 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44993 EXPECT_EQ(1, d.response_started_count());
994 EXPECT_FALSE(d.received_data_before_response());
995 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
996 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
997 EXPECT_TRUE(partial_buffer_string == d.data_received());
998 }
999
[email protected]dd3aa792013-07-16 19:10:231000 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441001}
1002
1003TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
1004 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:361005 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441006 FillBuffer(buffer.get(), buffer_size);
1007
[email protected]6cdfd7f2013-02-08 20:40:151008 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521009 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441010 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301011 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441012
avibf0746c2015-12-09 19:53:141013 int64_t file_size;
[email protected]56285702013-12-04 18:22:491014 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441015
1016 const size_t first_byte_position = 500;
1017 const size_t last_byte_position = buffer_size - 1;
1018 const size_t content_length = last_byte_position - first_byte_position + 1;
1019 std::string partial_buffer_string(buffer.get() + first_byte_position,
1020 buffer.get() + last_byte_position + 1);
1021
1022 TestDelegate d;
1023 {
danakj8522a25b2016-04-16 00:17:361024 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361025 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441026
1027 HttpRequestHeaders headers;
1028 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591029 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381030 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191031 r->SetExtraRequestHeaders(headers);
1032 r->Start();
1033 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441034
[email protected]255620da2013-08-19 13:14:291035 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191036 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441037 EXPECT_EQ(1, d.response_started_count());
1038 EXPECT_FALSE(d.received_data_before_response());
1039 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1040 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1041 EXPECT_TRUE(partial_buffer_string == d.data_received());
1042 }
1043
[email protected]dd3aa792013-07-16 19:10:231044 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441045}
1046
1047TEST_F(URLRequestTest, FileTestMultipleRanges) {
1048 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361049 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441050 FillBuffer(buffer.get(), buffer_size);
1051
[email protected]6cdfd7f2013-02-08 20:40:151052 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521053 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441054 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301055 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441056
avibf0746c2015-12-09 19:53:141057 int64_t file_size;
[email protected]56285702013-12-04 18:22:491058 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441059
1060 TestDelegate d;
1061 {
danakj8522a25b2016-04-16 00:17:361062 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361063 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441064
1065 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381066 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191067 r->SetExtraRequestHeaders(headers);
1068 r->Start();
1069 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441070
[email protected]255620da2013-08-19 13:14:291071 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441072 EXPECT_TRUE(d.request_failed());
1073 }
1074
[email protected]dd3aa792013-07-16 19:10:231075 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441076}
1077
[email protected]3ca8b362013-11-11 22:18:071078TEST_F(URLRequestTest, AllowFileURLs) {
1079 base::ScopedTempDir temp_dir;
1080 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1081 base::FilePath test_file;
vabrb8582322016-09-09 08:05:371082 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.GetPath(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071083 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301084 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591085 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071086
1087 {
1088 TestDelegate d;
1089 TestNetworkDelegate network_delegate;
1090 network_delegate.set_can_access_files(true);
1091 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361092 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361093 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191094 r->Start();
[email protected]3ca8b362013-11-11 22:18:071095 base::RunLoop().Run();
1096 EXPECT_FALSE(d.request_failed());
1097 EXPECT_EQ(test_data, d.data_received());
1098 }
1099
1100 {
1101 TestDelegate d;
1102 TestNetworkDelegate network_delegate;
1103 network_delegate.set_can_access_files(false);
1104 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361105 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361106 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191107 r->Start();
[email protected]3ca8b362013-11-11 22:18:071108 base::RunLoop().Run();
1109 EXPECT_TRUE(d.request_failed());
1110 EXPECT_EQ("", d.data_received());
1111 }
1112}
1113
[email protected]316c1e5e2012-09-12 15:17:441114
1115TEST_F(URLRequestTest, FileDirCancelTest) {
1116 // Put in mock resource provider.
1117 NetModule::SetResourceProvider(TestNetResourceProvider);
1118
1119 TestDelegate d;
1120 {
[email protected]6cdfd7f2013-02-08 20:40:151121 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441122 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1123 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1124 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1125
danakj8522a25b2016-04-16 00:17:361126 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361127 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191128 req->Start();
1129 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441130
1131 d.set_cancel_in_received_data_pending(true);
1132
[email protected]255620da2013-08-19 13:14:291133 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441134 }
1135
1136 // Take out mock resource provider.
1137 NetModule::SetResourceProvider(NULL);
1138}
1139
[email protected]5f9581402013-10-30 13:08:321140TEST_F(URLRequestTest, FileDirOutputSanity) {
1141 // Verify the general sanity of the the output of the file:
1142 // directory lister by checking for the output of a known existing
1143 // file.
1144 const char sentinel_name[] = "filedir-sentinel";
1145
1146 base::FilePath path;
1147 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471148 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321149
1150 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361151 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361152 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191153 req->Start();
[email protected]5f9581402013-10-30 13:08:321154 base::RunLoop().Run();
1155
1156 // Generate entry for the sentinel file.
1157 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581158 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491159 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321160 EXPECT_GT(info.size, 0);
1161 std::string sentinel_output = GetDirectoryListingEntry(
1162 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1163 std::string(sentinel_name),
1164 false /* is_dir */,
1165 info.size,
1166 info.last_modified);
1167
1168 ASSERT_LT(0, d.bytes_received());
1169 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501170 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321171 // Check for the entry generated for the "sentinel" file.
1172 const std::string& data = d.data_received();
1173 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1174}
1175
[email protected]316c1e5e2012-09-12 15:17:441176TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1177 // There is an implicit redirect when loading a file path that matches a
1178 // directory and does not end with a slash. Ensure that following such
1179 // redirects does not crash. See http://crbug.com/18686.
1180
[email protected]6cdfd7f2013-02-08 20:40:151181 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441182 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471183 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441184
1185 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361186 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361187 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191188 req->Start();
[email protected]255620da2013-08-19 13:14:291189 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441190
1191 ASSERT_EQ(1, d.received_redirect_count());
1192 ASSERT_LT(0, d.bytes_received());
1193 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501194 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441195}
1196
1197#if defined(OS_WIN)
1198// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1199TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1200 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361201 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361202 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191203 req->Start();
[email protected]255620da2013-08-19 13:14:291204 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441205
1206 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501207 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441208}
[email protected]5ecf7cb282014-05-11 01:49:551209#endif // defined(OS_WIN)
1210
brettwa1228ebb2016-10-28 03:51:341211#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551212
1213TEST_F(URLRequestTest, InvalidUrlTest) {
1214 TestDelegate d;
1215 {
danakj8522a25b2016-04-16 00:17:361216 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361217 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551218
[email protected]f7022f32014-08-21 16:32:191219 r->Start();
1220 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551221
1222 base::RunLoop().Run();
1223 EXPECT_TRUE(d.request_failed());
1224 }
1225}
1226
jochen0e3b3a62014-09-16 18:31:231227TEST_F(URLRequestTest, InvalidReferrerTest) {
1228 TestURLRequestContext context;
1229 TestNetworkDelegate network_delegate;
1230 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1231 context.set_network_delegate(&network_delegate);
1232 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361233 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361234 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231235 req->SetReferrer("https://somewhere.com/");
1236
1237 req->Start();
1238 base::RunLoop().Run();
1239 EXPECT_TRUE(d.request_failed());
1240}
1241
[email protected]5ecf7cb282014-05-11 01:49:551242#if defined(OS_WIN)
1243TEST_F(URLRequestTest, ResolveShortcutTest) {
1244 base::FilePath app_path;
1245 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471246 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551247 app_path = app_path.AppendASCII("with-headers.html");
1248
1249 std::wstring lnk_path = app_path.value() + L".lnk";
1250
1251 base::win::ScopedCOMInitializer com_initializer;
1252
1253 // Temporarily create a shortcut for test
1254 {
1255 base::win::ScopedComPtr<IShellLink> shell;
1256 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1257 CLSCTX_INPROC_SERVER)));
1258 base::win::ScopedComPtr<IPersistFile> persist;
1259 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1260 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1261 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1262 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1263 }
1264
1265 TestDelegate d;
1266 {
danakj8522a25b2016-04-16 00:17:361267 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361268 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551269
[email protected]f7022f32014-08-21 16:32:191270 r->Start();
1271 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551272
1273 base::RunLoop().Run();
1274
1275 WIN32_FILE_ATTRIBUTE_DATA data;
1276 GetFileAttributesEx(app_path.value().c_str(),
1277 GetFileExInfoStandard, &data);
1278 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1279 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1280 FILE_ATTRIBUTE_NORMAL, NULL);
1281 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361282 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551283 DWORD read_size;
1284 BOOL result;
1285 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1286 &read_size, NULL);
1287 std::string content(buffer.get(), read_size);
1288 CloseHandle(file);
1289
[email protected]f7022f32014-08-21 16:32:191290 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551291 EXPECT_EQ(1, d.received_redirect_count());
1292 EXPECT_EQ(content, d.data_received());
1293 }
1294
1295 // Clean the shortcut
1296 DeleteFile(lnk_path.c_str());
1297}
1298#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441299
1300// Custom URLRequestJobs for use with interceptor tests
1301class RestartTestJob : public URLRequestTestJob {
1302 public:
1303 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1304 : URLRequestTestJob(request, network_delegate, true) {}
1305 protected:
dchengb03027d2014-10-21 12:00:201306 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441307 private:
dchengb03027d2014-10-21 12:00:201308 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441309};
1310
1311class CancelTestJob : public URLRequestTestJob {
1312 public:
1313 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1314 : URLRequestTestJob(request, network_delegate, true) {}
1315 protected:
dchengb03027d2014-10-21 12:00:201316 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441317 private:
dchengb03027d2014-10-21 12:00:201318 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441319};
1320
1321class CancelThenRestartTestJob : public URLRequestTestJob {
1322 public:
1323 explicit CancelThenRestartTestJob(URLRequest* request,
1324 NetworkDelegate* network_delegate)
1325 : URLRequestTestJob(request, network_delegate, true) {
1326 }
1327 protected:
dchengb03027d2014-10-21 12:00:201328 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441329 request_->Cancel();
1330 this->NotifyRestartRequired();
1331 }
1332 private:
dchengb03027d2014-10-21 12:00:201333 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441334};
1335
bengr1bf8e942014-11-07 01:36:501336// An Interceptor for use with interceptor tests.
1337class MockURLRequestInterceptor : public URLRequestInterceptor {
1338 public:
1339 // Static getters for canned response header and data strings.
1340 static std::string ok_data() {
1341 return URLRequestTestJob::test_data_1();
1342 }
1343
1344 static std::string ok_headers() {
1345 return URLRequestTestJob::test_headers();
1346 }
1347
1348 static std::string redirect_data() {
1349 return std::string();
1350 }
1351
1352 static std::string redirect_headers() {
1353 return URLRequestTestJob::test_redirect_headers();
1354 }
1355
1356 static std::string error_data() {
1357 return std::string("ohhh nooooo mr. bill!");
1358 }
1359
1360 static std::string error_headers() {
1361 return URLRequestTestJob::test_error_headers();
1362 }
1363
1364 MockURLRequestInterceptor()
1365 : intercept_main_request_(false), restart_main_request_(false),
1366 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1367 simulate_main_network_error_(false),
1368 intercept_redirect_(false), cancel_redirect_request_(false),
1369 intercept_final_response_(false), cancel_final_request_(false),
1370 use_url_request_http_job_(false),
1371 did_intercept_main_(false), did_restart_main_(false),
1372 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1373 did_simulate_error_main_(false),
1374 did_intercept_redirect_(false), did_cancel_redirect_(false),
1375 did_intercept_final_(false), did_cancel_final_(false) {
1376 }
1377
1378 ~MockURLRequestInterceptor() override {
1379 }
1380
1381 // URLRequestInterceptor implementation:
1382 URLRequestJob* MaybeInterceptRequest(
1383 URLRequest* request,
1384 NetworkDelegate* network_delegate) const override {
1385 if (restart_main_request_) {
1386 restart_main_request_ = false;
1387 did_restart_main_ = true;
1388 return new RestartTestJob(request, network_delegate);
1389 }
1390 if (cancel_main_request_) {
1391 cancel_main_request_ = false;
1392 did_cancel_main_ = true;
1393 return new CancelTestJob(request, network_delegate);
1394 }
1395 if (cancel_then_restart_main_request_) {
1396 cancel_then_restart_main_request_ = false;
1397 did_cancel_then_restart_main_ = true;
1398 return new CancelThenRestartTestJob(request, network_delegate);
1399 }
1400 if (simulate_main_network_error_) {
1401 simulate_main_network_error_ = false;
1402 did_simulate_error_main_ = true;
1403 if (use_url_request_http_job_) {
1404 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1405 }
1406 // This job will result in error since the requested URL is not one of the
1407 // URLs supported by these tests.
1408 return new URLRequestTestJob(request, network_delegate, true);
1409 }
1410 if (!intercept_main_request_)
1411 return nullptr;
1412 intercept_main_request_ = false;
1413 did_intercept_main_ = true;
1414 URLRequestTestJob* job = new URLRequestTestJob(request,
1415 network_delegate,
1416 main_headers_,
1417 main_data_,
1418 true);
1419 job->set_load_timing_info(main_request_load_timing_info_);
1420 return job;
1421 }
1422
1423 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1424 NetworkDelegate* network_delegate,
1425 const GURL& location) const override {
1426 if (cancel_redirect_request_) {
1427 cancel_redirect_request_ = false;
1428 did_cancel_redirect_ = true;
1429 return new CancelTestJob(request, network_delegate);
1430 }
1431 if (!intercept_redirect_)
1432 return nullptr;
1433 intercept_redirect_ = false;
1434 did_intercept_redirect_ = true;
1435 if (use_url_request_http_job_) {
1436 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1437 }
1438 return new URLRequestTestJob(request,
1439 network_delegate,
1440 redirect_headers_,
1441 redirect_data_,
1442 true);
1443 }
1444
1445 URLRequestJob* MaybeInterceptResponse(
1446 URLRequest* request,
1447 NetworkDelegate* network_delegate) const override {
1448 if (cancel_final_request_) {
1449 cancel_final_request_ = false;
1450 did_cancel_final_ = true;
1451 return new CancelTestJob(request, network_delegate);
1452 }
1453 if (!intercept_final_response_)
1454 return nullptr;
1455 intercept_final_response_ = false;
1456 did_intercept_final_ = true;
1457 if (use_url_request_http_job_) {
1458 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1459 }
1460 return new URLRequestTestJob(request,
1461 network_delegate,
1462 final_headers_,
1463 final_data_,
1464 true);
1465 }
1466
1467 void set_intercept_main_request(bool intercept_main_request) {
1468 intercept_main_request_ = intercept_main_request;
1469 }
1470
1471 void set_main_headers(const std::string& main_headers) {
1472 main_headers_ = main_headers;
1473 }
1474
1475 void set_main_data(const std::string& main_data) {
1476 main_data_ = main_data;
1477 }
1478
1479 void set_main_request_load_timing_info(
1480 const LoadTimingInfo& main_request_load_timing_info) {
1481 main_request_load_timing_info_ = main_request_load_timing_info;
1482 }
1483
1484 void set_restart_main_request(bool restart_main_request) {
1485 restart_main_request_ = restart_main_request;
1486 }
1487
1488 void set_cancel_main_request(bool cancel_main_request) {
1489 cancel_main_request_ = cancel_main_request;
1490 }
1491
1492 void set_cancel_then_restart_main_request(
1493 bool cancel_then_restart_main_request) {
1494 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1495 }
1496
1497 void set_simulate_main_network_error(bool simulate_main_network_error) {
1498 simulate_main_network_error_ = simulate_main_network_error;
1499 }
1500
1501 void set_intercept_redirect(bool intercept_redirect) {
1502 intercept_redirect_ = intercept_redirect;
1503 }
1504
1505 void set_redirect_headers(const std::string& redirect_headers) {
1506 redirect_headers_ = redirect_headers;
1507 }
1508
1509 void set_redirect_data(const std::string& redirect_data) {
1510 redirect_data_ = redirect_data;
1511 }
1512
1513 void set_cancel_redirect_request(bool cancel_redirect_request) {
1514 cancel_redirect_request_ = cancel_redirect_request;
1515 }
1516
1517 void set_intercept_final_response(bool intercept_final_response) {
1518 intercept_final_response_ = intercept_final_response;
1519 }
1520
1521 void set_final_headers(const std::string& final_headers) {
1522 final_headers_ = final_headers;
1523 }
1524
1525 void set_final_data(const std::string& final_data) {
1526 final_data_ = final_data;
1527 }
1528
1529 void set_cancel_final_request(bool cancel_final_request) {
1530 cancel_final_request_ = cancel_final_request;
1531 }
1532
1533 void set_use_url_request_http_job(bool use_url_request_http_job) {
1534 use_url_request_http_job_ = use_url_request_http_job;
1535 }
1536
1537 bool did_intercept_main() const {
1538 return did_intercept_main_;
1539 }
1540
1541 bool did_restart_main() const {
1542 return did_restart_main_;
1543 }
1544
1545 bool did_cancel_main() const {
1546 return did_cancel_main_;
1547 }
1548
1549 bool did_cancel_then_restart_main() const {
1550 return did_cancel_then_restart_main_;
1551 }
1552
1553 bool did_simulate_error_main() const {
1554 return did_simulate_error_main_;
1555 }
1556
1557 bool did_intercept_redirect() const {
1558 return did_intercept_redirect_;
1559 }
1560
1561 bool did_cancel_redirect() const {
1562 return did_cancel_redirect_;
1563 }
1564
1565 bool did_intercept_final() const {
1566 return did_intercept_final_;
1567 }
1568
1569 bool did_cancel_final() const {
1570 return did_cancel_final_;
1571 }
1572
1573 private:
1574 // Indicate whether to intercept the main request, and if so specify the
1575 // response to return and the LoadTimingInfo to use.
1576 mutable bool intercept_main_request_;
1577 mutable std::string main_headers_;
1578 mutable std::string main_data_;
1579 mutable LoadTimingInfo main_request_load_timing_info_;
1580
1581 // These indicate actions that can be taken within MaybeInterceptRequest.
1582 mutable bool restart_main_request_;
1583 mutable bool cancel_main_request_;
1584 mutable bool cancel_then_restart_main_request_;
1585 mutable bool simulate_main_network_error_;
1586
1587 // Indicate whether to intercept redirects, and if so specify the response to
1588 // return.
1589 mutable bool intercept_redirect_;
1590 mutable std::string redirect_headers_;
1591 mutable std::string redirect_data_;
1592
1593 // Cancel the request within MaybeInterceptRedirect.
1594 mutable bool cancel_redirect_request_;
1595
1596 // Indicate whether to intercept the final response, and if so specify the
1597 // response to return.
1598 mutable bool intercept_final_response_;
1599 mutable std::string final_headers_;
1600 mutable std::string final_data_;
1601
1602 // Cancel the final request within MaybeInterceptResponse.
1603 mutable bool cancel_final_request_;
1604
1605 // Instruct the interceptor to use a real URLRequestHTTPJob.
1606 mutable bool use_url_request_http_job_;
1607
1608 // These indicate if the interceptor did something or not.
1609 mutable bool did_intercept_main_;
1610 mutable bool did_restart_main_;
1611 mutable bool did_cancel_main_;
1612 mutable bool did_cancel_then_restart_main_;
1613 mutable bool did_simulate_error_main_;
1614 mutable bool did_intercept_redirect_;
1615 mutable bool did_cancel_redirect_;
1616 mutable bool did_intercept_final_;
1617 mutable bool did_cancel_final_;
1618};
1619
1620// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1621class URLRequestInterceptorTest : public URLRequestTest {
1622 public:
1623 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1624 }
1625
1626 ~URLRequestInterceptorTest() override {
1627 // URLRequestJobs may post clean-up tasks on destruction.
1628 base::RunLoop().RunUntilIdle();
1629 }
1630
1631 void SetUpFactory() override {
1632 interceptor_ = new MockURLRequestInterceptor();
1633 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361634 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501635 }
1636
1637 MockURLRequestInterceptor* interceptor() const {
1638 return interceptor_;
1639 }
1640
1641 private:
1642 MockURLRequestInterceptor* interceptor_;
1643};
1644
1645TEST_F(URLRequestInterceptorTest, Intercept) {
1646 // Intercept the main request and respond with a simple response.
1647 interceptor()->set_intercept_main_request(true);
1648 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1649 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591650 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361651 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361652 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501653 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1654 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1655 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1656 req->SetUserData(nullptr, user_data0);
1657 req->SetUserData(&user_data1, user_data1);
1658 req->SetUserData(&user_data2, user_data2);
1659 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191660 req->Start();
[email protected]255620da2013-08-19 13:14:291661 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591662
bengr1bf8e942014-11-07 01:36:501663 // Make sure we can retrieve our specific user data.
1664 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1665 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1666 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591667
bengr1bf8e942014-11-07 01:36:501668 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501669 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501670 EXPECT_EQ(200, req->response_headers()->response_code());
1671 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1672 EXPECT_EQ(1, d.response_started_count());
1673 EXPECT_EQ(0, d.received_redirect_count());
1674}
[email protected]2bba3252013-04-08 19:50:591675
bengr1bf8e942014-11-07 01:36:501676TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1677 // Intercept the main request and respond with a redirect.
1678 interceptor()->set_intercept_main_request(true);
1679 interceptor()->set_main_headers(
1680 MockURLRequestInterceptor::redirect_headers());
1681 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1682
1683 // Intercept that redirect and respond with a final OK response.
1684 interceptor()->set_intercept_redirect(true);
1685 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1686 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1687
1688 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361689 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361690 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501691 req->set_method("GET");
1692 req->Start();
1693 base::RunLoop().Run();
1694
1695 // Check that the interceptor got called as expected.
1696 EXPECT_TRUE(interceptor()->did_intercept_main());
1697 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1698
1699 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501700 int status = d.request_status();
1701 EXPECT_EQ(OK, status);
1702 if (status == OK)
bengr1bf8e942014-11-07 01:36:501703 EXPECT_EQ(200, req->response_headers()->response_code());
1704
1705 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1706 EXPECT_EQ(1, d.response_started_count());
1707 EXPECT_EQ(0, d.received_redirect_count());
1708}
1709
1710TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1711 // Intercept the main request to generate a server error response.
1712 interceptor()->set_intercept_main_request(true);
1713 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1714 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1715
1716 // Intercept that error and respond with an OK response.
1717 interceptor()->set_intercept_final_response(true);
1718 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1719 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1720
1721 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361722 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361723 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501724 req->set_method("GET");
1725 req->Start();
1726 base::RunLoop().Run();
1727
1728 // Check that the interceptor got called as expected.
1729 EXPECT_TRUE(interceptor()->did_intercept_main());
1730 EXPECT_TRUE(interceptor()->did_intercept_final());
1731
1732 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501733 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501734 EXPECT_EQ(200, req->response_headers()->response_code());
1735 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1736 EXPECT_EQ(1, d.response_started_count());
1737 EXPECT_EQ(0, d.received_redirect_count());
1738}
1739
1740TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1741 // Intercept the main request to simulate a network error.
1742 interceptor()->set_simulate_main_network_error(true);
1743
1744 // Intercept that error and respond with an OK response.
1745 interceptor()->set_intercept_final_response(true);
1746 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1747 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1748
1749 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361750 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361751 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501752 req->set_method("GET");
1753 req->Start();
1754 base::RunLoop().Run();
1755
1756 // Check that the interceptor got called as expected.
1757 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1758 EXPECT_TRUE(interceptor()->did_intercept_final());
1759
1760 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501761 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501762 EXPECT_EQ(200, req->response_headers()->response_code());
1763 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1764 EXPECT_EQ(1, d.response_started_count());
1765 EXPECT_EQ(0, d.received_redirect_count());
1766}
1767
1768TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1769 // Restart the main request.
1770 interceptor()->set_restart_main_request(true);
1771
1772 // then intercept the new main request and respond with an OK response
1773 interceptor()->set_intercept_main_request(true);
1774 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1775 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1776
1777 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361778 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361779 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501780 req->set_method("GET");
1781 req->Start();
1782 base::RunLoop().Run();
1783
1784 // Check that the interceptor got called as expected.
1785 EXPECT_TRUE(interceptor()->did_restart_main());
1786 EXPECT_TRUE(interceptor()->did_intercept_main());
1787
1788 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501789 int status = d.request_status();
1790 EXPECT_EQ(OK, status);
1791 if (status == OK)
bengr1bf8e942014-11-07 01:36:501792 EXPECT_EQ(200, req->response_headers()->response_code());
1793
1794 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1795 EXPECT_EQ(1, d.response_started_count());
1796 EXPECT_EQ(0, d.received_redirect_count());
1797}
1798
1799TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1800 // Intercept the main request and cancel from within the restarted job.
1801 interceptor()->set_cancel_main_request(true);
1802
1803 // Set up to intercept the final response and override it with an OK response.
1804 interceptor()->set_intercept_final_response(true);
1805 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1806 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1807
1808 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361809 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361810 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501811 req->set_method("GET");
1812 req->Start();
1813 base::RunLoop().Run();
1814
1815 // Check that the interceptor got called as expected.
1816 EXPECT_TRUE(interceptor()->did_cancel_main());
1817 EXPECT_FALSE(interceptor()->did_intercept_final());
1818
1819 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501820 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501821}
1822
1823TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1824 // Intercept the main request and respond with a redirect.
1825 interceptor()->set_intercept_main_request(true);
1826 interceptor()->set_main_headers(
1827 MockURLRequestInterceptor::redirect_headers());
1828 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1829
1830 // Intercept the redirect and cancel from within that job.
1831 interceptor()->set_cancel_redirect_request(true);
1832
1833 // Set up to intercept the final response and override it with an OK response.
1834 interceptor()->set_intercept_final_response(true);
1835 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1836 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1837
1838 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361839 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361840 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501841 req->set_method("GET");
1842 req->Start();
1843 base::RunLoop().Run();
1844
1845 // Check that the interceptor got called as expected.
1846 EXPECT_TRUE(interceptor()->did_intercept_main());
1847 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1848 EXPECT_FALSE(interceptor()->did_intercept_final());
1849
1850 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501851 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501852}
1853
1854TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1855 // Intercept the main request to simulate a network error.
1856 interceptor()->set_simulate_main_network_error(true);
1857
1858 // Set up to intercept final the response and cancel from within that job.
1859 interceptor()->set_cancel_final_request(true);
1860
1861 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361862 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361863 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501864 req->set_method("GET");
1865 req->Start();
1866 base::RunLoop().Run();
1867
1868 // Check that the interceptor got called as expected.
1869 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1870 EXPECT_TRUE(interceptor()->did_cancel_final());
1871
1872 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501873 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501874}
1875
1876TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1877 // Intercept the main request and cancel then restart from within that job.
1878 interceptor()->set_cancel_then_restart_main_request(true);
1879
1880 // Set up to intercept the final response and override it with an OK response.
1881 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501882 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1883 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501884
1885 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361886 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361887 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
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_cancel_then_restart_main());
1894 EXPECT_FALSE(interceptor()->did_intercept_final());
1895
1896 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501897 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:591898}
1899
1900// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1901// reused. |connect_time_flags| is used to indicate if there should be dns
1902// or SSL times, and |used_proxy| is used for proxy times.
1903LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1904 int connect_time_flags,
1905 bool used_proxy) {
1906 LoadTimingInfo load_timing;
1907 load_timing.socket_log_id = 1;
1908
1909 if (used_proxy) {
1910 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1911 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1912 }
1913
1914 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1915 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1916 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1917 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1918 }
1919 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1920 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1921 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1922 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1923 }
1924 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1925
1926 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1927 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1928 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1929 return load_timing;
1930}
1931
1932// Same as above, but in the case of a reused socket.
1933LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1934 bool used_proxy) {
1935 LoadTimingInfo load_timing;
1936 load_timing.socket_log_id = 1;
1937 load_timing.socket_reused = true;
1938
1939 if (used_proxy) {
1940 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1941 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1942 }
1943
1944 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1945 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1946 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1947 return load_timing;
1948}
1949
bengr1bf8e942014-11-07 01:36:501950LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1951 const LoadTimingInfo& job_load_timing,
1952 const URLRequestContext& context,
1953 MockURLRequestInterceptor* interceptor) {
1954 interceptor->set_intercept_main_request(true);
1955 interceptor->set_main_request_load_timing_info(job_load_timing);
1956 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361957 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361958 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501959 req->Start();
1960 base::RunLoop().Run();
1961
1962 LoadTimingInfo resulting_load_timing;
1963 req->GetLoadTimingInfo(&resulting_load_timing);
1964
1965 // None of these should be modified by the URLRequest.
1966 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1967 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1968 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1969 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1970 EXPECT_EQ(job_load_timing.receive_headers_end,
1971 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571972 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1973 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501974
1975 return resulting_load_timing;
1976}
1977
[email protected]2bba3252013-04-08 19:50:591978// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501979TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591980 base::TimeTicks now = base::TimeTicks::Now();
1981 LoadTimingInfo job_load_timing =
1982 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1983
[email protected]2ca01e52013-10-31 22:05:191984 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501985 RunURLRequestInterceptorLoadTimingTest(
1986 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591987
1988 // Nothing should have been changed by the URLRequest.
1989 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1990 load_timing_result.proxy_resolve_start);
1991 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1992 load_timing_result.proxy_resolve_end);
1993 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1994 load_timing_result.connect_timing.dns_start);
1995 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1996 load_timing_result.connect_timing.dns_end);
1997 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1998 load_timing_result.connect_timing.connect_start);
1999 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2000 load_timing_result.connect_timing.connect_end);
2001 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2002 load_timing_result.connect_timing.ssl_start);
2003 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2004 load_timing_result.connect_timing.ssl_end);
2005
2006 // Redundant sanity check.
2007 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2008}
2009
2010// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502011TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592012 base::TimeTicks now = base::TimeTicks::Now();
2013 LoadTimingInfo job_load_timing =
2014 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2015
[email protected]2ca01e52013-10-31 22:05:192016 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502017 RunURLRequestInterceptorLoadTimingTest(
2018 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592019
2020 // Nothing should have been changed by the URLRequest.
2021 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2022 load_timing_result.proxy_resolve_start);
2023 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2024 load_timing_result.proxy_resolve_end);
2025 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2026 load_timing_result.connect_timing.dns_start);
2027 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2028 load_timing_result.connect_timing.dns_end);
2029 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2030 load_timing_result.connect_timing.connect_start);
2031 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2032 load_timing_result.connect_timing.connect_end);
2033 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2034 load_timing_result.connect_timing.ssl_start);
2035 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2036 load_timing_result.connect_timing.ssl_end);
2037
2038 // Redundant sanity check.
2039 TestLoadTimingNotReusedWithProxy(load_timing_result,
2040 CONNECT_TIMING_HAS_SSL_TIMES);
2041}
2042
2043// Make sure that URLRequest correctly adjusts proxy times when they're before
2044// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102045// the case of reusing a SPDY session. The connected socket is not considered
2046// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592047//
2048// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502049TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592050 base::TimeTicks now = base::TimeTicks::Now();
2051 LoadTimingInfo job_load_timing =
2052 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2053 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2054 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2055 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2056 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2057 job_load_timing.connect_timing.connect_start =
2058 now - base::TimeDelta::FromDays(2);
2059 job_load_timing.connect_timing.connect_end =
2060 now - base::TimeDelta::FromDays(1);
2061
[email protected]2ca01e52013-10-31 22:05:192062 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502063 RunURLRequestInterceptorLoadTimingTest(
2064 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592065
2066 // Proxy times, connect times, and DNS times should all be replaced with
2067 // request_start.
2068 EXPECT_EQ(load_timing_result.request_start,
2069 load_timing_result.proxy_resolve_start);
2070 EXPECT_EQ(load_timing_result.request_start,
2071 load_timing_result.proxy_resolve_end);
2072 EXPECT_EQ(load_timing_result.request_start,
2073 load_timing_result.connect_timing.dns_start);
2074 EXPECT_EQ(load_timing_result.request_start,
2075 load_timing_result.connect_timing.dns_end);
2076 EXPECT_EQ(load_timing_result.request_start,
2077 load_timing_result.connect_timing.connect_start);
2078 EXPECT_EQ(load_timing_result.request_start,
2079 load_timing_result.connect_timing.connect_end);
2080
2081 // Other times should have been left null.
2082 TestLoadTimingNotReusedWithProxy(load_timing_result,
2083 CONNECT_TIMING_HAS_DNS_TIMES);
2084}
2085
2086// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502087TEST_F(URLRequestInterceptorTest,
2088 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592089 base::TimeTicks now = base::TimeTicks::Now();
2090 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2091 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2092 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2093
[email protected]2ca01e52013-10-31 22:05:192094 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502095 RunURLRequestInterceptorLoadTimingTest(
2096 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592097
2098 // Proxy times and connect times should all be replaced with request_start.
2099 EXPECT_EQ(load_timing_result.request_start,
2100 load_timing_result.proxy_resolve_start);
2101 EXPECT_EQ(load_timing_result.request_start,
2102 load_timing_result.proxy_resolve_end);
2103
2104 // Other times should have been left null.
2105 TestLoadTimingReusedWithProxy(load_timing_result);
2106}
2107
2108// Make sure that URLRequest correctly adjusts connect times when they're before
2109// |request_start|, due to reusing a connected socket. The connected socket is
2110// not considered reused in this test (May be a preconnect).
2111//
2112// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502113TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592114 base::TimeTicks now = base::TimeTicks::Now();
2115 LoadTimingInfo job_load_timing =
2116 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2117 job_load_timing.connect_timing.connect_start =
2118 now - base::TimeDelta::FromDays(1);
2119 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2120 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2121 job_load_timing.connect_timing.connect_end =
2122 now - base::TimeDelta::FromDays(4);
2123
[email protected]2ca01e52013-10-31 22:05:192124 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502125 RunURLRequestInterceptorLoadTimingTest(
2126 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592127
2128 // Connect times, and SSL times should be replaced with request_start.
2129 EXPECT_EQ(load_timing_result.request_start,
2130 load_timing_result.connect_timing.connect_start);
2131 EXPECT_EQ(load_timing_result.request_start,
2132 load_timing_result.connect_timing.ssl_start);
2133 EXPECT_EQ(load_timing_result.request_start,
2134 load_timing_result.connect_timing.ssl_end);
2135 EXPECT_EQ(load_timing_result.request_start,
2136 load_timing_result.connect_timing.connect_end);
2137
2138 // Other times should have been left null.
2139 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2140}
2141
2142// Make sure that URLRequest correctly adjusts connect times when they're before
2143// |request_start|, due to reusing a connected socket in the case that there
2144// are also proxy times. The connected socket is not considered reused in this
2145// test (May be a preconnect).
2146//
2147// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502148TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592149 base::TimeTicks now = base::TimeTicks::Now();
2150 LoadTimingInfo job_load_timing =
2151 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2152 job_load_timing.connect_timing.connect_start =
2153 now - base::TimeDelta::FromDays(1);
2154 job_load_timing.connect_timing.connect_end =
2155 now - base::TimeDelta::FromDays(2);
2156
[email protected]2ca01e52013-10-31 22:05:192157 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502158 RunURLRequestInterceptorLoadTimingTest(
2159 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592160
2161 // Connect times should be replaced with proxy_resolve_end.
2162 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2163 load_timing_result.connect_timing.connect_start);
2164 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2165 load_timing_result.connect_timing.connect_end);
2166
2167 // Other times should have been left null.
2168 TestLoadTimingNotReusedWithProxy(load_timing_result,
2169 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2170}
2171
[email protected]316c1e5e2012-09-12 15:17:442172// Check that two different URL requests have different identifiers.
2173TEST_F(URLRequestTest, Identifiers) {
2174 TestDelegate d;
2175 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362176 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362177 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362178 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362179 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442180
mmenke19378d22014-09-09 04:12:592181 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442182}
2183
blundellb8163592f2015-12-16 14:22:422184#if defined(OS_IOS)
2185// TODO(droger): Check that a failure to connect to the proxy is reported to
2186// the network delegate. crbug.com/496743
2187#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2188#else
2189#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2190#endif
2191TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442192 MockHostResolver host_resolver;
2193 host_resolver.rules()->AddSimulatedFailure("*");
2194
[email protected]ceefd7fd2012-11-29 00:36:242195 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442196 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2197
2198 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362199 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362200 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192201 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442202
[email protected]f7022f32014-08-21 16:32:192203 req->Start();
[email protected]255620da2013-08-19 13:14:292204 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442205
2206 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152207 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472208 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502209 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442210
2211 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012212 EXPECT_THAT(network_delegate.last_error(),
2213 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442214 EXPECT_EQ(1, network_delegate.completed_requests());
2215}
2216
[email protected]cba24642014-08-15 20:49:592217// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442218// content is empty.
2219TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2220 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362221 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362222 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192223 req->Start();
[email protected]255620da2013-08-19 13:14:292224 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442225 EXPECT_EQ("", d.data_received());
2226 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2227}
2228
[email protected]5033ab82013-03-22 20:17:462229// Make sure that SetPriority actually sets the URLRequest's priority
2230// correctly, both before and after start.
2231TEST_F(URLRequestTest, SetPriorityBasic) {
2232 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362233 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362234 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192235 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462236
[email protected]f7022f32014-08-21 16:32:192237 req->SetPriority(LOW);
2238 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462239
[email protected]f7022f32014-08-21 16:32:192240 req->Start();
2241 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462242
[email protected]f7022f32014-08-21 16:32:192243 req->SetPriority(MEDIUM);
2244 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462245}
2246
2247// Make sure that URLRequest calls SetPriority on a job before calling
2248// Start on it.
2249TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2250 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362251 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362252 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192253 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462254
mmenkeed0498b2015-12-08 23:20:422255 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362256 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422257 req.get(), &default_network_delegate_, &job_priority));
2258 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2259 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462260
[email protected]f7022f32014-08-21 16:32:192261 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462262
[email protected]f7022f32014-08-21 16:32:192263 req->Start();
mmenkeed0498b2015-12-08 23:20:422264 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462265}
2266
2267// Make sure that URLRequest passes on its priority updates to its
2268// job.
2269TEST_F(URLRequestTest, SetJobPriority) {
2270 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362271 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362272 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462273
mmenkeed0498b2015-12-08 23:20:422274 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362275 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422276 req.get(), &default_network_delegate_, &job_priority));
2277 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462278
[email protected]f7022f32014-08-21 16:32:192279 req->SetPriority(LOW);
2280 req->Start();
mmenkeed0498b2015-12-08 23:20:422281 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462282
[email protected]f7022f32014-08-21 16:32:192283 req->SetPriority(MEDIUM);
2284 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422285 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462286}
2287
[email protected]bb1c4662013-11-14 00:00:072288// Setting the IGNORE_LIMITS load flag should be okay if the priority
2289// is MAXIMUM_PRIORITY.
2290TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2291 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362292 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362293 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192294 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072295
mmenkeed0498b2015-12-08 23:20:422296 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362297 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422298 req.get(), &default_network_delegate_, &job_priority));
2299 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072300
[email protected]f7022f32014-08-21 16:32:192301 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2302 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072303
[email protected]f7022f32014-08-21 16:32:192304 req->SetPriority(MAXIMUM_PRIORITY);
2305 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072306
[email protected]f7022f32014-08-21 16:32:192307 req->Start();
2308 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422309 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072310}
2311
nick5d570de92015-05-04 20:16:162312namespace {
2313
2314// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552315class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442316 public:
tommycli59a63432015-11-06 00:10:552317 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2318 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272319 }
tommycli59a63432015-11-06 00:10:552320
2321 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2322};
tommyclieae5f75f2015-11-05 19:07:272323
nick5d570de92015-05-04 20:16:162324} // namespace
2325
[email protected]f2f31b32013-01-16 23:24:092326TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442327 LocalHttpTestServer test_server;
2328 ASSERT_TRUE(test_server.Start());
2329
2330 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362331 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502332 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442333
2334 // Set up a cookie.
2335 {
2336 TestNetworkDelegate network_delegate;
2337 context.set_network_delegate(&network_delegate);
2338 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362339 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552340 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362341 &d));
[email protected]f7022f32014-08-21 16:32:192342 req->Start();
[email protected]255620da2013-08-19 13:14:292343 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442344 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2345 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2346 EXPECT_EQ(1, network_delegate.set_cookie_count());
2347 }
2348
2349 // Verify that the cookie is set.
2350 {
2351 TestNetworkDelegate network_delegate;
2352 context.set_network_delegate(&network_delegate);
2353 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362354 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552355 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192356 req->Start();
[email protected]255620da2013-08-19 13:14:292357 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442358
2359 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2360 != std::string::npos);
2361 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2362 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2363 }
2364}
2365
[email protected]f2f31b32013-01-16 23:24:092366TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442367 LocalHttpTestServer test_server;
2368 ASSERT_TRUE(test_server.Start());
2369
2370 // Set up a cookie.
2371 {
2372 TestNetworkDelegate network_delegate;
2373 default_context_.set_network_delegate(&network_delegate);
2374 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362375 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552376 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362377 &d));
[email protected]f7022f32014-08-21 16:32:192378 req->Start();
[email protected]255620da2013-08-19 13:14:292379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442380 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2381 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2382 }
2383
2384 // Verify that the cookie is set.
2385 {
2386 TestNetworkDelegate network_delegate;
2387 default_context_.set_network_delegate(&network_delegate);
2388 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362389 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552390 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192391 req->Start();
[email protected]255620da2013-08-19 13:14:292392 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442393
2394 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2395 != std::string::npos);
2396 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2397 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2398 }
2399
2400 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2401 {
2402 TestNetworkDelegate network_delegate;
2403 default_context_.set_network_delegate(&network_delegate);
2404 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362405 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552406 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192407 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2408 req->Start();
[email protected]255620da2013-08-19 13:14:292409 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442410
2411 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2412 == std::string::npos);
2413
2414 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2415 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2416 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2417 }
2418}
2419
2420TEST_F(URLRequestTest, DoNotSaveCookies) {
2421 LocalHttpTestServer test_server;
2422 ASSERT_TRUE(test_server.Start());
2423
2424 // Set up a cookie.
2425 {
2426 TestNetworkDelegate network_delegate;
2427 default_context_.set_network_delegate(&network_delegate);
2428 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362429 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552430 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362431 &d));
[email protected]f7022f32014-08-21 16:32:192432 req->Start();
[email protected]255620da2013-08-19 13:14:292433 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442434
2435 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2436 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2437 EXPECT_EQ(1, network_delegate.set_cookie_count());
2438 }
2439
2440 // Try to set-up another cookie and update the previous cookie.
2441 {
2442 TestNetworkDelegate network_delegate;
2443 default_context_.set_network_delegate(&network_delegate);
2444 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362445 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552446 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362447 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192448 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2449 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442450
[email protected]255620da2013-08-19 13:14:292451 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442452
2453 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2454 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2455 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2456 EXPECT_EQ(0, network_delegate.set_cookie_count());
2457 }
2458
2459 // Verify the cookies weren't saved or updated.
2460 {
2461 TestNetworkDelegate network_delegate;
2462 default_context_.set_network_delegate(&network_delegate);
2463 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362464 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552465 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192466 req->Start();
[email protected]255620da2013-08-19 13:14:292467 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442468
2469 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2470 == std::string::npos);
2471 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2472 != std::string::npos);
2473
2474 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2475 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2476 EXPECT_EQ(0, network_delegate.set_cookie_count());
2477 }
2478}
2479
2480TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2481 LocalHttpTestServer test_server;
2482 ASSERT_TRUE(test_server.Start());
2483
2484 // Set up a cookie.
2485 {
2486 TestNetworkDelegate network_delegate;
2487 default_context_.set_network_delegate(&network_delegate);
2488 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362489 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552490 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362491 &d));
[email protected]f7022f32014-08-21 16:32:192492 req->Start();
[email protected]255620da2013-08-19 13:14:292493 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442494
2495 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2496 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2497 }
2498
2499 // Verify that the cookie is set.
2500 {
2501 TestNetworkDelegate network_delegate;
2502 default_context_.set_network_delegate(&network_delegate);
2503 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362504 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552505 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192506 req->Start();
[email protected]255620da2013-08-19 13:14:292507 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442508
2509 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2510 != std::string::npos);
2511
2512 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2513 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2514 }
2515
2516 // Verify that the cookie isn't sent.
2517 {
2518 TestNetworkDelegate network_delegate;
2519 default_context_.set_network_delegate(&network_delegate);
2520 TestDelegate d;
2521 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362522 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552523 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192524 req->Start();
[email protected]255620da2013-08-19 13:14:292525 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442526
2527 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2528 == std::string::npos);
2529
[email protected]22e045f2013-09-20 03:54:032530 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442531 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2532 }
2533}
2534
marqf14fff8d2015-12-02 15:52:292535// TODO(crbug.com/564656) This test is flaky on iOS.
2536#if defined(OS_IOS)
2537#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2538#else
2539#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2540#endif
[email protected]316c1e5e2012-09-12 15:17:442541TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2542 LocalHttpTestServer test_server;
2543 ASSERT_TRUE(test_server.Start());
2544
2545 // Set up a cookie.
2546 {
2547 TestNetworkDelegate network_delegate;
2548 default_context_.set_network_delegate(&network_delegate);
2549 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362550 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552551 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362552 &d));
[email protected]f7022f32014-08-21 16:32:192553 req->Start();
[email protected]255620da2013-08-19 13:14:292554 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442555
2556 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2557 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2558 }
2559
2560 // Try to set-up another cookie and update the previous cookie.
2561 {
2562 TestNetworkDelegate network_delegate;
2563 default_context_.set_network_delegate(&network_delegate);
2564 TestDelegate d;
2565 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362566 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552567 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362568 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192569 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442570
[email protected]255620da2013-08-19 13:14:292571 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442572
2573 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2574 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2575 }
2576
2577 // Verify the cookies weren't saved or updated.
2578 {
2579 TestNetworkDelegate network_delegate;
2580 default_context_.set_network_delegate(&network_delegate);
2581 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362582 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552583 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192584 req->Start();
[email protected]255620da2013-08-19 13:14:292585 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442586
2587 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2588 == std::string::npos);
2589 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2590 != std::string::npos);
2591
2592 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2593 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2594 }
2595}
2596
2597TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2598 LocalHttpTestServer test_server;
2599 ASSERT_TRUE(test_server.Start());
2600
2601 // Set up an empty cookie.
2602 {
2603 TestNetworkDelegate network_delegate;
2604 default_context_.set_network_delegate(&network_delegate);
2605 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362606 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552607 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192608 req->Start();
[email protected]255620da2013-08-19 13:14:292609 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442610
2611 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2612 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2613 EXPECT_EQ(0, network_delegate.set_cookie_count());
2614 }
2615}
2616
2617TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2618 LocalHttpTestServer test_server;
2619 ASSERT_TRUE(test_server.Start());
2620
2621 // Set up a 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?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362628 &d));
[email protected]f7022f32014-08-21 16:32:192629 req->Start();
[email protected]255620da2013-08-19 13:14:292630 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442631
2632 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2633 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2634 }
2635
2636 // Verify that the cookie is set.
2637 {
2638 TestNetworkDelegate network_delegate;
2639 default_context_.set_network_delegate(&network_delegate);
2640 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362641 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552642 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192643 req->Start();
[email protected]255620da2013-08-19 13:14:292644 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442645
2646 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2647 != std::string::npos);
2648
2649 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2650 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2651 }
2652
2653 // Verify that the cookie isn't sent.
2654 {
2655 TestNetworkDelegate network_delegate;
2656 default_context_.set_network_delegate(&network_delegate);
2657 TestDelegate d;
2658 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362659 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552660 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192661 req->Start();
[email protected]255620da2013-08-19 13:14:292662 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442663
2664 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2665 == std::string::npos);
2666
[email protected]22e045f2013-09-20 03:54:032667 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442668 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2669 }
2670}
2671
2672TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2673 LocalHttpTestServer test_server;
2674 ASSERT_TRUE(test_server.Start());
2675
2676 // Set up a cookie.
2677 {
2678 TestNetworkDelegate network_delegate;
2679 default_context_.set_network_delegate(&network_delegate);
2680 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362681 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552682 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362683 &d));
[email protected]f7022f32014-08-21 16:32:192684 req->Start();
[email protected]255620da2013-08-19 13:14:292685 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442686
2687 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2688 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2689 }
2690
2691 // Try to set-up another cookie and update the previous cookie.
2692 {
2693 TestNetworkDelegate network_delegate;
2694 default_context_.set_network_delegate(&network_delegate);
2695 TestDelegate d;
2696 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362697 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552698 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362699 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192700 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442701
[email protected]255620da2013-08-19 13:14:292702 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442703
2704 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2705 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2706 }
2707
2708 // Verify the cookies weren't saved or updated.
2709 {
2710 TestNetworkDelegate network_delegate;
2711 default_context_.set_network_delegate(&network_delegate);
2712 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362713 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552714 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192715 req->Start();
[email protected]255620da2013-08-19 13:14:292716 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442717
2718 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2719 == std::string::npos);
2720 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2721 != std::string::npos);
2722
2723 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2724 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2725 }
2726}
2727
mkwstc5fa7762016-03-28 09:28:232728TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262729 LocalHttpTestServer test_server;
2730 ASSERT_TRUE(test_server.Start());
2731
mkwst202534e32016-01-15 16:07:152732 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152733 default_context_.set_network_delegate(&network_delegate);
2734
mkwstf71d0bd2016-03-21 14:15:242735 const std::string kHost = "example.test";
2736 const std::string kSubHost = "subdomain.example.test";
2737 const std::string kCrossHost = "cross-origin.test";
2738
2739 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262740 {
mkwst3f3daac2015-02-26 20:15:262741 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362742 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242743 test_server.GetURL(kHost,
2744 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2745 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362746 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262747 req->Start();
2748 base::RunLoop().Run();
2749 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2750 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242751 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262752 }
2753
mkwstf71d0bd2016-03-21 14:15:242754 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262755 {
mkwst3f3daac2015-02-26 20:15:262756 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362757 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242758 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2759 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2760 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262761 req->Start();
2762 base::RunLoop().Run();
2763
mkwstf71d0bd2016-03-21 14:15:242764 EXPECT_NE(std::string::npos,
2765 d.data_received().find("StrictSameSiteCookie=1"));
2766 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262767 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2768 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2769 }
2770
clamyfd58ca072016-12-21 17:18:322771 // Verify that both cookies are sent when the request has no initiator (can
2772 // happen for main frame browser-initiated navigations).
2773 {
2774 TestDelegate d;
2775 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2776 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2777 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2778 req->Start();
2779 base::RunLoop().Run();
2780
2781 EXPECT_NE(std::string::npos,
2782 d.data_received().find("StrictSameSiteCookie=1"));
2783 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2784 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2785 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2786 }
2787
mkwstf71d0bd2016-03-21 14:15:242788 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262789 {
mkwst3f3daac2015-02-26 20:15:262790 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362791 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242792 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2793 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2794 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152795 req->Start();
2796 base::RunLoop().Run();
2797
mkwstf71d0bd2016-03-21 14:15:242798 EXPECT_NE(std::string::npos,
2799 d.data_received().find("StrictSameSiteCookie=1"));
2800 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152801 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2802 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2803 }
2804
mkwstf71d0bd2016-03-21 14:15:242805 // Verify that neither cookie is not sent for cross-site requests.
2806 {
2807 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362808 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242809 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2810 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2811 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2812 req->Start();
2813 base::RunLoop().Run();
2814
2815 EXPECT_EQ(std::string::npos,
2816 d.data_received().find("StrictSameSiteCookie=1"));
2817 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
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 lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152823 // method is "safe".
2824 {
2825 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362826 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242827 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2828 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2829 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2830 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152831 req->Start();
2832 base::RunLoop().Run();
2833
mkwstf71d0bd2016-03-21 14:15:242834 EXPECT_EQ(std::string::npos,
2835 d.data_received().find("StrictSameSiteCookie=1"));
2836 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152837 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2838 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2839 }
2840
mkwstf71d0bd2016-03-21 14:15:242841 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152842 // method is unsafe (e.g. POST).
2843 {
2844 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362845 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242846 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2847 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2848 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152849 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262850 req->Start();
2851 base::RunLoop().Run();
2852
mkwstf71d0bd2016-03-21 14:15:242853 EXPECT_EQ(std::string::npos,
2854 d.data_received().find("StrictSameSiteCookie=1"));
2855 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262856 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2857 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2858 }
2859}
2860
estark557a5eb82015-12-01 22:57:102861// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362862TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552863 EmbeddedTestServer http_server;
2864 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362865 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552866 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2867 https_server.AddDefaultHandlers(
2868 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2869 ASSERT_TRUE(http_server.Start());
2870 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362871
estarkb15166b2015-12-18 16:56:382872 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362873 TestURLRequestContext context(true);
2874 context.set_network_delegate(&network_delegate);
2875 context.Init();
2876
estarkb15166b2015-12-18 16:56:382877 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362878 {
2879 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362880 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102881 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362882 DEFAULT_PRIORITY, &d));
2883 req->Start();
2884 base::RunLoop().Run();
2885 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2886 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2887 }
2888
2889 // Verify that the cookie is not set.
2890 {
2891 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362892 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552893 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362894 req->Start();
2895 base::RunLoop().Run();
2896
jww79aceda2015-12-07 01:56:342897 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2898 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362899 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2900 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2901 }
2902}
2903
estarkb15166b2015-12-18 16:56:382904TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552905 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2906 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362907 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552908 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362909
2910 TestNetworkDelegate network_delegate;
2911 TestURLRequestContext context(true);
2912 context.set_network_delegate(&network_delegate);
2913 context.Init();
2914
estarkb15166b2015-12-18 16:56:382915 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362916 {
2917 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362918 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102919 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552920 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362921 req->Start();
2922 base::RunLoop().Run();
2923 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2924 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2925 }
2926
2927 // Verify that the cookie is not set.
2928 {
2929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362930 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552931 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362932 req->Start();
2933 base::RunLoop().Run();
2934
jww79aceda2015-12-07 01:56:342935 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362936 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2937 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2938 }
2939}
2940
estarkb15166b2015-12-18 16:56:382941TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552942 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2943 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362944 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552945 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362946
estarkb15166b2015-12-18 16:56:382947 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362948 TestURLRequestContext context(true);
2949 context.set_network_delegate(&network_delegate);
2950 context.Init();
2951
estarkb15166b2015-12-18 16:56:382952 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362953 {
2954 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362955 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102956 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552957 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362958 req->Start();
2959 base::RunLoop().Run();
2960 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2961 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2962 }
2963
2964 // Verify that the cookie is set.
2965 {
2966 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362967 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552968 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362969 req->Start();
2970 base::RunLoop().Run();
2971
jww79aceda2015-12-07 01:56:342972 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2973 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2974 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2975 }
2976}
2977
2978// Tests that secure cookies can't be set on non-secure origins if strict secure
2979// cookies are enabled.
2980TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2981 EmbeddedTestServer http_server;
2982 http_server.AddDefaultHandlers(
2983 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2984 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2985 https_server.AddDefaultHandlers(
2986 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2987 ASSERT_TRUE(http_server.Start());
2988 ASSERT_TRUE(https_server.Start());
2989
2990 TestExperimentalFeaturesNetworkDelegate network_delegate;
2991 TestURLRequestContext context(true);
2992 context.set_network_delegate(&network_delegate);
2993 context.Init();
2994
2995 // Try to set a Secure cookie, with experimental features enabled.
2996 {
2997 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362998 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342999 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
3000 DEFAULT_PRIORITY, &d));
3001 req->Start();
3002 base::RunLoop().Run();
3003 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3004 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3005 }
3006
3007 // Verify that the cookie is not set.
3008 {
3009 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363010 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343011 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
3012 req->Start();
3013 base::RunLoop().Run();
3014
3015 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3016 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3017 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3018 }
3019}
3020
3021// Tests that secure cookies can be set on secure origins even if strict secure
3022// cookies are enabled.
3023TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3024 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3025 https_server.AddDefaultHandlers(
3026 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3027 ASSERT_TRUE(https_server.Start());
3028
3029 TestExperimentalFeaturesNetworkDelegate network_delegate;
3030 TestURLRequestContext context(true);
3031 context.set_network_delegate(&network_delegate);
3032 context.Init();
3033
3034 // Try to set a Secure cookie, with experimental features enabled.
3035 {
3036 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363037 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343038 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
3039 DEFAULT_PRIORITY, &d));
3040 req->Start();
3041 base::RunLoop().Run();
3042 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3043 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3044 }
3045
3046 // Verify that the cookie is not set.
3047 {
3048 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363049 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343050 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
3051 req->Start();
3052 base::RunLoop().Run();
3053
3054 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363055 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3056 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3057 }
3058}
3059
mmenkefb18c772015-09-30 22:22:503060// Tests that a request is cancelled while entering suspend mode. Uses mocks
3061// rather than a spawned test server because the connection used to talk to
3062// the test server is affected by entering suspend mode on Android.
3063TEST_F(URLRequestTest, CancelOnSuspend) {
3064 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363065 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503066
3067 URLRequestFailedJob::AddUrlHandler();
3068
3069 TestDelegate d;
3070 // Request that just hangs.
3071 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:363072 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:503073 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3074 r->Start();
3075
3076 power_monitor_source->Suspend();
3077 // Wait for the suspend notification to cause the request to fail.
3078 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503079 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503080 EXPECT_TRUE(d.request_failed());
3081 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3082
3083 URLRequestFilter::GetInstance()->ClearHandlers();
3084
3085 // Shouldn't be needed, but just in case.
3086 power_monitor_source->Resume();
3087}
3088
[email protected]5095cd72012-11-01 10:29:163089// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3090// value for the |fixed_date| argument given to the constructor.
3091class FixedDateNetworkDelegate : public TestNetworkDelegate {
3092 public:
3093 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3094 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203095 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163096
[email protected]cba24642014-08-15 20:49:593097 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203098 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593099 URLRequest* request,
3100 const CompletionCallback& callback,
3101 const HttpResponseHeaders* original_response_headers,
3102 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133103 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163104
3105 private:
3106 std::string fixed_date_;
3107
3108 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3109};
3110
3111int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593112 URLRequest* request,
3113 const CompletionCallback& callback,
3114 const HttpResponseHeaders* original_response_headers,
3115 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163116 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593117 HttpResponseHeaders* new_response_headers =
3118 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163119
3120 new_response_headers->RemoveHeader("Date");
3121 new_response_headers->AddHeader("Date: " + fixed_date_);
3122
3123 *override_response_headers = new_response_headers;
3124 return TestNetworkDelegate::OnHeadersReceived(request,
3125 callback,
3126 original_response_headers,
[email protected]5f714132014-03-26 10:41:163127 override_response_headers,
3128 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163129}
3130
3131// Test that cookie expiration times are adjusted for server/client clock
3132// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3133// headers by defaulting to GMT. (crbug.com/135131)
3134TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3135 LocalHttpTestServer test_server;
3136 ASSERT_TRUE(test_server.Start());
3137
3138 // Set up an expired cookie.
3139 {
3140 TestNetworkDelegate network_delegate;
3141 default_context_.set_network_delegate(&network_delegate);
3142 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363143 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193144 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553145 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363146 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193147 req->Start();
[email protected]255620da2013-08-19 13:14:293148 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163149 }
3150 // Verify that the cookie is not set.
3151 {
3152 TestNetworkDelegate network_delegate;
3153 default_context_.set_network_delegate(&network_delegate);
3154 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363155 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553156 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193157 req->Start();
[email protected]255620da2013-08-19 13:14:293158 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163159
3160 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3161 }
3162 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3163 {
3164 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3165 default_context_.set_network_delegate(&network_delegate);
3166 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363167 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193168 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553169 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363170 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193171 req->Start();
[email protected]255620da2013-08-19 13:14:293172 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163173 }
3174 // Verify that the cookie is set.
3175 {
3176 TestNetworkDelegate network_delegate;
3177 default_context_.set_network_delegate(&network_delegate);
3178 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363179 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553180 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193181 req->Start();
[email protected]255620da2013-08-19 13:14:293182 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163183
3184 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3185 }
3186}
3187
3188
[email protected]316c1e5e2012-09-12 15:17:443189// Check that it is impossible to change the referrer in the extra headers of
3190// an URLRequest.
3191TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3192 LocalHttpTestServer test_server;
3193 ASSERT_TRUE(test_server.Start());
3194
3195 // If extra headers contain referer and the request contains a referer,
3196 // only the latter shall be respected.
3197 {
3198 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363199 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553200 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193201 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443202
3203 HttpRequestHeaders headers;
3204 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193205 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443206
[email protected]f7022f32014-08-21 16:32:193207 req->Start();
[email protected]255620da2013-08-19 13:14:293208 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443209
3210 EXPECT_EQ("http://foo.com/", d.data_received());
3211 }
3212
3213 // If extra headers contain a referer but the request does not, no referer
3214 // shall be sent in the header.
3215 {
3216 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363217 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553218 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443219
3220 HttpRequestHeaders headers;
3221 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193222 req->SetExtraRequestHeaders(headers);
3223 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443224
[email protected]f7022f32014-08-21 16:32:193225 req->Start();
[email protected]255620da2013-08-19 13:14:293226 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443227
3228 EXPECT_EQ("None", d.data_received());
3229 }
3230}
3231
[email protected]b89290212009-08-14 22:37:353232class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113233 public:
mmenke9f2ec60c2015-06-01 20:59:473234 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113235
[email protected]b89290212009-08-14 22:37:353236 protected:
[email protected]21184962011-10-26 00:50:303237 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3238 // |request_method| is the method to use for the initial request.
3239 // |redirect_method| is the method that is expected to be used for the second
3240 // request, after redirection.
3241 // If |include_data| is true, data is uploaded with the request. The
3242 // response body is expected to match it exactly, if and only if
3243 // |request_method| == |redirect_method|.
3244 void HTTPRedirectMethodTest(const GURL& redirect_url,
3245 const std::string& request_method,
3246 const std::string& redirect_method,
3247 bool include_data) {
3248 static const char kData[] = "hello world";
3249 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363250 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363251 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193252 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303253 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073254 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303255 HttpRequestHeaders headers;
3256 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513257 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543258 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193259 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303260 }
[email protected]f7022f32014-08-21 16:32:193261 req->Start();
[email protected]255620da2013-08-19 13:14:293262 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193263 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503264 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303265 if (include_data) {
3266 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543267 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3268 HttpRequestHeaders::kContentLength));
3269 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3270 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303271 EXPECT_EQ(kData, d.data_received());
3272 } else {
svaldez5b3a8972015-10-09 23:23:543273 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3274 HttpRequestHeaders::kContentLength));
3275 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3276 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303277 EXPECT_NE(kData, d.data_received());
3278 }
3279 }
3280 if (HasFailure())
3281 LOG(WARNING) << "Request method was: " << request_method;
3282 }
3283
jww5fe460ff2015-03-28 00:22:513284 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3285 // |request_method| is the method to use for the initial request.
3286 // |redirect_method| is the method that is expected to be used for the second
3287 // request, after redirection.
3288 // |origin_value| is the expected value for the Origin header after
3289 // redirection. If empty, expects that there will be no Origin header.
3290 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3291 const std::string& request_method,
3292 const std::string& redirect_method,
3293 const std::string& origin_value) {
3294 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363295 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513296 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3297 req->set_method(request_method);
3298 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3299 redirect_url.GetOrigin().spec(), false);
3300 req->Start();
3301
3302 base::RunLoop().Run();
3303
3304 EXPECT_EQ(redirect_method, req->method());
3305 // Note that there is no check for request success here because, for
3306 // purposes of testing, the request very well may fail. For example, if the
3307 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3308 // origin, there is not an HTTPS server in this unit test framework, so the
3309 // request would fail. However, that's fine, as long as the request headers
3310 // are in order and pass the checks below.
3311 if (origin_value.empty()) {
3312 EXPECT_FALSE(
3313 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3314 } else {
3315 std::string origin_header;
3316 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3317 HttpRequestHeaders::kOrigin, &origin_header));
3318 EXPECT_EQ(origin_value, origin_header);
3319 }
3320 }
3321
[email protected]762d2db2010-01-11 19:03:013322 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013323 const int kMsgSize = 20000; // multiple of 10
3324 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483325 char* uploadBytes = new char[kMsgSize+1];
3326 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013327 char marker = 'a';
3328 for (int idx = 0; idx < kMsgSize/10; idx++) {
3329 memcpy(ptr, "----------", 10);
3330 ptr += 10;
3331 if (idx % 100 == 0) {
3332 ptr--;
3333 *ptr++ = marker;
3334 if (++marker > 'z')
3335 marker = 'a';
3336 }
3337 }
3338 uploadBytes[kMsgSize] = '\0';
3339
[email protected]762d2db2010-01-11 19:03:013340 for (int i = 0; i < kIterations; ++i) {
3341 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363342 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553343 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193344 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013345
mmenkecbc2b712014-10-09 20:29:073346 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013347
[email protected]f7022f32014-08-21 16:32:193348 r->Start();
3349 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013350
[email protected]255620da2013-08-19 13:14:293351 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013352
maksim.sisovb53724b52016-09-16 05:30:503353 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3354 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013355
3356 EXPECT_FALSE(d.received_data_before_response());
3357 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013358 }
3359 delete[] uploadBytes;
3360 }
3361
[email protected]ede03212012-09-07 12:52:263362 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343363 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363364 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553365 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363366 base::IntToString(num_cookies)),
3367 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343368
[email protected]f7022f32014-08-21 16:32:193369 r->Start();
3370 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343371
[email protected]255620da2013-08-19 13:14:293372 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343373
maksim.sisovb53724b52016-09-16 05:30:503374 if (d.request_status() != OK) {
3375 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3376 return false;
3377 }
[email protected]263163f2012-06-14 22:40:343378
maksim.sisovb53724b52016-09-16 05:30:503379 return true;
[email protected]263163f2012-06-14 22:40:343380 }
3381
tommycli59a63432015-11-06 00:10:553382 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503383
tommycli59a63432015-11-06 00:10:553384 private:
[email protected]1700c6a2012-02-22 18:07:073385 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353386};
3387
tommycli59a63432015-11-06 00:10:553388namespace {
3389
danakj8522a25b2016-04-16 00:17:363390std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553391 const test_server::HttpRequest& request) {
3392 if (request.headers.find("Host") == request.headers.end() ||
3393 request.headers.at("Host") != "www.redirect.com" ||
3394 request.method != test_server::METHOD_CONNECT) {
3395 return nullptr;
3396 }
3397
danakj8522a25b2016-04-16 00:17:363398 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553399 new test_server::BasicHttpResponse);
3400 http_response->set_code(HTTP_FOUND);
3401 http_response->AddCustomHeader("Location",
3402 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483403 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553404}
3405
3406} // namespace
3407
nharperb7441ef2016-01-25 23:54:143408class TestSSLConfigService : public SSLConfigService {
3409 public:
3410 TestSSLConfigService(bool ev_enabled,
3411 bool online_rev_checking,
3412 bool rev_checking_required_local_anchors,
3413 bool token_binding_enabled)
3414 : ev_enabled_(ev_enabled),
3415 online_rev_checking_(online_rev_checking),
3416 rev_checking_required_local_anchors_(
3417 rev_checking_required_local_anchors),
3418 token_binding_enabled_(token_binding_enabled),
davidben5a312152016-06-27 22:11:473419 min_version_(kDefaultSSLVersionMin) {}
nharperb7441ef2016-01-25 23:54:143420
3421 void set_min_version(uint16_t version) { min_version_ = version; }
3422
nharperb7441ef2016-01-25 23:54:143423 // SSLConfigService:
3424 void GetSSLConfig(SSLConfig* config) override {
3425 *config = SSLConfig();
3426 config->rev_checking_enabled = online_rev_checking_;
3427 config->verify_ev_cert = ev_enabled_;
3428 config->rev_checking_required_local_anchors =
3429 rev_checking_required_local_anchors_;
nharperb7441ef2016-01-25 23:54:143430 if (min_version_) {
3431 config->version_min = min_version_;
3432 }
3433 if (token_binding_enabled_) {
3434 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3435 }
3436 }
3437
3438 protected:
3439 ~TestSSLConfigService() override {}
3440
3441 private:
3442 const bool ev_enabled_;
3443 const bool online_rev_checking_;
3444 const bool rev_checking_required_local_anchors_;
3445 const bool token_binding_enabled_;
3446 uint16_t min_version_;
nharperb7441ef2016-01-25 23:54:143447};
3448
3449// TODO(svaldez): Update tests to use EmbeddedTestServer.
3450#if !defined(OS_IOS)
3451class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3452 public:
fdoraya89e673c2017-01-31 21:44:213453 TokenBindingURLRequestTest()
3454 : scoped_task_scheduler_(base::MessageLoop::current()) {}
3455
nharperb7441ef2016-01-25 23:54:143456 void SetUp() override {
3457 default_context_.set_ssl_config_service(
3458 new TestSSLConfigService(false, false, false, true));
fdoraya89e673c2017-01-31 21:44:213459 channel_id_service_.reset(
3460 new ChannelIDService(new DefaultChannelIDStore(NULL)));
nharperb7441ef2016-01-25 23:54:143461 default_context_.set_channel_id_service(channel_id_service_.get());
3462 URLRequestTestHTTP::SetUp();
3463 }
3464
3465 protected:
fdoraya89e673c2017-01-31 21:44:213466 // Required by ChannelIDService.
3467 base::test::ScopedTaskScheduler scoped_task_scheduler_;
danakj8522a25b2016-04-16 00:17:363468 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143469};
3470
3471TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3472 SpawnedTestServer::SSLOptions ssl_options;
3473 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3474 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3475 ssl_options,
3476 base::FilePath(kTestFilePath));
3477 ASSERT_TRUE(https_test_server.Start());
3478
3479 TestDelegate d;
3480 {
danakj8522a25b2016-04-16 00:17:363481 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143482 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3483 r->Start();
3484 EXPECT_TRUE(r->is_pending());
3485
3486 base::RunLoop().Run();
3487
maksim.sisovb53724b52016-09-16 05:30:503488 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143489
3490 HttpRequestHeaders headers;
3491 std::string token_binding_header, token_binding_message;
3492 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3493 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3494 &token_binding_header));
3495 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353496 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143497 &token_binding_message));
nharperd6e65822016-03-30 23:05:483498 std::vector<TokenBinding> token_bindings;
3499 ASSERT_TRUE(
3500 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3501 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143502
3503 EXPECT_GT(d.bytes_received(), 0);
3504 std::string ekm = d.data_received();
3505
nharperd6e65822016-03-30 23:05:483506 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353507 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3508 token_bindings[0].signature,
3509 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143510 }
3511}
nharperd6e65822016-03-30 23:05:483512
3513TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3514 SpawnedTestServer::SSLOptions ssl_options;
3515 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3516 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3517 ssl_options,
3518 base::FilePath(kTestFilePath));
3519 ASSERT_TRUE(https_test_server.Start());
3520
3521 TestDelegate d;
3522 {
3523 GURL redirect_url =
3524 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363525 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483526 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3527 r->Start();
3528 EXPECT_TRUE(r->is_pending());
3529
3530 base::RunLoop().Run();
3531
maksim.sisovb53724b52016-09-16 05:30:503532 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483533
3534 HttpRequestHeaders headers;
3535 std::string token_binding_header, token_binding_message;
3536 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3537 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3538 &token_binding_header));
3539 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353540 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483541 &token_binding_message));
3542 std::vector<TokenBinding> token_bindings;
3543 ASSERT_TRUE(
3544 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3545 ASSERT_EQ(2ull, token_bindings.size());
3546
3547 EXPECT_GT(d.bytes_received(), 0);
3548 std::string ekm = d.data_received();
3549
3550 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353551 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3552 token_bindings[0].signature,
3553 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483554 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353555 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3556 token_bindings[1].signature,
3557 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483558 }
3559}
3560
3561// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3562// EmbeddedTestServer once crbug.com/599187 is resolved.
3563#if !defined(OS_ANDROID)
3564TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3565 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3566 SpawnedTestServer::kLocalhost,
3567 base::FilePath());
3568 ASSERT_TRUE(http_server.Start());
3569 SpawnedTestServer::SSLOptions ssl_options;
3570 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3571 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3572 ssl_options,
3573 base::FilePath(kTestFilePath));
3574 ASSERT_TRUE(https_test_server.Start());
3575
3576 TestDelegate d;
3577 {
3578 GURL redirect_url = http_server.GetURL(
3579 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363580 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483581 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3582 r->Start();
3583 EXPECT_TRUE(r->is_pending());
3584
3585 base::RunLoop().Run();
3586
maksim.sisovb53724b52016-09-16 05:30:503587 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483588
3589 HttpRequestHeaders headers;
3590 std::string token_binding_header, token_binding_message;
3591 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3592 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3593 &token_binding_header));
3594 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353595 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483596 &token_binding_message));
3597 std::vector<TokenBinding> token_bindings;
3598 ASSERT_TRUE(
3599 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3600 ASSERT_EQ(1ull, token_bindings.size());
3601
3602 EXPECT_GT(d.bytes_received(), 0);
3603 std::string ekm = d.data_received();
3604
3605 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353606 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3607 token_bindings[0].signature,
3608 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483609 }
3610}
3611
3612// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363613// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483614// support Token Binding, then we do not send a Sec-Token-Binding when following
3615// the redirect.
3616TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3617 SpawnedTestServer::SSLOptions ssl_options;
3618 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3619 ssl_options,
3620 base::FilePath(kTestFilePath));
3621 ASSERT_TRUE(https_test_server.Start());
3622 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3623 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3624 ssl_options,
3625 base::FilePath(kTestFilePath));
3626 ASSERT_TRUE(token_binding_test_server.Start());
3627
3628 TestDelegate d;
3629 {
3630 GURL redirect_url = token_binding_test_server.GetURL(
3631 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363632 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483633 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3634 r->Start();
3635 EXPECT_TRUE(r->is_pending());
3636
3637 base::RunLoop().Run();
3638
maksim.sisovb53724b52016-09-16 05:30:503639 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483640
3641 HttpRequestHeaders headers;
3642 std::string token_binding_header, token_binding_message;
3643 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3644 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3645 &token_binding_header));
3646 }
3647}
3648#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143649#endif // !defined(OS_IOS)
3650
3651// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113652// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553653// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113654// follow.
[email protected]f2f31b32013-01-16 23:24:093655TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553656 http_test_server()->RegisterRequestHandler(
3657 base::Bind(&HandleRedirectConnect));
3658 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113659
[email protected]ceefd7fd2012-11-29 00:36:243660 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043661 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553662 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503663
[email protected]d1ec59082009-02-11 02:48:153664 TestDelegate d;
3665 {
danakj8522a25b2016-04-16 00:17:363666 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363667 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193668 r->Start();
3669 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153670
[email protected]255620da2013-08-19 13:14:293671 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153672
[email protected]d8fc4722014-06-13 13:17:153673 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473674 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503675 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083676 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153677 // We should not have followed the redirect.
3678 EXPECT_EQ(0, d.received_redirect_count());
3679 }
3680}
3681
[email protected]8202d0c2011-02-23 08:31:143682// This is the same as the previous test, but checks that the network delegate
3683// registers the error.
[email protected]c044616e2013-02-20 02:01:263684TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553685 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143686
[email protected]ceefd7fd2012-11-29 00:36:243687 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043688 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553689 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503690
[email protected]8202d0c2011-02-23 08:31:143691 TestDelegate d;
3692 {
danakj8522a25b2016-04-16 00:17:363693 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363694 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193695 r->Start();
3696 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143697
[email protected]255620da2013-08-19 13:14:293698 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143699
[email protected]d8fc4722014-06-13 13:17:153700 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473701 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:143702 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:503703 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:143704 // We should not have followed the redirect.
3705 EXPECT_EQ(0, d.received_redirect_count());
3706
3707 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:013708 EXPECT_THAT(network_delegate.last_error(),
3709 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143710 }
3711}
3712
[email protected]dc5a5cf2012-09-26 02:49:303713// Tests that we can block and asynchronously return OK in various stages.
3714TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3715 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3716 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3717 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3718 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3719 };
3720 static const size_t blocking_stages_length = arraysize(blocking_stages);
3721
tommycli59a63432015-11-06 00:10:553722 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303723
3724 TestDelegate d;
3725 BlockingNetworkDelegate network_delegate(
3726 BlockingNetworkDelegate::USER_CALLBACK);
3727 network_delegate.set_block_on(
3728 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3729 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3730 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3731
3732 TestURLRequestContext context(true);
3733 context.set_network_delegate(&network_delegate);
3734 context.Init();
3735
3736 {
danakj8522a25b2016-04-16 00:17:363737 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553738 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303739
[email protected]f7022f32014-08-21 16:32:193740 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303741 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293742 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303743 EXPECT_EQ(blocking_stages[i],
3744 network_delegate.stage_blocked_for_callback());
3745 network_delegate.DoCallback(OK);
3746 }
[email protected]255620da2013-08-19 13:14:293747 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193748 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:503749 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:303750 EXPECT_EQ(1, network_delegate.created_requests());
3751 EXPECT_EQ(0, network_delegate.destroyed_requests());
3752 }
3753 EXPECT_EQ(1, network_delegate.destroyed_requests());
3754}
3755
[email protected]4c76d7c2011-04-15 19:14:123756// Tests that the network delegate can block and cancel a request.
3757TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553758 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123759
3760 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303761 BlockingNetworkDelegate network_delegate(
3762 BlockingNetworkDelegate::AUTO_CALLBACK);
3763 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3764 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123765
[email protected]d5a4dd62012-05-23 01:41:043766 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553767 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503768
[email protected]4c76d7c2011-04-15 19:14:123769 {
danakj8522a25b2016-04-16 00:17:363770 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553771 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123772
[email protected]f7022f32014-08-21 16:32:193773 r->Start();
[email protected]255620da2013-08-19 13:14:293774 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123775
[email protected]d8fc4722014-06-13 13:17:153776 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473777 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503778 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:123779 EXPECT_EQ(1, network_delegate.created_requests());
3780 EXPECT_EQ(0, network_delegate.destroyed_requests());
3781 }
3782 EXPECT_EQ(1, network_delegate.destroyed_requests());
3783}
3784
[email protected]b4438d32012-09-27 06:15:303785// Helper function for NetworkDelegateCancelRequestAsynchronously and
3786// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3787// delegate operating in |block_mode| and a request for |url|. It blocks the
3788// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3789void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3790 BlockingNetworkDelegate::Stage stage,
3791 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363792 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303793 BlockingNetworkDelegate network_delegate(block_mode);
3794 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3795 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363796
[email protected]b4438d32012-09-27 06:15:303797 TestURLRequestContext context(true);
3798 context.set_network_delegate(&network_delegate);
3799 context.Init();
[email protected]3cd384c602011-08-31 16:12:363800
3801 {
danakj8522a25b2016-04-16 00:17:363802 std::unique_ptr<URLRequest> r(
3803 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363804
[email protected]f7022f32014-08-21 16:32:193805 r->Start();
[email protected]255620da2013-08-19 13:14:293806 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363807
[email protected]d8fc4722014-06-13 13:17:153808 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473809 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
3810 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
3811 EXPECT_FALSE(r->proxy_server().is_valid());
3812 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
3813 EXPECT_TRUE(r->proxy_server().is_direct());
3814 } else {
3815 NOTREACHED();
3816 }
maksim.sisovb53724b52016-09-16 05:30:503817 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:363818 EXPECT_EQ(1, network_delegate.created_requests());
3819 EXPECT_EQ(0, network_delegate.destroyed_requests());
3820 }
3821 EXPECT_EQ(1, network_delegate.destroyed_requests());
3822}
3823
[email protected]b4438d32012-09-27 06:15:303824// The following 3 tests check that the network delegate can cancel a request
3825// synchronously in various stages of the request.
3826TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553827 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303828 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3829 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553830 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303831}
3832
3833TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553834 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303835 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3836 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553837 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303838}
3839
3840TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553841 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303842 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3843 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553844 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303845}
3846
3847// The following 3 tests check that the network delegate can cancel a request
3848// asynchronously in various stages of the request.
3849TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553850 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303851 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3852 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553853 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303854}
3855
3856TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553857 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303858 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3859 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553860 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303861}
3862
3863TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553864 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303865 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3866 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553867 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303868}
3869
[email protected]4c76d7c2011-04-15 19:14:123870// Tests that the network delegate can block and redirect a request to a new
3871// URL.
3872TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553873 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123874
3875 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303876 BlockingNetworkDelegate network_delegate(
3877 BlockingNetworkDelegate::AUTO_CALLBACK);
3878 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553879 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123880 network_delegate.set_redirect_url(redirect_url);
3881
[email protected]d5a4dd62012-05-23 01:41:043882 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553883 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503884
[email protected]4c76d7c2011-04-15 19:14:123885 {
tommycli59a63432015-11-06 00:10:553886 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363887 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363888 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123889
[email protected]6be6fa92014-08-06 23:44:563890 // Quit after hitting the redirect, so can check the headers.
3891 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193892 r->Start();
[email protected]255620da2013-08-19 13:14:293893 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123894
[email protected]6be6fa92014-08-06 23:44:563895 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193896 EXPECT_EQ(307, r->GetResponseCode());
3897 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563898 std::string location;
[email protected]f7022f32014-08-21 16:32:193899 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3900 &location));
[email protected]6be6fa92014-08-06 23:44:563901 EXPECT_EQ(redirect_url, GURL(location));
3902
3903 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193904 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563905 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503906 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473907 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3908 http_test_server()->host_port_pair()),
3909 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093910 // before_send_headers_with_proxy_count only increments for headers sent
3911 // through an untunneled proxy.
3912 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553913 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3914 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273915
maksim.sisovb53724b52016-09-16 05:30:503916 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193917 EXPECT_EQ(redirect_url, r->url());
3918 EXPECT_EQ(original_url, r->original_url());
3919 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123920 EXPECT_EQ(1, network_delegate.created_requests());
3921 EXPECT_EQ(0, network_delegate.destroyed_requests());
3922 }
3923 EXPECT_EQ(1, network_delegate.destroyed_requests());
3924}
3925
[email protected]b813ed72012-04-05 08:21:363926// Tests that the network delegate can block and redirect a request to a new
3927// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3928TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553929 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363930
3931 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303932 BlockingNetworkDelegate network_delegate(
3933 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553934 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363935 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363936
[email protected]d5a4dd62012-05-23 01:41:043937 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553938 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363939
3940 {
tommycli59a63432015-11-06 00:10:553941 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363942 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363943 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363944
[email protected]6be6fa92014-08-06 23:44:563945 // Quit after hitting the redirect, so can check the headers.
3946 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193947 r->Start();
[email protected]255620da2013-08-19 13:14:293948 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363949
[email protected]6be6fa92014-08-06 23:44:563950 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193951 EXPECT_EQ(307, r->GetResponseCode());
3952 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563953 std::string location;
[email protected]f7022f32014-08-21 16:32:193954 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3955 &location));
[email protected]6be6fa92014-08-06 23:44:563956 EXPECT_EQ(redirect_url, GURL(location));
3957
3958 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193959 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563960 base::RunLoop().Run();
3961
maksim.sisovb53724b52016-09-16 05:30:503962 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473963 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3964 http_test_server()->host_port_pair()),
3965 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093966 // before_send_headers_with_proxy_count only increments for headers sent
3967 // through an untunneled proxy.
3968 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553969 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3970 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:503971 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193972 EXPECT_EQ(redirect_url, r->url());
3973 EXPECT_EQ(original_url, r->original_url());
3974 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363975 EXPECT_EQ(1, network_delegate.created_requests());
3976 EXPECT_EQ(0, network_delegate.destroyed_requests());
3977 }
3978 EXPECT_EQ(1, network_delegate.destroyed_requests());
3979}
3980
[email protected]3c5ca8c2011-09-29 01:14:513981// Tests that redirects caused by the network delegate preserve POST data.
3982TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553983 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513984
3985 const char kData[] = "hello world";
3986
3987 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303988 BlockingNetworkDelegate network_delegate(
3989 BlockingNetworkDelegate::AUTO_CALLBACK);
3990 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553991 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513992 network_delegate.set_redirect_url(redirect_url);
3993
[email protected]ef2bf422012-05-11 03:27:093994 TestURLRequestContext context(true);
3995 context.set_network_delegate(&network_delegate);
3996 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513997
3998 {
tommycli59a63432015-11-06 00:10:553999 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364000 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364001 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194002 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:074003 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:514004 HttpRequestHeaders headers;
4005 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:514006 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:194007 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:564008
4009 // Quit after hitting the redirect, so can check the headers.
4010 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194011 r->Start();
[email protected]255620da2013-08-19 13:14:294012 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514013
[email protected]6be6fa92014-08-06 23:44:564014 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194015 EXPECT_EQ(307, r->GetResponseCode());
4016 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564017 std::string location;
[email protected]f7022f32014-08-21 16:32:194018 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4019 &location));
[email protected]6be6fa92014-08-06 23:44:564020 EXPECT_EQ(redirect_url, GURL(location));
4021
4022 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194023 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564024 base::RunLoop().Run();
4025
maksim.sisovb53724b52016-09-16 05:30:504026 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194027 EXPECT_EQ(redirect_url, r->url());
4028 EXPECT_EQ(original_url, r->original_url());
4029 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514030 EXPECT_EQ(1, network_delegate.created_requests());
4031 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194032 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514033 EXPECT_EQ(kData, d.data_received());
4034 }
4035 EXPECT_EQ(1, network_delegate.destroyed_requests());
4036}
4037
[email protected]5f714132014-03-26 10:41:164038// Tests that the network delegate can block and redirect a request to a new
4039// URL during OnHeadersReceived.
4040TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554041 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164042
4043 TestDelegate d;
4044 BlockingNetworkDelegate network_delegate(
4045 BlockingNetworkDelegate::AUTO_CALLBACK);
4046 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554047 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164048 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4049
4050 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554051 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164052
4053 {
tommycli59a63432015-11-06 00:10:554054 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364055 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364056 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:164057
[email protected]f7022f32014-08-21 16:32:194058 r->Start();
[email protected]5f714132014-03-26 10:41:164059 base::RunLoop().Run();
4060
maksim.sisovb53724b52016-09-16 05:30:504061 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474062 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4063 http_test_server()->host_port_pair()),
4064 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094065 // before_send_headers_with_proxy_count only increments for headers sent
4066 // through an untunneled proxy.
4067 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554068 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4069 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194070
maksim.sisovb53724b52016-09-16 05:30:504071 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194072 EXPECT_EQ(redirect_url, r->url());
4073 EXPECT_EQ(original_url, r->original_url());
4074 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164075 EXPECT_EQ(2, network_delegate.created_requests());
4076 EXPECT_EQ(0, network_delegate.destroyed_requests());
4077 }
4078 EXPECT_EQ(1, network_delegate.destroyed_requests());
4079}
4080
[email protected]c2911d72011-10-03 22:16:364081// Tests that the network delegate can synchronously complete OnAuthRequired
4082// by taking no action. This indicates that the NetworkDelegate does not want to
4083// handle the challenge, and is passing the buck along to the
4084// URLRequest::Delegate.
4085TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554086 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364087
4088 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304089 BlockingNetworkDelegate network_delegate(
4090 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364091
[email protected]ef2bf422012-05-11 03:27:094092 TestURLRequestContext context(true);
4093 context.set_network_delegate(&network_delegate);
4094 context.Init();
[email protected]c2911d72011-10-03 22:16:364095
[email protected]f3cf9802011-10-28 18:44:584096 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364097
4098 {
tommycli59a63432015-11-06 00:10:554099 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364100 std::unique_ptr<URLRequest> r(
4101 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194102 r->Start();
[email protected]79e1fd62013-06-20 06:50:044103
[email protected]255620da2013-08-19 13:14:294104 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044105
maksim.sisovb53724b52016-09-16 05:30:504106 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194107 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044108 EXPECT_TRUE(d.auth_required_called());
4109 EXPECT_EQ(1, network_delegate.created_requests());
4110 EXPECT_EQ(0, network_delegate.destroyed_requests());
4111 }
4112 EXPECT_EQ(1, network_delegate.destroyed_requests());
4113}
4114
4115TEST_F(URLRequestTestHTTP,
4116 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554117 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044118
4119 TestDelegate d;
4120 BlockingNetworkDelegate network_delegate(
4121 BlockingNetworkDelegate::SYNCHRONOUS);
4122
4123 TestURLRequestContext context(true);
4124 context.set_network_delegate(&network_delegate);
4125 context.Init();
4126
4127 d.set_credentials(AuthCredentials(kUser, kSecret));
4128
4129 {
tommycli59a63432015-11-06 00:10:554130 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364131 std::unique_ptr<URLRequest> r(
4132 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194133 r->Start();
[email protected]79e1fd62013-06-20 06:50:044134
4135 {
4136 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194137 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044138 EXPECT_FALSE(headers.HasHeader("Authorization"));
4139 }
4140
[email protected]255620da2013-08-19 13:14:294141 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364142
maksim.sisovb53724b52016-09-16 05:30:504143 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194144 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364145 EXPECT_TRUE(d.auth_required_called());
4146 EXPECT_EQ(1, network_delegate.created_requests());
4147 EXPECT_EQ(0, network_delegate.destroyed_requests());
4148 }
4149 EXPECT_EQ(1, network_delegate.destroyed_requests());
4150}
4151
4152// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404153// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364154TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554155 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364156
4157 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304158 BlockingNetworkDelegate network_delegate(
4159 BlockingNetworkDelegate::SYNCHRONOUS);
4160 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364161 network_delegate.set_auth_retval(
4162 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4163
[email protected]f3cf9802011-10-28 18:44:584164 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364165
[email protected]ef2bf422012-05-11 03:27:094166 TestURLRequestContext context(true);
4167 context.set_network_delegate(&network_delegate);
4168 context.Init();
[email protected]c2911d72011-10-03 22:16:364169
4170 {
tommycli59a63432015-11-06 00:10:554171 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364172 std::unique_ptr<URLRequest> r(
4173 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194174 r->Start();
[email protected]255620da2013-08-19 13:14:294175 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364176
maksim.sisovb53724b52016-09-16 05:30:504177 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194178 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364179 EXPECT_FALSE(d.auth_required_called());
4180 EXPECT_EQ(1, network_delegate.created_requests());
4181 EXPECT_EQ(0, network_delegate.destroyed_requests());
4182 }
4183 EXPECT_EQ(1, network_delegate.destroyed_requests());
4184}
4185
[email protected]79e1fd62013-06-20 06:50:044186// Same as above, but also tests that GetFullRequestHeaders returns the proper
4187// headers (for the first or second request) when called at the proper times.
4188TEST_F(URLRequestTestHTTP,
4189 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554190 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044191
4192 TestDelegate d;
4193 BlockingNetworkDelegate network_delegate(
4194 BlockingNetworkDelegate::SYNCHRONOUS);
4195 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4196 network_delegate.set_auth_retval(
4197 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4198
4199 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4200
4201 TestURLRequestContext context(true);
4202 context.set_network_delegate(&network_delegate);
4203 context.Init();
4204
4205 {
tommycli59a63432015-11-06 00:10:554206 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364207 std::unique_ptr<URLRequest> r(
4208 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194209 r->Start();
[email protected]255620da2013-08-19 13:14:294210 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044211
maksim.sisovb53724b52016-09-16 05:30:504212 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194213 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044214 EXPECT_FALSE(d.auth_required_called());
4215 EXPECT_EQ(1, network_delegate.created_requests());
4216 EXPECT_EQ(0, network_delegate.destroyed_requests());
4217
4218 {
4219 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194220 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044221 EXPECT_TRUE(headers.HasHeader("Authorization"));
4222 }
4223 }
4224 EXPECT_EQ(1, network_delegate.destroyed_requests());
4225}
4226
[email protected]c2911d72011-10-03 22:16:364227// Tests that the network delegate can synchronously complete OnAuthRequired
4228// by cancelling authentication.
4229TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554230 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364231
4232 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304233 BlockingNetworkDelegate network_delegate(
4234 BlockingNetworkDelegate::SYNCHRONOUS);
4235 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364236 network_delegate.set_auth_retval(
4237 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4238
[email protected]ef2bf422012-05-11 03:27:094239 TestURLRequestContext context(true);
4240 context.set_network_delegate(&network_delegate);
4241 context.Init();
[email protected]c2911d72011-10-03 22:16:364242
4243 {
tommycli59a63432015-11-06 00:10:554244 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364245 std::unique_ptr<URLRequest> r(
4246 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194247 r->Start();
[email protected]255620da2013-08-19 13:14:294248 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364249
maksim.sisovb53724b52016-09-16 05:30:504250 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194251 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364252 EXPECT_FALSE(d.auth_required_called());
4253 EXPECT_EQ(1, network_delegate.created_requests());
4254 EXPECT_EQ(0, network_delegate.destroyed_requests());
4255 }
4256 EXPECT_EQ(1, network_delegate.destroyed_requests());
4257}
4258
4259// Tests that the network delegate can asynchronously complete OnAuthRequired
4260// by taking no action. This indicates that the NetworkDelegate does not want
4261// to handle the challenge, and is passing the buck along to the
4262// URLRequest::Delegate.
4263TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554264 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364265
4266 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304267 BlockingNetworkDelegate network_delegate(
4268 BlockingNetworkDelegate::AUTO_CALLBACK);
4269 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364270
[email protected]ef2bf422012-05-11 03:27:094271 TestURLRequestContext context(true);
4272 context.set_network_delegate(&network_delegate);
4273 context.Init();
[email protected]c2911d72011-10-03 22:16:364274
[email protected]f3cf9802011-10-28 18:44:584275 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364276
4277 {
tommycli59a63432015-11-06 00:10:554278 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364279 std::unique_ptr<URLRequest> r(
4280 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194281 r->Start();
[email protected]255620da2013-08-19 13:14:294282 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364283
maksim.sisovb53724b52016-09-16 05:30:504284 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194285 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364286 EXPECT_TRUE(d.auth_required_called());
4287 EXPECT_EQ(1, network_delegate.created_requests());
4288 EXPECT_EQ(0, network_delegate.destroyed_requests());
4289 }
4290 EXPECT_EQ(1, network_delegate.destroyed_requests());
4291}
4292
4293// Tests that the network delegate can asynchronously complete OnAuthRequired
4294// by setting credentials.
4295TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554296 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364297
4298 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304299 BlockingNetworkDelegate network_delegate(
4300 BlockingNetworkDelegate::AUTO_CALLBACK);
4301 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364302 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364303 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4304
[email protected]f3cf9802011-10-28 18:44:584305 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364306 network_delegate.set_auth_credentials(auth_credentials);
4307
[email protected]ef2bf422012-05-11 03:27:094308 TestURLRequestContext context(true);
4309 context.set_network_delegate(&network_delegate);
4310 context.Init();
[email protected]c2911d72011-10-03 22:16:364311
4312 {
tommycli59a63432015-11-06 00:10:554313 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364314 std::unique_ptr<URLRequest> r(
4315 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194316 r->Start();
[email protected]255620da2013-08-19 13:14:294317 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364318
maksim.sisovb53724b52016-09-16 05:30:504319 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194320 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364321 EXPECT_FALSE(d.auth_required_called());
4322 EXPECT_EQ(1, network_delegate.created_requests());
4323 EXPECT_EQ(0, network_delegate.destroyed_requests());
4324 }
4325 EXPECT_EQ(1, network_delegate.destroyed_requests());
4326}
4327
4328// Tests that the network delegate can asynchronously complete OnAuthRequired
4329// by cancelling authentication.
4330TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554331 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364332
4333 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304334 BlockingNetworkDelegate network_delegate(
4335 BlockingNetworkDelegate::AUTO_CALLBACK);
4336 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364337 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364338 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4339
[email protected]ef2bf422012-05-11 03:27:094340 TestURLRequestContext context(true);
4341 context.set_network_delegate(&network_delegate);
4342 context.Init();
[email protected]c2911d72011-10-03 22:16:364343
4344 {
tommycli59a63432015-11-06 00:10:554345 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364346 std::unique_ptr<URLRequest> r(
4347 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194348 r->Start();
[email protected]255620da2013-08-19 13:14:294349 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364350
maksim.sisovb53724b52016-09-16 05:30:504351 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194352 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364353 EXPECT_FALSE(d.auth_required_called());
4354 EXPECT_EQ(1, network_delegate.created_requests());
4355 EXPECT_EQ(0, network_delegate.destroyed_requests());
4356 }
4357 EXPECT_EQ(1, network_delegate.destroyed_requests());
4358}
4359
[email protected]9045b8822012-01-13 20:35:354360// Tests that we can handle when a network request was canceled while we were
4361// waiting for the network delegate.
4362// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4363TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554364 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354365
4366 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304367 BlockingNetworkDelegate network_delegate(
4368 BlockingNetworkDelegate::USER_CALLBACK);
4369 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354370
[email protected]ef2bf422012-05-11 03:27:094371 TestURLRequestContext context(true);
4372 context.set_network_delegate(&network_delegate);
4373 context.Init();
[email protected]9045b8822012-01-13 20:35:354374
4375 {
danakj8522a25b2016-04-16 00:17:364376 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554377 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354378
[email protected]f7022f32014-08-21 16:32:194379 r->Start();
[email protected]255620da2013-08-19 13:14:294380 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304381 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4382 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354383 EXPECT_EQ(0, network_delegate.completed_requests());
4384 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194385 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354386 // Ensure that network delegate is notified.
4387 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504388 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354389 EXPECT_EQ(1, network_delegate.created_requests());
4390 EXPECT_EQ(0, network_delegate.destroyed_requests());
4391 }
4392 EXPECT_EQ(1, network_delegate.destroyed_requests());
4393}
4394
4395// Tests that we can handle when a network request was canceled while we were
4396// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004397// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4398// callback.
[email protected]9045b8822012-01-13 20:35:354399TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554400 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354401
4402 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304403 BlockingNetworkDelegate network_delegate(
4404 BlockingNetworkDelegate::USER_CALLBACK);
4405 network_delegate.set_block_on(
4406 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354407
[email protected]ef2bf422012-05-11 03:27:094408 TestURLRequestContext context(true);
4409 context.set_network_delegate(&network_delegate);
4410 context.Init();
[email protected]9045b8822012-01-13 20:35:354411
4412 {
danakj8522a25b2016-04-16 00:17:364413 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554414 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354415
[email protected]f7022f32014-08-21 16:32:194416 r->Start();
[email protected]255620da2013-08-19 13:14:294417 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304418 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4419 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354420 EXPECT_EQ(0, network_delegate.completed_requests());
4421 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194422 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354423 // Ensure that network delegate is notified.
4424 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504425 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354426 EXPECT_EQ(1, network_delegate.created_requests());
4427 EXPECT_EQ(0, network_delegate.destroyed_requests());
4428 }
4429 EXPECT_EQ(1, network_delegate.destroyed_requests());
4430}
4431
4432// Tests that we can handle when a network request was canceled while we were
4433// waiting for the network delegate.
4434// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4435TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554436 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354437
4438 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304439 BlockingNetworkDelegate network_delegate(
4440 BlockingNetworkDelegate::USER_CALLBACK);
4441 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354442
[email protected]ef2bf422012-05-11 03:27:094443 TestURLRequestContext context(true);
4444 context.set_network_delegate(&network_delegate);
4445 context.Init();
[email protected]9045b8822012-01-13 20:35:354446
4447 {
danakj8522a25b2016-04-16 00:17:364448 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554449 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354450
[email protected]f7022f32014-08-21 16:32:194451 r->Start();
[email protected]255620da2013-08-19 13:14:294452 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304453 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4454 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354455 EXPECT_EQ(0, network_delegate.completed_requests());
4456 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194457 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354458 // Ensure that network delegate is notified.
4459 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504460 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354461 EXPECT_EQ(1, network_delegate.created_requests());
4462 EXPECT_EQ(0, network_delegate.destroyed_requests());
4463 }
4464 EXPECT_EQ(1, network_delegate.destroyed_requests());
4465}
4466
4467// Tests that we can handle when a network request was canceled while we were
4468// waiting for the network delegate.
4469// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024470TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554471 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354472
4473 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304474 BlockingNetworkDelegate network_delegate(
4475 BlockingNetworkDelegate::USER_CALLBACK);
4476 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354477
[email protected]ef2bf422012-05-11 03:27:094478 TestURLRequestContext context(true);
4479 context.set_network_delegate(&network_delegate);
4480 context.Init();
[email protected]9045b8822012-01-13 20:35:354481
4482 {
danakj8522a25b2016-04-16 00:17:364483 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554484 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354485
[email protected]f7022f32014-08-21 16:32:194486 r->Start();
[email protected]255620da2013-08-19 13:14:294487 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304488 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4489 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354490 EXPECT_EQ(0, network_delegate.completed_requests());
4491 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194492 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354493 // Ensure that network delegate is notified.
4494 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504495 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354496 EXPECT_EQ(1, network_delegate.created_requests());
4497 EXPECT_EQ(0, network_delegate.destroyed_requests());
4498 }
4499 EXPECT_EQ(1, network_delegate.destroyed_requests());
4500}
4501
tommycli59a63432015-11-06 00:10:554502namespace {
4503
danakj8522a25b2016-04-16 00:17:364504std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554505 const test_server::HttpRequest& request) {
4506 if (request.headers.find("Host") == request.headers.end() ||
4507 request.headers.at("Host") != "www.server-auth.com" ||
4508 request.method != test_server::METHOD_CONNECT) {
4509 return nullptr;
4510 }
4511
danakj8522a25b2016-04-16 00:17:364512 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554513 new test_server::BasicHttpResponse);
4514 http_response->set_code(HTTP_UNAUTHORIZED);
4515 http_response->AddCustomHeader("WWW-Authenticate",
4516 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484517 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554518}
4519
4520} // namespace
4521
4522// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114523// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554524// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354525TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554526 http_test_server()->RegisterRequestHandler(
4527 base::Bind(&HandleServerAuthConnect));
4528 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114529
[email protected]ceefd7fd2012-11-29 00:36:244530 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044531 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554532 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504533
[email protected]dc651782009-02-14 01:45:084534 TestDelegate d;
4535 {
danakj8522a25b2016-04-16 00:17:364536 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364537 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084538
[email protected]f7022f32014-08-21 16:32:194539 r->Start();
4540 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084541
[email protected]255620da2013-08-19 13:14:294542 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084543
[email protected]d8fc4722014-06-13 13:17:154544 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474545 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504546 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084547 }
4548}
4549
[email protected]b89290212009-08-14 22:37:354550TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554551 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114552
initial.commit586acc5fe2008-07-26 22:42:524553 TestDelegate d;
4554 {
danakj8522a25b2016-04-16 00:17:364555 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554556 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524557
[email protected]f7022f32014-08-21 16:32:194558 r->Start();
4559 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524560
[email protected]255620da2013-08-19 13:14:294561 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524562
4563 EXPECT_EQ(1, d.response_started_count());
4564 EXPECT_FALSE(d.received_data_before_response());
4565 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554566 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194567 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554568 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194569 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164570
[email protected]9e743cd2010-03-16 07:03:534571 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524572 }
initial.commit586acc5fe2008-07-26 22:42:524573}
4574
[email protected]263163f2012-06-14 22:40:344575// This test has the server send a large number of cookies to the client.
4576// To ensure that no number of cookies causes a crash, a galloping binary
4577// search is used to estimate that maximum number of cookies that are accepted
4578// by the browser. Beyond the maximum number, the request will fail with
4579// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304580#if defined(OS_WIN)
4581// http://crbug.com/177916
4582#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4583#else
4584#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4585#endif // defined(OS_WIN)
4586TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554587 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344588
4589 int lower_bound = 0;
4590 int upper_bound = 1;
4591
4592 // Double the number of cookies until the response header limits are
4593 // exceeded.
4594 while (DoManyCookiesRequest(upper_bound)) {
4595 lower_bound = upper_bound;
4596 upper_bound *= 2;
4597 ASSERT_LT(upper_bound, 1000000);
4598 }
4599
pkasting6b68a162014-12-01 22:10:294600 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344601 if (tolerance < 2)
4602 tolerance = 2;
4603
4604 // Perform a binary search to find the highest possible number of cookies,
4605 // within the desired tolerance.
4606 while (upper_bound - lower_bound >= tolerance) {
4607 int num_cookies = (lower_bound + upper_bound) / 2;
4608
4609 if (DoManyCookiesRequest(num_cookies))
4610 lower_bound = num_cookies;
4611 else
4612 upper_bound = num_cookies;
4613 }
4614 // Success: the test did not crash.
4615}
4616
[email protected]b89290212009-08-14 22:37:354617TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554618 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114619
initial.commit586acc5fe2008-07-26 22:42:524620 TestDelegate d;
4621 {
danakj8522a25b2016-04-16 00:17:364622 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554623 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524624
[email protected]f7022f32014-08-21 16:32:194625 r->Start();
4626 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524627
[email protected]255620da2013-08-19 13:14:294628 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524629
4630 EXPECT_EQ(1, d.response_started_count());
4631 EXPECT_FALSE(d.received_data_before_response());
4632 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554633 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194634 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554635 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194636 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524637 }
[email protected]5d7b373e2009-09-02 07:19:034638}
4639
[email protected]79e1fd62013-06-20 06:50:044640TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554641 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044642
4643 TestDelegate d;
4644 {
tommycli59a63432015-11-06 00:10:554645 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364646 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364647 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044648
4649 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194650 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044651
[email protected]f7022f32014-08-21 16:32:194652 r->Start();
4653 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044654
[email protected]255620da2013-08-19 13:14:294655 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044656
4657 EXPECT_EQ(1, d.response_started_count());
4658 EXPECT_FALSE(d.received_data_before_response());
4659 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554660 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194661 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554662 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194663 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044664
4665 EXPECT_TRUE(d.have_full_request_headers());
4666 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4667 }
4668}
4669
[email protected]58e32bb2013-01-21 18:23:254670TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554671 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254672
4673 TestDelegate d;
4674 {
danakj8522a25b2016-04-16 00:17:364675 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554676 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254677
[email protected]f7022f32014-08-21 16:32:194678 r->Start();
4679 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254680
[email protected]255620da2013-08-19 13:14:294681 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254682
4683 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194684 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254685 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4686
4687 EXPECT_EQ(1, d.response_started_count());
4688 EXPECT_FALSE(d.received_data_before_response());
4689 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554690 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194691 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554692 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194693 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254694 }
4695}
4696
tommycli59a63432015-11-06 00:10:554697// TODO(svaldez): Update tests to use EmbeddedTestServer.
4698#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394699TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554700 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4701 SpawnedTestServer::kLocalhost,
4702 base::FilePath(kTestFilePath));
4703
4704 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394705
4706 // Parameter that specifies the Content-Length field in the response:
4707 // C - Compressed length.
4708 // U - Uncompressed length.
4709 // L - Large length (larger than both C & U).
4710 // M - Medium length (between C & U).
4711 // S - Small length (smaller than both C & U).
4712 const char test_parameters[] = "CULMS";
4713 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4714 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444715 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394716 // S has too little data, but we seem to accept it.
4717 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374718 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394719
xunjielifb4da222016-07-14 18:38:594720 base::FilePath file_path;
4721 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
4722 file_path = file_path.Append(kTestFilePath);
4723 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
4724 std::string expected_content;
4725 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
4726
4727 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:394728 TestDelegate d;
4729 {
tommycli59a63432015-11-06 00:10:554730 std::string test_file = base::StringPrintf(
4731 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394732
[email protected]ceefd7fd2012-11-29 00:36:244733 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094734 TestURLRequestContext context(true);
4735 context.set_network_delegate(&network_delegate);
4736 context.Init();
[email protected]87a09a92011-07-14 15:50:504737
danakj8522a25b2016-04-16 00:17:364738 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554739 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194740 r->Start();
4741 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394742
[email protected]255620da2013-08-19 13:14:294743 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394744
4745 EXPECT_EQ(1, d.response_started_count());
4746 EXPECT_FALSE(d.received_data_before_response());
4747 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:504748 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:394749 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:504750 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
4751 << "\"";
xunjielifb4da222016-07-14 18:38:594752 if (test_parameters[i] == 'S') {
4753 // When content length is smaller than both compressed length and
4754 // uncompressed length, HttpStreamParser might not read the full
4755 // response body.
4756 continue;
4757 }
4758 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:394759 } else {
maksim.sisovb53724b52016-09-16 05:30:504760 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:394761 << " Parameter = \"" << test_file << "\"";
4762 }
4763 }
4764 }
4765}
tommycli59a63432015-11-06 00:10:554766#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394767
[email protected]58e32bb2013-01-21 18:23:254768TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554769 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254770
tommycli59a63432015-11-06 00:10:554771 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454772 GURL original_url =
tommycli59a63432015-11-06 00:10:554773 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254774 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364775 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364776 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194777 req->Start();
[email protected]255620da2013-08-19 13:14:294778 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254779
4780 EXPECT_EQ(1, d.response_started_count());
4781 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194782 EXPECT_EQ(destination_url, req->url());
4783 EXPECT_EQ(original_url, req->original_url());
4784 ASSERT_EQ(2U, req->url_chain().size());
4785 EXPECT_EQ(original_url, req->url_chain()[0]);
4786 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254787
4788 LoadTimingInfo load_timing_info_before_redirect;
4789 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4790 &load_timing_info_before_redirect));
4791 TestLoadTimingNotReused(load_timing_info_before_redirect,
4792 CONNECT_TIMING_HAS_DNS_TIMES);
4793
4794 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194795 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254796 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4797
4798 // Check that a new socket was used on redirect, since the server does not
4799 // supposed keep-alive sockets, and that the times before the redirect are
4800 // before the ones recorded for the second request.
4801 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4802 load_timing_info.socket_log_id);
4803 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4804 load_timing_info.connect_timing.connect_start);
4805}
4806
[email protected]8f1ac082011-04-19 21:14:134807TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554808 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134809
tommycli59a63432015-11-06 00:10:554810 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454811 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554812 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4813 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4814 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134815 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364816 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364817 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194818 req->Start();
[email protected]255620da2013-08-19 13:14:294819 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134820
4821 EXPECT_EQ(1, d.response_started_count());
4822 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194823 EXPECT_EQ(destination_url, req->url());
4824 EXPECT_EQ(original_url, req->original_url());
4825 ASSERT_EQ(3U, req->url_chain().size());
4826 EXPECT_EQ(original_url, req->url_chain()[0]);
4827 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4828 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134829}
4830
[email protected]abe1c4a2013-10-25 19:28:514831// First and second pieces of information logged by delegates to URLRequests.
4832const char kFirstDelegateInfo[] = "Wonderful delegate";
4833const char kSecondDelegateInfo[] = "Exciting delegate";
4834
4835// Logs delegate information to a URLRequest. The first string is logged
4836// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4837// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4838// another asynchronous call is used to clear the delegate information
4839// before calling a callback. The object then deletes itself.
4840class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4841 public:
4842 typedef base::Callback<void()> Callback;
4843
4844 // Each time delegate information is added to the URLRequest, the resulting
4845 // load state is checked. The expected load state after each request is
4846 // passed in as an argument.
4847 static void Run(URLRequest* url_request,
4848 LoadState expected_first_load_state,
4849 LoadState expected_second_load_state,
4850 LoadState expected_third_load_state,
4851 const Callback& callback) {
4852 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4853 url_request,
4854 expected_first_load_state,
4855 expected_second_load_state,
4856 expected_third_load_state,
4857 callback);
4858 logger->Start();
4859 }
4860
4861 // Checks that the log entries, starting with log_position, contain the
4862 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4863 // recorded. Returns the index of entry after the expected number of
4864 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464865 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514866 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514867 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4868 if (log_position + 3 >= entries.size()) {
4869 ADD_FAILURE() << "Not enough log entries";
4870 return entries.size();
4871 }
4872 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:004873 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4874 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:074875 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:514876 &delegate_info));
4877 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4878
4879 ++log_position;
mikecirone8b85c432016-09-08 19:11:004880 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4881 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514882
4883 ++log_position;
mikecirone8b85c432016-09-08 19:11:004884 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4885 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:074886 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:514887 &delegate_info));
4888 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4889
4890 ++log_position;
mikecirone8b85c432016-09-08 19:11:004891 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4892 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514893
4894 return log_position + 1;
4895 }
4896
4897 private:
4898 friend class base::RefCounted<AsyncDelegateLogger>;
4899
4900 AsyncDelegateLogger(URLRequest* url_request,
4901 LoadState expected_first_load_state,
4902 LoadState expected_second_load_state,
4903 LoadState expected_third_load_state,
4904 const Callback& callback)
4905 : url_request_(url_request),
4906 expected_first_load_state_(expected_first_load_state),
4907 expected_second_load_state_(expected_second_load_state),
4908 expected_third_load_state_(expected_third_load_state),
4909 callback_(callback) {
4910 }
4911
4912 ~AsyncDelegateLogger() {}
4913
4914 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534915 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514916 LoadStateWithParam load_state = url_request_->GetLoadState();
4917 EXPECT_EQ(expected_first_load_state_, load_state.state);
4918 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454919 base::ThreadTaskRunnerHandle::Get()->PostTask(
4920 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514921 }
4922
4923 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534924 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514925 LoadStateWithParam load_state = url_request_->GetLoadState();
4926 EXPECT_EQ(expected_second_load_state_, load_state.state);
4927 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4928 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4929 } else {
4930 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4931 }
skyostil4891b25b2015-06-11 11:43:454932 base::ThreadTaskRunnerHandle::Get()->PostTask(
4933 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514934 }
4935
4936 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534937 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514938 LoadStateWithParam load_state = url_request_->GetLoadState();
4939 EXPECT_EQ(expected_third_load_state_, load_state.state);
4940 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084941 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514942 callback_.Run();
4943 }
4944
4945 URLRequest* url_request_;
4946 const int expected_first_load_state_;
4947 const int expected_second_load_state_;
4948 const int expected_third_load_state_;
4949 const Callback callback_;
4950
4951 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4952};
4953
4954// NetworkDelegate that logs delegate information before a request is started,
4955// before headers are sent, when headers are read, and when auth information
4956// is requested. Uses AsyncDelegateLogger.
4957class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4958 public:
4959 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204960 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514961
4962 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204963 int OnBeforeURLRequest(URLRequest* request,
4964 const CompletionCallback& callback,
4965 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514966 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4967 return RunCallbackAsynchronously(request, callback);
4968 }
4969
ryansturm2343cb62016-06-15 01:09:004970 int OnBeforeStartTransaction(URLRequest* request,
4971 const CompletionCallback& callback,
4972 HttpRequestHeaders* headers) override {
4973 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514974 return RunCallbackAsynchronously(request, callback);
4975 }
4976
dchengb03027d2014-10-21 12:00:204977 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514978 URLRequest* request,
4979 const CompletionCallback& callback,
4980 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164981 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134982 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164983 TestNetworkDelegate::OnHeadersReceived(request,
4984 callback,
[email protected]abe1c4a2013-10-25 19:28:514985 original_response_headers,
[email protected]5f714132014-03-26 10:41:164986 override_response_headers,
4987 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514988 return RunCallbackAsynchronously(request, callback);
4989 }
4990
dchengb03027d2014-10-21 12:00:204991 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514992 URLRequest* request,
4993 const AuthChallengeInfo& auth_info,
4994 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134995 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514996 AsyncDelegateLogger::Run(
4997 request,
4998 LOAD_STATE_WAITING_FOR_DELEGATE,
4999 LOAD_STATE_WAITING_FOR_DELEGATE,
5000 LOAD_STATE_WAITING_FOR_DELEGATE,
5001 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
5002 callback, credentials));
5003 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
5004 }
5005
5006 private:
5007 static int RunCallbackAsynchronously(
5008 URLRequest* request,
5009 const CompletionCallback& callback) {
5010 AsyncDelegateLogger::Run(
5011 request,
5012 LOAD_STATE_WAITING_FOR_DELEGATE,
5013 LOAD_STATE_WAITING_FOR_DELEGATE,
5014 LOAD_STATE_WAITING_FOR_DELEGATE,
5015 base::Bind(callback, OK));
5016 return ERR_IO_PENDING;
5017 }
5018
5019 static void SetAuthAndResume(const AuthCallback& callback,
5020 AuthCredentials* credentials) {
5021 *credentials = AuthCredentials(kUser, kSecret);
5022 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5023 }
5024
5025 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5026};
5027
5028// URLRequest::Delegate that logs delegate information when the headers
5029// are received, when each read completes, and during redirects. Uses
5030// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5031//
5032// Inherits from TestDelegate to reuse the TestDelegate code to handle
5033// advancing to the next step in most cases, as well as cancellation.
5034class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5035 public:
5036 enum CancelStage {
5037 NO_CANCEL = 0,
5038 CANCEL_ON_RECEIVED_REDIRECT,
5039 CANCEL_ON_RESPONSE_STARTED,
5040 CANCEL_ON_READ_COMPLETED
5041 };
5042
5043 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5044 : cancel_stage_(cancel_stage) {
5045 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5046 set_cancel_in_received_redirect(true);
5047 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5048 set_cancel_in_response_started(true);
5049 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5050 set_cancel_in_received_data(true);
5051 }
dchengb03027d2014-10-21 12:00:205052 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515053
5054 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205055 void OnReceivedRedirect(URLRequest* request,
5056 const RedirectInfo& redirect_info,
5057 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515058 *defer_redirect = true;
5059 AsyncDelegateLogger::Run(
5060 request,
5061 LOAD_STATE_WAITING_FOR_DELEGATE,
5062 LOAD_STATE_WAITING_FOR_DELEGATE,
5063 LOAD_STATE_WAITING_FOR_DELEGATE,
5064 base::Bind(
5065 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595066 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515067 }
5068
maksim.sisov0f4aa142016-09-05 05:55:285069 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515070 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285071 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5072 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5073 base::Bind(
5074 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5075 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515076 }
5077
dchengb03027d2014-10-21 12:00:205078 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515079 AsyncDelegateLogger::Run(
5080 request,
5081 LOAD_STATE_IDLE,
5082 LOAD_STATE_IDLE,
5083 LOAD_STATE_IDLE,
5084 base::Bind(
5085 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5086 base::Unretained(this), request, bytes_read));
5087 }
5088
5089 private:
5090 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595091 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515092 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595093 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515094 // FollowDeferredRedirect should not be called after cancellation.
5095 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5096 return;
5097 if (!defer_redirect)
5098 request->FollowDeferredRedirect();
5099 }
5100
maksim.sisov0f4aa142016-09-05 05:55:285101 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515102 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285103 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515104 }
5105
5106 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5107 // The parent class continues the request.
5108 TestDelegate::OnReadCompleted(request, bytes_read);
5109 }
5110
5111 const CancelStage cancel_stage_;
5112
5113 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5114};
5115
5116// Tests handling of delegate info before a request starts.
5117TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555118 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515119
5120 TestDelegate request_delegate;
5121 TestURLRequestContext context(true);
5122 context.set_network_delegate(NULL);
5123 context.set_net_log(&net_log_);
5124 context.Init();
5125
5126 {
danakj8522a25b2016-04-16 00:17:365127 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555128 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365129 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195130 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515131 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085132 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515133
5134 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195135 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515136 LOAD_STATE_WAITING_FOR_DELEGATE,
5137 LOAD_STATE_WAITING_FOR_DELEGATE,
5138 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195139 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515140
5141 base::RunLoop().Run();
5142
[email protected]f7022f32014-08-21 16:32:195143 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505144 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515145 }
5146
mmenke43758e62015-05-04 21:09:465147 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515148 net_log_.GetEntries(&entries);
5149 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005150 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515151
5152 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5153
5154 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005155 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5156 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515157}
5158
5159// Tests handling of delegate info from a network delegate.
5160TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555161 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515162
5163 TestDelegate request_delegate;
5164 AsyncLoggingNetworkDelegate network_delegate;
5165 TestURLRequestContext context(true);
5166 context.set_network_delegate(&network_delegate);
5167 context.set_net_log(&net_log_);
5168 context.Init();
5169
5170 {
danakj8522a25b2016-04-16 00:17:365171 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555172 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365173 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195174 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515175 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085176 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515177
[email protected]f7022f32014-08-21 16:32:195178 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515179 base::RunLoop().Run();
5180
[email protected]f7022f32014-08-21 16:32:195181 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505182 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515183 EXPECT_EQ(1, network_delegate.created_requests());
5184 EXPECT_EQ(0, network_delegate.destroyed_requests());
5185 }
5186 EXPECT_EQ(1, network_delegate.destroyed_requests());
5187
5188 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465189 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515190 net_log_.GetEntries(&entries);
5191 for (size_t i = 0; i < 3; ++i) {
5192 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005193 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5194 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515195
5196 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5197 log_position + 1);
5198
5199 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005200 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5201 entries[log_position].type);
5202 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515203 }
5204
mikecirone8b85c432016-09-08 19:11:005205 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5206 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515207}
5208
5209// Tests handling of delegate info from a network delegate in the case of an
5210// HTTP redirect.
5211TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555212 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515213
5214 TestDelegate request_delegate;
5215 AsyncLoggingNetworkDelegate network_delegate;
5216 TestURLRequestContext context(true);
5217 context.set_network_delegate(&network_delegate);
5218 context.set_net_log(&net_log_);
5219 context.Init();
5220
5221 {
danakj8522a25b2016-04-16 00:17:365222 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555223 http_test_server()->GetURL("/server-redirect?simple.html"),
5224 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195225 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515226 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085227 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515228
[email protected]f7022f32014-08-21 16:32:195229 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515230 base::RunLoop().Run();
5231
[email protected]f7022f32014-08-21 16:32:195232 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505233 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515234 EXPECT_EQ(2, network_delegate.created_requests());
5235 EXPECT_EQ(0, network_delegate.destroyed_requests());
5236 }
5237 EXPECT_EQ(1, network_delegate.destroyed_requests());
5238
5239 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465240 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515241 net_log_.GetEntries(&entries);
5242 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005243 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515244 for (size_t i = 0; i < 3; ++i) {
5245 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005246 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5247 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515248
5249 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5250 log_position + 1);
5251
5252 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005253 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5254 entries[log_position].type);
5255 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515256 }
5257
5258 // The URLRequest::Delegate then gets informed about the redirect.
5259 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005260 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5261 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515262
5263 // The NetworkDelegate logged information in the same three events as before.
5264 for (size_t i = 0; i < 3; ++i) {
5265 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005266 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5267 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515268
5269 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5270 log_position + 1);
5271
5272 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005273 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5274 entries[log_position].type);
5275 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515276 }
5277
mikecirone8b85c432016-09-08 19:11:005278 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5279 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515280}
5281
5282// Tests handling of delegate info from a network delegate in the case of HTTP
5283// AUTH.
5284TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555285 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515286
5287 TestDelegate request_delegate;
5288 AsyncLoggingNetworkDelegate network_delegate;
5289 TestURLRequestContext context(true);
5290 context.set_network_delegate(&network_delegate);
5291 context.set_net_log(&net_log_);
5292 context.Init();
5293
5294 {
danakj8522a25b2016-04-16 00:17:365295 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555296 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365297 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195298 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515299 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085300 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515301
[email protected]f7022f32014-08-21 16:32:195302 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515303 base::RunLoop().Run();
5304
[email protected]f7022f32014-08-21 16:32:195305 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505306 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515307 EXPECT_EQ(1, network_delegate.created_requests());
5308 EXPECT_EQ(0, network_delegate.destroyed_requests());
5309 }
5310 EXPECT_EQ(1, network_delegate.destroyed_requests());
5311
5312 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465313 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515314 net_log_.GetEntries(&entries);
5315 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005316 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5317 // in
5318 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515319 for (size_t i = 0; i < 6; ++i) {
5320 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005321 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5322 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515323
5324 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5325 log_position + 1);
5326
5327 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005328 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5329 entries[log_position].type);
5330 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515331 }
5332
mikecirone8b85c432016-09-08 19:11:005333 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5334 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515335}
5336
tommycli59a63432015-11-06 00:10:555337// TODO(svaldez): Update tests to use EmbeddedTestServer.
5338#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515339// Tests handling of delegate info from a URLRequest::Delegate.
5340TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555341 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5342 SpawnedTestServer::kLocalhost,
5343 base::FilePath(kTestFilePath));
5344
5345 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515346
5347 AsyncLoggingUrlRequestDelegate request_delegate(
5348 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5349 TestURLRequestContext context(true);
5350 context.set_network_delegate(NULL);
5351 context.set_net_log(&net_log_);
5352 context.Init();
5353
5354 {
5355 // A chunked response with delays between chunks is used to make sure that
5356 // attempts by the URLRequest delegate to log information while reading the
5357 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485358 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515359 // that it occurs.
danakj8522a25b2016-04-16 00:17:365360 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555361 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365362 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195363 LoadStateWithParam load_state = r->GetLoadState();
5364 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515365 base::RunLoop().Run();
5366
[email protected]f7022f32014-08-21 16:32:195367 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505368 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515369 }
5370
mmenke43758e62015-05-04 21:09:465371 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515372 net_log_.GetEntries(&entries);
5373
[email protected]1826a402014-01-08 15:40:485374 size_t log_position = 0;
5375
[email protected]abe1c4a2013-10-25 19:28:515376 // The delegate info should only have been logged on header complete. Other
5377 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005378 log_position = ExpectLogContainsSomewhereAfter(
5379 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5380 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515381
5382 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5383 log_position + 1);
5384
5385 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005386 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5387 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515388
mikecirone8b85c432016-09-08 19:11:005389 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5390 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515391 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005392 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515393}
tommycli59a63432015-11-06 00:10:555394#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515395
5396// Tests handling of delegate info from a URLRequest::Delegate in the case of
5397// an HTTP redirect.
5398TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555399 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515400
5401 AsyncLoggingUrlRequestDelegate request_delegate(
5402 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5403 TestURLRequestContext context(true);
5404 context.set_network_delegate(NULL);
5405 context.set_net_log(&net_log_);
5406 context.Init();
5407
5408 {
danakj8522a25b2016-04-16 00:17:365409 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555410 http_test_server()->GetURL("/server-redirect?simple.html"),
5411 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195412 LoadStateWithParam load_state = r->GetLoadState();
5413 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515414 base::RunLoop().Run();
5415
[email protected]f7022f32014-08-21 16:32:195416 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505417 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515418 }
5419
mmenke43758e62015-05-04 21:09:465420 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515421 net_log_.GetEntries(&entries);
5422
5423 // Delegate info should only have been logged in OnReceivedRedirect and
5424 // OnResponseStarted.
5425 size_t log_position = 0;
5426 for (int i = 0; i < 2; ++i) {
5427 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005428 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5429 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515430
5431 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5432 log_position + 1);
5433
5434 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005435 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5436 entries[log_position].type);
5437 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515438 }
5439
mikecirone8b85c432016-09-08 19:11:005440 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5441 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515442 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005443 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515444}
5445
5446// Tests handling of delegate info from a URLRequest::Delegate in the case of
5447// an HTTP redirect, with cancellation at various points.
5448TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555449 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515450
5451 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5452 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5453 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5454 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5455 };
5456
5457 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5458 ++test_case) {
5459 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
vishal.b62985ca92015-04-17 08:45:515460 TestNetLog net_log;
krasin0bfeb6b2017-01-13 21:48:045461 TestURLRequestContext context(true);
[email protected]abe1c4a2013-10-25 19:28:515462 context.set_network_delegate(NULL);
5463 context.set_net_log(&net_log);
5464 context.Init();
5465
5466 {
danakj8522a25b2016-04-16 00:17:365467 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555468 http_test_server()->GetURL("/server-redirect?simple.html"),
5469 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195470 LoadStateWithParam load_state = r->GetLoadState();
5471 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515472 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505473 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515474 }
5475
mmenke43758e62015-05-04 21:09:465476 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515477 net_log.GetEntries(&entries);
5478
5479 // Delegate info is always logged in both OnReceivedRedirect and
5480 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5481 // OnResponseStarted delegate call is after cancellation, but logging is
5482 // still currently supported in that call.
5483 size_t log_position = 0;
5484 for (int i = 0; i < 2; ++i) {
5485 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005486 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5487 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515488
5489 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5490 log_position + 1);
5491
5492 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005493 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5494 entries[log_position].type);
5495 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515496 }
5497
mikecirone8b85c432016-09-08 19:11:005498 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5499 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515500 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005501 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515502 }
5503}
5504
[email protected]847c0fa92012-11-06 16:37:425505namespace {
5506
5507const char kExtraHeader[] = "Allow-Snafu";
5508const char kExtraValue[] = "fubar";
5509
5510class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205511 void OnReceivedRedirect(URLRequest* request,
5512 const RedirectInfo& redirect_info,
5513 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595514 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425515 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5516 }
5517};
5518
5519} // namespace
5520
5521TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555522 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425523
tommycli59a63432015-11-06 00:10:555524 GURL destination_url =
5525 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5526 GURL original_url =
5527 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425528 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365529 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365530 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195531 req->Start();
[email protected]255620da2013-08-19 13:14:295532 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425533
5534 std::string value;
[email protected]f7022f32014-08-21 16:32:195535 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425536 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5537 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195538 EXPECT_FALSE(req->is_pending());
5539 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425540 EXPECT_EQ(kExtraValue, d.data_received());
5541}
5542
[email protected]251a1b92012-11-13 11:01:095543namespace {
5544
5545const char kExtraHeaderToRemove[] = "To-Be-Removed";
5546
5547class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205548 void OnReceivedRedirect(URLRequest* request,
5549 const RedirectInfo& redirect_info,
5550 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595551 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095552 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5553 }
5554};
5555
5556} // namespace
5557
5558TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555559 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095560
tommycli59a63432015-11-06 00:10:555561 GURL destination_url = http_test_server()->GetURL(
5562 "/echoheader?" + std::string(kExtraHeaderToRemove));
5563 GURL original_url =
5564 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095565 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365566 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365567 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195568 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5569 req->Start();
[email protected]255620da2013-08-19 13:14:295570 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095571
5572 std::string value;
[email protected]f7022f32014-08-21 16:32:195573 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095574 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195575 EXPECT_FALSE(req->is_pending());
5576 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095577 EXPECT_EQ("None", d.data_received());
5578}
5579
mmenke94f1bd92016-12-07 21:13:055580TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:445581 TestDelegate d;
5582 {
danakj8522a25b2016-04-16 00:17:365583 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365584 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445585
[email protected]f7022f32014-08-21 16:32:195586 r->Start();
5587 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445588
[email protected]f7022f32014-08-21 16:32:195589 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445590
[email protected]255620da2013-08-19 13:14:295591 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445592
5593 // We expect to receive OnResponseStarted even though the request has been
5594 // cancelled.
5595 EXPECT_EQ(1, d.response_started_count());
5596 EXPECT_EQ(0, d.bytes_received());
5597 EXPECT_FALSE(d.received_data_before_response());
5598 }
5599}
5600
mmenke94f1bd92016-12-07 21:13:055601TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:555602 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445603
5604 TestDelegate d;
5605 {
danakj8522a25b2016-04-16 00:17:365606 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555607 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445608
5609 d.set_cancel_in_response_started(true);
5610
[email protected]f7022f32014-08-21 16:32:195611 r->Start();
5612 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445613
[email protected]255620da2013-08-19 13:14:295614 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445615
5616 EXPECT_EQ(1, d.response_started_count());
5617 EXPECT_EQ(0, d.bytes_received());
5618 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505619 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445620 }
5621}
5622
mmenke94f1bd92016-12-07 21:13:055623TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:555624 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445625
5626 TestDelegate d;
5627 {
danakj8522a25b2016-04-16 00:17:365628 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke94f1bd92016-12-07 21:13:055629 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
5630
5631 d.set_cancel_in_received_data(true);
5632
5633 r->Start();
5634 EXPECT_TRUE(r->is_pending());
5635
5636 base::RunLoop().Run();
5637
5638 EXPECT_EQ(1, d.response_started_count());
5639 EXPECT_NE(0, d.received_bytes_count());
5640 EXPECT_FALSE(d.received_data_before_response());
5641 EXPECT_EQ(ERR_ABORTED, d.request_status());
5642 }
5643}
5644
5645TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
5646 ASSERT_TRUE(http_test_server()->Start());
5647
5648 TestDelegate d;
5649 {
5650 // This returns an empty response (With headers).
5651 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555652 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445653
5654 d.set_cancel_in_received_data(true);
5655
[email protected]f7022f32014-08-21 16:32:195656 r->Start();
5657 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445658
[email protected]255620da2013-08-19 13:14:295659 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445660
5661 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:055662 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:445663 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505664 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445665 }
5666}
5667
mmenke94f1bd92016-12-07 21:13:055668TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:555669 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445670
5671 TestDelegate d;
5672 {
danakj8522a25b2016-04-16 00:17:365673 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555674 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445675
[email protected]f7022f32014-08-21 16:32:195676 r->Start();
5677 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445678
5679 // The request will be implicitly canceled when it is destroyed. The
5680 // test delegate must not post a quit message when this happens because
5681 // this test doesn't actually have a message loop. The quit message would
5682 // get put on this thread's message queue and the next test would exit
5683 // early, causing problems.
5684 d.set_quit_on_complete(false);
5685 }
5686 // expect things to just cleanup properly.
5687
kimwjdalsl2bb4ff02015-12-16 22:06:025688 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445689 // message loop
5690 EXPECT_FALSE(d.received_data_before_response());
5691 EXPECT_EQ(0, d.bytes_received());
5692}
5693
mmenke94f1bd92016-12-07 21:13:055694TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:555695 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445696
5697 // populate cache
5698 {
5699 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365700 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555701 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195702 r->Start();
[email protected]255620da2013-08-19 13:14:295703 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505704 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445705 }
5706
5707 // cancel read from cache (see bug 990242)
5708 {
5709 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365710 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555711 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195712 r->Start();
5713 r->Cancel();
[email protected]255620da2013-08-19 13:14:295714 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445715
maksim.sisovb53724b52016-09-16 05:30:505716 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445717 EXPECT_EQ(1, d.response_started_count());
5718 EXPECT_EQ(0, d.bytes_received());
5719 EXPECT_FALSE(d.received_data_before_response());
5720 }
5721}
5722
5723TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555724 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445725 HTTPUploadDataOperationTest("POST");
5726}
5727
5728TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555729 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445730 HTTPUploadDataOperationTest("PUT");
5731}
5732
5733TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555734 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445735
5736 TestDelegate d;
5737 {
danakj8522a25b2016-04-16 00:17:365738 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555739 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195740 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445741
[email protected]f7022f32014-08-21 16:32:195742 r->Start();
5743 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445744
[email protected]255620da2013-08-19 13:14:295745 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445746
maksim.sisovb53724b52016-09-16 05:30:505747 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5748 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445749
5750 EXPECT_FALSE(d.received_data_before_response());
5751 EXPECT_TRUE(d.data_received().empty());
5752 }
5753}
5754
5755TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555756 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445757
5758 TestDelegate d;
5759 {
danakj8522a25b2016-04-16 00:17:365760 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555761 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195762 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445763
[email protected]6cdfd7f2013-02-08 20:40:155764 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445765 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025766 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445767
danakj8522a25b2016-04-16 00:17:365768 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445769
[email protected]6cdfd7f2013-02-08 20:40:155770 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445771 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475772 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445773 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
ricea2deef682016-09-09 08:04:075774 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:145775 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:075776 std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365777 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225778 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445779
[email protected]f7022f32014-08-21 16:32:195780 r->Start();
5781 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445782
[email protected]255620da2013-08-19 13:14:295783 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445784
avibf0746c2015-12-09 19:53:145785 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295786 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5787 ASSERT_LE(size64, std::numeric_limits<int>::max());
5788 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365789 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445790
[email protected]7600d0b2013-12-08 21:43:305791 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445792
maksim.sisovb53724b52016-09-16 05:30:505793 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5794 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445795
5796 EXPECT_FALSE(d.received_data_before_response());
5797
[email protected]329b68b2012-11-14 17:54:275798 EXPECT_EQ(size, d.bytes_received());
5799 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445800 }
5801}
5802
[email protected]999dd8c2013-11-12 06:45:545803TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555804 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545805
5806 TestDelegate d;
5807 {
danakj8522a25b2016-04-16 00:17:365808 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555809 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195810 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545811
danakj8522a25b2016-04-16 00:17:365812 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545813
ricea2deef682016-09-09 08:04:075814 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:455815 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545816 base::FilePath(FILE_PATH_LITERAL(
5817 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:075818 0, std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365819 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225820 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545821
[email protected]f7022f32014-08-21 16:32:195822 r->Start();
5823 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545824
5825 base::RunLoop().Run();
5826
[email protected]999dd8c2013-11-12 06:45:545827 EXPECT_TRUE(d.request_failed());
5828 EXPECT_FALSE(d.received_data_before_response());
5829 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:505830 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:545831 }
5832}
5833
mmenke56b0cbb912016-03-28 21:34:535834namespace {
5835
5836// Adds a standard set of data to an upload for chunked upload integration
5837// tests.
5838void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5839 writer->AppendData("a", 1, false);
5840 writer->AppendData("bcd", 3, false);
5841 writer->AppendData("this is a longer chunk than before.", 35, false);
5842 writer->AppendData("\r\n\r\n", 4, false);
5843 writer->AppendData("0", 1, false);
5844 writer->AppendData("2323", 4, true);
5845}
5846
5847// Checks that the upload data added in AddChunksToUpload() was echoed back from
5848// the server.
5849void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5850 // This should match the chunks sent by AddChunksToUpload().
5851 const std::string expected_data =
5852 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5853
maksim.sisovb53724b52016-09-16 05:30:505854 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
5855 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:535856
5857 EXPECT_FALSE(d->received_data_before_response());
5858
5859 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5860 EXPECT_EQ(expected_data, d->data_received());
5861}
5862
5863} // namespace
5864
[email protected]316c1e5e2012-09-12 15:17:445865TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555866 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445867
5868 TestDelegate d;
5869 {
danakj8522a25b2016-04-16 00:17:365870 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555871 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365872 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535873 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365874 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535875 upload_data_stream->CreateWriter();
5876 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195877 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535878 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195879 r->Start();
5880 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445881
[email protected]255620da2013-08-19 13:14:295882 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445883
[email protected]f7022f32014-08-21 16:32:195884 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445885 }
5886}
5887
[email protected]329b68b2012-11-14 17:54:275888TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555889 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275890
5891 TestDelegate d;
5892 {
danakj8522a25b2016-04-16 00:17:365893 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555894 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365895 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535896 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365897 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535898 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365899 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195900 r->set_method("POST");
5901 r->Start();
5902 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535903 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295904 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275905
[email protected]f7022f32014-08-21 16:32:195906 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275907 }
5908}
5909
[email protected]316c1e5e2012-09-12 15:17:445910TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555911 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445912
5913 TestDelegate d;
5914 {
danakj8522a25b2016-04-16 00:17:365915 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555916 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365917 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535918 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365919 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535920 upload_data_stream->CreateWriter();
5921 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195922 r->set_method("POST");
5923 r->Start();
5924 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445925
[email protected]255620da2013-08-19 13:14:295926 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535927 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295928 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445929
[email protected]f7022f32014-08-21 16:32:195930 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445931 }
5932}
5933
5934TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555935 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445936
5937 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365938 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555939 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195940 req->Start();
[email protected]255620da2013-08-19 13:14:295941 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445942
[email protected]f7022f32014-08-21 16:32:195943 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445944
5945 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195946 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445947
5948 std::string header;
5949 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5950 EXPECT_EQ("private", header);
5951
5952 header.clear();
5953 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5954 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5955
5956 // The response has two "X-Multiple-Entries" headers.
5957 // This verfies our output has them concatenated together.
5958 header.clear();
5959 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5960 EXPECT_EQ("a, b", header);
5961}
5962
tommycli59a63432015-11-06 00:10:555963// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5964// security state. (see http://crbug.com/550977).
5965#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465966TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555967 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5968 https_test_server.SetSSLConfig(
5969 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5970 https_test_server.ServeFilesFromSourceDirectory(
5971 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465972 ASSERT_TRUE(https_test_server.Start());
5973
tommycli59a63432015-11-06 00:10:555974 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465975 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365976 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555977 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195978 request->Start();
[email protected]255620da2013-08-19 13:14:295979 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465980
5981 TransportSecurityState* security_state =
5982 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405983 TransportSecurityState::STSState sts_state;
5984 TransportSecurityState::PKPState pkp_state;
5985 EXPECT_TRUE(
5986 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5987 EXPECT_FALSE(
5988 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5989 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5990 sts_state.upgrade_mode);
5991 EXPECT_TRUE(sts_state.include_subdomains);
5992 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035993#if defined(OS_ANDROID)
5994 // Android's CertVerifyProc does not (yet) handle pins.
5995#else
martijnc0d6b622015-06-30 19:14:405996 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035997#endif
[email protected]37fd55fb2013-06-29 13:13:275998}
5999
estarka5da76702015-04-09 04:00:166000TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556001 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6002 https_test_server.ServeFilesFromSourceDirectory(
6003 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166004 ASSERT_TRUE(https_test_server.Start());
6005 // Make sure this test fails if the test server is changed to not
6006 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556007 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6008 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166009
6010 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366011 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556012 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166013 request->Start();
6014 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166015 TransportSecurityState* security_state =
6016 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406017 TransportSecurityState::STSState sts_state;
6018 EXPECT_FALSE(
6019 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166020}
6021
estark06e0dac2015-08-07 21:56:016022namespace {
estark1614475f2016-03-10 03:46:476023const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:246024const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
6025const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:016026const char kHPKPReportUri[] = "https://hpkp-report.test";
6027} // namespace
6028
[email protected]37fd55fb2013-06-29 13:13:276029// Tests that enabling HPKP on a domain does not affect the HSTS
6030// validity/expiration.
dadrian2faf2062016-07-16 00:03:176031TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016032 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556033 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6034 https_test_server.SetSSLConfig(
6035 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6036 https_test_server.ServeFilesFromSourceDirectory(
6037 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276038 ASSERT_TRUE(https_test_server.Start());
6039
tommycli59a63432015-11-06 00:10:556040 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166041
[email protected]37fd55fb2013-06-29 13:13:276042 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366043 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556044 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196045 request->Start();
[email protected]255620da2013-08-19 13:14:296046 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276047 TransportSecurityState* security_state =
6048 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406049 TransportSecurityState::STSState sts_state;
6050 TransportSecurityState::PKPState pkp_state;
6051 EXPECT_FALSE(
6052 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6053 EXPECT_TRUE(
6054 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6055 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6056 sts_state.upgrade_mode);
6057 EXPECT_FALSE(sts_state.include_subdomains);
6058 EXPECT_FALSE(pkp_state.include_subdomains);
6059 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016060 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406061 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466062}
6063
estark06e0dac2015-08-07 21:56:016064// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176065TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016066 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556067 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6068 https_test_server.SetSSLConfig(
6069 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6070 https_test_server.ServeFilesFromSourceDirectory(
6071 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016072 ASSERT_TRUE(https_test_server.Start());
6073
tommycli59a63432015-11-06 00:10:556074 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016075
6076 // Set up a pin for |test_server_hostname|.
6077 TransportSecurityState security_state;
6078 const base::Time current_time(base::Time::Now());
6079 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6080 HashValueVector hashes;
6081 HashValue hash1;
6082 HashValue hash2;
6083 // The values here don't matter, as long as they are different from
6084 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446085 ASSERT_TRUE(
6086 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6087 ASSERT_TRUE(
6088 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016089 hashes.push_back(hash1);
6090 hashes.push_back(hash2);
6091 security_state.AddHPKP(test_server_hostname, expiry,
6092 false, /* include subdomains */
6093 hashes, report_uri);
6094
6095 MockCertificateReportSender mock_report_sender;
6096 security_state.SetReportSender(&mock_report_sender);
6097
6098 // Set up a MockCertVerifier to trigger a violation of the previously
6099 // set pin.
6100 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6101 ASSERT_TRUE(cert);
6102
6103 MockCertVerifier cert_verifier;
6104 CertVerifyResult verify_result;
6105 verify_result.verified_cert = cert;
6106 verify_result.is_issued_by_known_root = true;
6107 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446108 ASSERT_TRUE(
6109 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016110 verify_result.public_key_hashes.push_back(hash3);
6111 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6112
6113 TestNetworkDelegate network_delegate;
6114 TestURLRequestContext context(true);
6115 context.set_transport_security_state(&security_state);
6116 context.set_network_delegate(&network_delegate);
6117 context.set_cert_verifier(&cert_verifier);
6118 context.Init();
6119
6120 // Now send a request to trigger the violation.
6121 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366122 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556123 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016124 violating_request->Start();
6125 base::RunLoop().Run();
6126
6127 // Check that a report was sent.
6128 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6129 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446130 EXPECT_EQ("application/json; charset=utf-8",
6131 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366132 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016133 base::JSONReader::Read(mock_report_sender.latest_report()));
6134 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286135 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016136 base::DictionaryValue* report_dict;
6137 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6138 std::string report_hostname;
6139 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6140 EXPECT_EQ(test_server_hostname, report_hostname);
6141}
6142
6143// Tests that reports get sent on requests with
6144// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176145TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016146 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556147 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6148 https_test_server.SetSSLConfig(
6149 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6150 https_test_server.ServeFilesFromSourceDirectory(
6151 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016152 ASSERT_TRUE(https_test_server.Start());
6153
tommycli59a63432015-11-06 00:10:556154 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016155
6156 TransportSecurityState security_state;
6157 MockCertificateReportSender mock_report_sender;
6158 security_state.SetReportSender(&mock_report_sender);
6159
6160 // Set up a MockCertVerifier to violate the pin in the Report-Only
6161 // header.
6162 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6163 ASSERT_TRUE(cert);
6164
6165 MockCertVerifier cert_verifier;
6166 CertVerifyResult verify_result;
6167 verify_result.verified_cert = cert;
6168 verify_result.is_issued_by_known_root = true;
6169 HashValue hash;
6170 // This value doesn't matter, as long as it is different from the pins
6171 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446172 ASSERT_TRUE(
6173 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016174 verify_result.public_key_hashes.push_back(hash);
6175 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6176
6177 TestNetworkDelegate network_delegate;
6178 TestURLRequestContext context(true);
6179 context.set_transport_security_state(&security_state);
6180 context.set_network_delegate(&network_delegate);
6181 context.set_cert_verifier(&cert_verifier);
6182 context.Init();
6183
6184 // Now send a request to trigger the violation.
6185 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366186 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556187 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016188 DEFAULT_PRIORITY, &d));
6189 violating_request->Start();
6190 base::RunLoop().Run();
6191
6192 // Check that a report was sent.
6193 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6194 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446195 EXPECT_EQ("application/json; charset=utf-8",
6196 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366197 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016198 base::JSONReader::Read(mock_report_sender.latest_report()));
6199 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286200 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016201 base::DictionaryValue* report_dict;
6202 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6203 std::string report_hostname;
6204 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6205 EXPECT_EQ(test_server_hostname, report_hostname);
6206}
6207
6208// Tests that reports do not get sent on requests with
6209// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176210TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016211 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556212 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6213 https_test_server.SetSSLConfig(
6214 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6215 https_test_server.ServeFilesFromSourceDirectory(
6216 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016217 ASSERT_TRUE(https_test_server.Start());
6218
tommycli59a63432015-11-06 00:10:556219 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016220
6221 TransportSecurityState security_state;
6222 MockCertificateReportSender mock_report_sender;
6223 security_state.SetReportSender(&mock_report_sender);
6224
6225 TestNetworkDelegate network_delegate;
6226 MockCertVerifier mock_cert_verifier;
6227 TestURLRequestContext context(true);
6228 context.set_transport_security_state(&security_state);
6229 context.set_network_delegate(&network_delegate);
6230 context.set_cert_verifier(&mock_cert_verifier);
6231 mock_cert_verifier.set_default_result(OK);
6232 context.Init();
6233
6234 // Now send a request that does not trigger the violation.
6235 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366236 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556237 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016238 DEFAULT_PRIORITY, &d));
6239 request->Start();
6240 base::RunLoop().Run();
6241
6242 // Check that a report was not sent.
6243 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6244 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6245}
6246
estarka5da76702015-04-09 04:00:166247TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556248 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6249 https_test_server.ServeFilesFromSourceDirectory(
6250 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166251 ASSERT_TRUE(https_test_server.Start());
6252 // Make sure this test fails if the test server is changed to not
6253 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556254 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6255 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166256
6257 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366258 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556259 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166260 request->Start();
6261 base::RunLoop().Run();
6262
6263 TransportSecurityState* security_state =
6264 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406265 TransportSecurityState::PKPState pkp_state;
6266 EXPECT_FALSE(
6267 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166268}
6269
dadriandf302c42016-06-10 18:48:596270TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6271 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6272 https_test_server.SetSSLConfig(
6273 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6274 https_test_server.ServeFilesFromSourceDirectory(
6275 base::FilePath(kTestFilePath));
6276 ASSERT_TRUE(https_test_server.Start());
6277
6278 // Set up a MockCertVerifier to be a local root that violates the pin
6279 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6280 ASSERT_TRUE(cert);
6281
6282 MockCertVerifier cert_verifier;
6283 CertVerifyResult verify_result;
6284 verify_result.verified_cert = cert;
6285 verify_result.is_issued_by_known_root = false;
6286 HashValue hash;
6287 ASSERT_TRUE(
6288 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6289 verify_result.public_key_hashes.push_back(hash);
6290 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6291 cert_verifier.set_default_result(OK);
6292
6293 std::string test_server_hostname = https_test_server.GetURL("/").host();
6294
6295 // Set up HPKP
6296 base::Time current_time = base::Time::Now();
6297 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6298 HashValue pin;
6299 ASSERT_TRUE(
6300 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6301 HashValueVector hashes;
6302 hashes.push_back(pin);
6303 GURL report_uri(kHPKPReportUri);
6304 TransportSecurityState security_state;
6305 security_state.AddHPKP(test_server_hostname, expiry,
6306 false, /* include subdomains */
6307 hashes, report_uri);
6308
6309 TestNetworkDelegate network_delegate;
6310 TestURLRequestContext context(true);
6311 context.set_transport_security_state(&security_state);
6312 context.set_network_delegate(&network_delegate);
6313 context.set_cert_verifier(&cert_verifier);
6314 context.Init();
6315
6316 TestDelegate d;
6317 std::unique_ptr<URLRequest> request(context.CreateRequest(
6318 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6319 request->Start();
6320 base::RunLoop().Run();
6321
6322 TransportSecurityState::PKPState pkp_state;
6323 EXPECT_TRUE(
6324 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6325 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6326}
6327
[email protected]242d8562012-10-30 21:20:466328TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556329 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6330 https_test_server.SetSSLConfig(
6331 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6332 https_test_server.ServeFilesFromSourceDirectory(
6333 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466334 ASSERT_TRUE(https_test_server.Start());
6335
tommycli59a63432015-11-06 00:10:556336 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166337
[email protected]242d8562012-10-30 21:20:466338 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366339 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556340 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6341 &d));
[email protected]f7022f32014-08-21 16:32:196342 request->Start();
[email protected]255620da2013-08-19 13:14:296343 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466344
6345 // We should have set parameters from the first header, not the second.
6346 TransportSecurityState* security_state =
6347 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406348 TransportSecurityState::STSState sts_state;
6349 EXPECT_TRUE(
6350 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6351 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6352 sts_state.upgrade_mode);
6353 EXPECT_FALSE(sts_state.include_subdomains);
6354 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466355}
6356
[email protected]9f972ec2013-04-10 20:24:366357TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556358 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6359 https_test_server.SetSSLConfig(
6360 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6361 https_test_server.ServeFilesFromSourceDirectory(
6362 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366363 ASSERT_TRUE(https_test_server.Start());
6364
tommycli59a63432015-11-06 00:10:556365 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166366
[email protected]9f972ec2013-04-10 20:24:366367 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366368 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556369 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6370 &d));
[email protected]f7022f32014-08-21 16:32:196371 request->Start();
[email protected]255620da2013-08-19 13:14:296372 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366373
6374 // We should have set parameters from the first header, not the second.
6375 TransportSecurityState* security_state =
6376 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406377 TransportSecurityState::STSState sts_state;
6378 TransportSecurityState::PKPState pkp_state;
6379 EXPECT_TRUE(
6380 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6381 EXPECT_TRUE(
6382 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6383 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6384 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036385#if defined(OS_ANDROID)
6386 // Android's CertVerifyProc does not (yet) handle pins.
6387#else
martijnc0d6b622015-06-30 19:14:406388 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036389#endif
martijnc0d6b622015-06-30 19:14:406390 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366391
[email protected]a165f092013-06-12 16:10:056392 // Even though there is an HSTS header asserting includeSubdomains, it is
6393 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406394 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056395 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406396 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366397}
6398
[email protected]37fd55fb2013-06-29 13:13:276399// Tests that when multiple HPKP headers are present, asserting different
6400// policies, that only the first such policy is processed.
6401TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556402 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6403 https_test_server.SetSSLConfig(
6404 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6405 https_test_server.ServeFilesFromSourceDirectory(
6406 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276407 ASSERT_TRUE(https_test_server.Start());
6408
tommycli59a63432015-11-06 00:10:556409 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166410
[email protected]37fd55fb2013-06-29 13:13:276411 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366412 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556413 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366414 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196415 request->Start();
[email protected]255620da2013-08-19 13:14:296416 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276417
6418 TransportSecurityState* security_state =
6419 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406420 TransportSecurityState::STSState sts_state;
6421 TransportSecurityState::PKPState pkp_state;
6422 EXPECT_TRUE(
6423 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6424 EXPECT_TRUE(
6425 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6426 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6427 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036428#if defined(OS_ANDROID)
6429 // Android's CertVerifyProc does not (yet) handle pins.
6430#else
martijnc0d6b622015-06-30 19:14:406431 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036432#endif
martijnc0d6b622015-06-30 19:14:406433 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276434
martijnc0d6b622015-06-30 19:14:406435 EXPECT_TRUE(sts_state.include_subdomains);
6436 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276437}
6438
estark1614475f2016-03-10 03:46:476439// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6440// called.
6441class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6442 public:
6443 MockExpectCTReporter() : num_failures_(0) {}
6444 ~MockExpectCTReporter() override {}
6445
6446 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6447 const GURL& report_uri,
6448 const net::SSLInfo& ssl_info) override {
6449 num_failures_++;
6450 }
6451
6452 uint32_t num_failures() { return num_failures_; }
6453
6454 private:
6455 uint32_t num_failures_;
6456};
6457
estark1614475f2016-03-10 03:46:476458// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6459// for every certificate.
6460class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6461 public:
6462 MockCTPolicyEnforcer()
6463 : default_result_(
6464 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6465 ~MockCTPolicyEnforcer() override {}
6466
6467 ct::CertPolicyCompliance DoesConformToCertPolicy(
6468 X509Certificate* cert,
6469 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206470 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476471 return default_result_;
6472 }
6473
6474 void set_default_result(ct::CertPolicyCompliance default_result) {
6475 default_result_ = default_result;
6476 }
6477
6478 private:
6479 ct::CertPolicyCompliance default_result_;
6480};
6481
6482// Tests that Expect CT headers are processed correctly.
6483TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6484 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6485 https_test_server.SetSSLConfig(
6486 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6487 https_test_server.ServeFilesFromSourceDirectory(
6488 base::FilePath(kTestFilePath));
6489 ASSERT_TRUE(https_test_server.Start());
6490
6491 MockExpectCTReporter reporter;
6492 TransportSecurityState transport_security_state;
6493 transport_security_state.enable_static_expect_ct_ = true;
6494 transport_security_state.SetExpectCTReporter(&reporter);
6495
6496 // Set up a MockCertVerifier to accept the certificate that the server sends.
6497 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6498 ASSERT_TRUE(cert);
6499 MockCertVerifier cert_verifier;
6500 CertVerifyResult verify_result;
6501 verify_result.verified_cert = cert;
6502 verify_result.is_issued_by_known_root = true;
6503 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6504
rsleevi22cae1672016-12-28 01:53:366505 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6506 // CT violation.
6507 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476508 MockCTPolicyEnforcer ct_policy_enforcer;
6509 ct_policy_enforcer.set_default_result(
6510 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6511
6512 TestNetworkDelegate network_delegate;
6513 // Use a MockHostResolver (which by default maps all hosts to
6514 // 127.0.0.1) so that the request can be sent to a site on the Expect
6515 // CT preload list.
6516 MockHostResolver host_resolver;
6517 TestURLRequestContext context(true);
6518 context.set_host_resolver(&host_resolver);
6519 context.set_transport_security_state(&transport_security_state);
6520 context.set_network_delegate(&network_delegate);
6521 context.set_cert_verifier(&cert_verifier);
6522 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206523 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476524 context.Init();
6525
6526 // Now send a request to trigger the violation.
6527 TestDelegate d;
6528 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6529 GURL::Replacements replace_host;
6530 replace_host.SetHostStr(kExpectCTStaticHostname);
6531 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366532 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476533 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6534 violating_request->Start();
6535 base::RunLoop().Run();
6536
6537 EXPECT_EQ(1u, reporter.num_failures());
6538}
6539
tommycli59a63432015-11-06 00:10:556540#endif // !defined(OS_IOS)
6541
[email protected]316c1e5e2012-09-12 15:17:446542TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556543 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446544
6545 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366546 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556547 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366548 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196549 req->Start();
[email protected]255620da2013-08-19 13:14:296550 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446551
6552 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196553 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446554 EXPECT_EQ("text/html", mime_type);
6555
6556 std::string charset;
[email protected]f7022f32014-08-21 16:32:196557 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446558 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196559 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446560}
6561
[email protected]02494ec2014-05-07 15:05:296562TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346563 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346564 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346565 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026566 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346567
6568 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506569 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346570}
6571
brettwa1228ebb2016-10-28 03:51:346572#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:296573TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6574 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6575 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456576 FileProtocolHandler file_protocol_handler(
6577 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296578 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6579
6580 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506581 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296582}
6583
[email protected]588614c22013-08-16 00:09:026584TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556585 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446586
6587 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366588 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556589 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366590 &d));
[email protected]f7022f32014-08-21 16:32:196591 req->Start();
[email protected]255620da2013-08-19 13:14:296592 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446593
maksim.sisovb53724b52016-09-16 05:30:506594 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446595}
brettwa1228ebb2016-10-28 03:51:346596#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446597
[email protected]588614c22013-08-16 00:09:026598TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556599 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026600
6601 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366602 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556603 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366604 &d));
[email protected]f7022f32014-08-21 16:32:196605 req->Start();
fdoray5eeb7642016-06-22 16:11:286606 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026607
maksim.sisovb53724b52016-09-16 05:30:506608 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]588614c22013-08-16 00:09:026609}
6610
[email protected]316c1e5e2012-09-12 15:17:446611TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556612 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446613
6614 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366615 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556616 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366617 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196618 req->Start();
[email protected]255620da2013-08-19 13:14:296619 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446620
maksim.sisovb53724b52016-09-16 05:30:506621 EXPECT_EQ(ERR_INVALID_URL, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446622}
6623
[email protected]e50efea2014-03-24 18:41:006624// Make sure redirects are cached, despite not reading their bodies.
6625TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556626 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006627 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556628 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006629
6630 {
6631 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366632 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366633 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196634 req->Start();
[email protected]e50efea2014-03-24 18:41:006635 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506636 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006637 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556638 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006639 }
6640
6641 {
6642 TestDelegate d;
6643 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366644 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366645 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196646 req->Start();
[email protected]e50efea2014-03-24 18:41:006647 base::RunLoop().Run();
6648
6649 EXPECT_EQ(1, d.received_redirect_count());
6650 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196651 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006652
[email protected]f7022f32014-08-21 16:32:196653 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006654 base::RunLoop().Run();
6655 EXPECT_EQ(1, d.received_redirect_count());
6656 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:506657 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:556658 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006659 }
6660}
6661
6662// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6663// when the headers are read, since the body won't have been read.
6664TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556665 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006666 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556667 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006668
6669 {
6670 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556671 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006672 default_network_delegate_.set_redirect_on_headers_received_url(
6673 redirect_to_url);
6674
6675 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366676 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366677 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196678 req->Start();
[email protected]e50efea2014-03-24 18:41:006679 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506680 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006681 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196682 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006683 }
6684
6685 {
6686 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366687 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366688 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196689 req->Start();
[email protected]e50efea2014-03-24 18:41:006690 base::RunLoop().Run();
6691
maksim.sisovb53724b52016-09-16 05:30:506692 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196693 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006694 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196695 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006696 }
6697}
6698
[email protected]5f714132014-03-26 10:41:166699// Tests that redirection to an unsafe URL is allowed when it has been marked as
6700// safe.
6701TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556702 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166703
6704 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6705 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6706 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6707
6708 TestDelegate d;
6709 {
danakj8522a25b2016-04-16 00:17:366710 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556711 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166712
[email protected]f7022f32014-08-21 16:32:196713 r->Start();
[email protected]5f714132014-03-26 10:41:166714 base::RunLoop().Run();
6715
maksim.sisovb53724b52016-09-16 05:30:506716 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196717 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:196718 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166719 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6720 }
6721}
6722
6723// Tests that a redirect to a different unsafe URL is blocked, even after adding
6724// some other URL to the whitelist.
6725TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556726 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166727
6728 GURL unsafe_url("data:text/html,something");
6729 GURL different_unsafe_url("data:text/html,something-else");
6730 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6731 default_network_delegate_.set_allowed_unsafe_redirect_url(
6732 different_unsafe_url);
6733
6734 TestDelegate d;
6735 {
danakj8522a25b2016-04-16 00:17:366736 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556737 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166738
[email protected]f7022f32014-08-21 16:32:196739 r->Start();
[email protected]5f714132014-03-26 10:41:166740 base::RunLoop().Run();
6741
maksim.sisovb53724b52016-09-16 05:30:506742 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]5f714132014-03-26 10:41:166743 }
6744}
6745
[email protected]5f714132014-03-26 10:41:166746// Redirects from an URL with fragment to an unsafe URL with fragment should
6747// be allowed, and the reference fragment of the target URL should be preserved.
6748TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556749 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166750
tommycli59a63432015-11-06 00:10:556751 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166752 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6753 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6754
6755 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6756 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6757
6758 TestDelegate d;
6759 {
danakj8522a25b2016-04-16 00:17:366760 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366761 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166762
[email protected]f7022f32014-08-21 16:32:196763 r->Start();
[email protected]5f714132014-03-26 10:41:166764 base::RunLoop().Run();
6765
[email protected]f7022f32014-08-21 16:32:196766 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506767 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196768 EXPECT_EQ(original_url, r->original_url());
6769 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166770 }
6771}
6772
6773// When a delegate has specified a safe redirect URL, but it does not match the
6774// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146775TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556776 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166777
tommycli59a63432015-11-06 00:10:556778 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166779 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556780 GURL redirect_url(http_test_server()->GetURL("/target"));
6781 GURL expected_redirect_url(
6782 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166783
6784 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6785 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6786
6787 TestDelegate d;
6788 {
danakj8522a25b2016-04-16 00:17:366789 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366790 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166791
[email protected]f7022f32014-08-21 16:32:196792 r->Start();
[email protected]5f714132014-03-26 10:41:166793 base::RunLoop().Run();
6794
[email protected]f7022f32014-08-21 16:32:196795 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506796 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196797 EXPECT_EQ(original_url, r->original_url());
6798 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166799 }
6800}
6801
[email protected]f878230e2014-04-03 15:36:146802// When a delegate has specified a safe redirect URL, assume that the redirect
6803// URL should not be changed. In particular, the reference fragment should not
6804// be modified.
6805TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556806 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146807
tommycli59a63432015-11-06 00:10:556808 GURL original_url(
6809 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146810 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6811
6812 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6813 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6814
6815 TestDelegate d;
6816 {
danakj8522a25b2016-04-16 00:17:366817 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366818 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146819
[email protected]f7022f32014-08-21 16:32:196820 r->Start();
[email protected]f878230e2014-04-03 15:36:146821 base::RunLoop().Run();
6822
[email protected]f7022f32014-08-21 16:32:196823 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506824 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196825 EXPECT_EQ(original_url, r->original_url());
6826 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146827 }
6828}
6829
6830// When a URLRequestRedirectJob is created, the redirection must be followed and
6831// the reference fragment of the target URL must not be modified.
6832TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556833 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146834
tommycli59a63432015-11-06 00:10:556835 GURL original_url(
6836 http_test_server()->GetURL("/original#should-not-be-appended"));
6837 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146838
6839 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366840 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366841 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146842
danakj8522a25b2016-04-16 00:17:366843 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196844 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426845 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6846 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146847
[email protected]f7022f32014-08-21 16:32:196848 r->Start();
[email protected]f878230e2014-04-03 15:36:146849 base::RunLoop().Run();
6850
maksim.sisovb53724b52016-09-16 05:30:506851 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196852 EXPECT_EQ(original_url, r->original_url());
6853 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146854}
6855
lizeb5120f6dc2016-02-19 09:29:446856TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6857 ASSERT_TRUE(http_test_server()->Start());
6858
6859 const std::string referrer("foobar://totally.legit.referrer");
6860 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366861 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446862 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6863 req->SetReferrer(referrer);
6864 req->Start();
6865 base::RunLoop().Run();
6866
6867 EXPECT_EQ(std::string("None"), d.data_received());
6868}
6869
[email protected]316c1e5e2012-09-12 15:17:446870TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556871 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446872
6873 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366874 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556875 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196876 req->SetReferrer("http://user:[email protected]/");
6877 req->Start();
[email protected]255620da2013-08-19 13:14:296878 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446879
6880 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6881}
6882
[email protected]99ecf6e2013-04-10 22:46:136883TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556884 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136885
6886 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366887 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556888 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196889 req->SetReferrer("http://foo.com/test#fragment");
6890 req->Start();
[email protected]255620da2013-08-19 13:14:296891 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136892
6893 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6894}
6895
6896TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556897 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136898
6899 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366900 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556901 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196902 req->SetReferrer("http://foo.com/test#fragment");
6903 req->SetReferrer("");
6904 req->Start();
[email protected]255620da2013-08-19 13:14:296905 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136906
6907 EXPECT_EQ(std::string("None"), d.data_received());
6908}
6909
[email protected]316c1e5e2012-09-12 15:17:446910TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556911 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446912
6913 TestDelegate d;
6914 {
6915 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366916 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556917 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6918 &d));
[email protected]f7022f32014-08-21 16:32:196919 req->Start();
[email protected]255620da2013-08-19 13:14:296920 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446921
6922 EXPECT_EQ(1, d.response_started_count());
6923 EXPECT_EQ(0, d.bytes_received());
6924 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506925 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446926 }
6927}
6928
6929TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556930 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446931
6932 TestDelegate d;
6933 {
6934 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556935 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366936 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366937 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046938
[email protected]f7022f32014-08-21 16:32:196939 req->Start();
[email protected]255620da2013-08-19 13:14:296940 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446941
6942 EXPECT_EQ(1, d.received_redirect_count());
6943
[email protected]f7022f32014-08-21 16:32:196944 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296945 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446946
6947 EXPECT_EQ(1, d.response_started_count());
6948 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506949 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446950
[email protected]6cdfd7f2013-02-08 20:40:156951 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446952 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476953 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446954 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6955
6956 std::string contents;
[email protected]82f84b92013-08-30 18:23:506957 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446958 EXPECT_EQ(contents, d.data_received());
6959 }
6960}
6961
[email protected]79e1fd62013-06-20 06:50:046962TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556963 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046964
6965 TestDelegate d;
6966 {
6967 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556968 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366969 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366970 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046971
6972 EXPECT_FALSE(d.have_full_request_headers());
6973
[email protected]f7022f32014-08-21 16:32:196974 req->Start();
[email protected]255620da2013-08-19 13:14:296975 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046976
6977 EXPECT_EQ(1, d.received_redirect_count());
6978 EXPECT_TRUE(d.have_full_request_headers());
6979 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6980 d.ClearFullRequestHeaders();
6981
[email protected]f7022f32014-08-21 16:32:196982 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296983 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046984
tommycli59a63432015-11-06 00:10:556985 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046986 EXPECT_EQ(1, d.response_started_count());
6987 EXPECT_TRUE(d.have_full_request_headers());
6988 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6989 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506990 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:046991
6992 base::FilePath path;
6993 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476994 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046995 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6996
6997 std::string contents;
[email protected]82f84b92013-08-30 18:23:506998 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046999 EXPECT_EQ(contents, d.data_received());
7000 }
7001}
7002
[email protected]316c1e5e2012-09-12 15:17:447003TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557004 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447005
7006 TestDelegate d;
7007 {
7008 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:367009 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557010 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
7011 &d));
[email protected]f7022f32014-08-21 16:32:197012 req->Start();
[email protected]255620da2013-08-19 13:14:297013 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447014
7015 EXPECT_EQ(1, d.received_redirect_count());
7016
[email protected]f7022f32014-08-21 16:32:197017 req->Cancel();
[email protected]255620da2013-08-19 13:14:297018 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447019
7020 EXPECT_EQ(1, d.response_started_count());
7021 EXPECT_EQ(0, d.bytes_received());
7022 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507023 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447024 }
7025}
7026
7027TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557028 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447029
[email protected]3b23a222013-05-15 21:33:257030 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447031 {
7032 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367033 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557034 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7035 &d));
[email protected]316c1e5e2012-09-12 15:17:447036 HttpRequestHeaders headers;
7037 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197038 req->SetExtraRequestHeaders(headers);
7039 req->Start();
[email protected]255620da2013-08-19 13:14:297040 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257041
7042 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197043 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257044 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447045 }
7046
[email protected]3b23a222013-05-15 21:33:257047 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447048 {
7049 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367050 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557051 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7052 &d));
[email protected]316c1e5e2012-09-12 15:17:447053 HttpRequestHeaders headers;
7054 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197055 req->SetExtraRequestHeaders(headers);
7056 req->Start();
[email protected]255620da2013-08-19 13:14:297057 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447058
[email protected]f7022f32014-08-21 16:32:197059 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257060
7061 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197062 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257063 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447064 }
7065
[email protected]3b23a222013-05-15 21:33:257066 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447067 {
7068 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367069 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557070 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7071 &d));
[email protected]316c1e5e2012-09-12 15:17:447072 HttpRequestHeaders headers;
7073 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197074 req->SetExtraRequestHeaders(headers);
7075 req->Start();
[email protected]255620da2013-08-19 13:14:297076 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447077
[email protected]f7022f32014-08-21 16:32:197078 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257079
7080 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197081 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257082 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447083 }
7084}
7085
7086TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557087 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447088
7089 // populate the cache
7090 {
7091 TestDelegate d;
7092 d.set_credentials(AuthCredentials(kUser, kSecret));
7093
danakj8522a25b2016-04-16 00:17:367094 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557095 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197096 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447097
[email protected]255620da2013-08-19 13:14:297098 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447099
7100 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7101 }
7102
7103 // repeat request with end-to-end validation. since auth-basic results in a
7104 // cachable page, we expect this test to result in a 304. in which case, the
7105 // response should be fetched from the cache.
7106 {
7107 TestDelegate d;
7108 d.set_credentials(AuthCredentials(kUser, kSecret));
7109
danakj8522a25b2016-04-16 00:17:367110 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557111 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197112 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7113 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447114
[email protected]255620da2013-08-19 13:14:297115 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447116
7117 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7118
7119 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197120 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447121 }
7122}
7123
7124// Check that Set-Cookie headers in 401 responses are respected.
7125// http://crbug.com/6450
7126TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557127 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447128
7129 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557130 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447131
7132 // Request a page that will give a 401 containing a Set-Cookie header.
7133 // Verify that when the transaction is restarted, it includes the new cookie.
7134 {
[email protected]ceefd7fd2012-11-29 00:36:247135 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447136 TestURLRequestContext context(true);
7137 context.set_network_delegate(&network_delegate);
7138 context.Init();
7139
7140 TestDelegate d;
7141 d.set_credentials(AuthCredentials(kUser, kSecret));
7142
danakj8522a25b2016-04-16 00:17:367143 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367144 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197145 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447146
[email protected]255620da2013-08-19 13:14:297147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447148
7149 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7150
7151 // Make sure we sent the cookie in the restarted transaction.
7152 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7153 != std::string::npos);
7154 }
7155
7156 // Same test as above, except this time the restart is initiated earlier
7157 // (without user intervention since identity is embedded in the URL).
7158 {
[email protected]ceefd7fd2012-11-29 00:36:247159 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447160 TestURLRequestContext context(true);
7161 context.set_network_delegate(&network_delegate);
7162 context.Init();
7163
7164 TestDelegate d;
7165
7166 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187167 replacements.SetUsernameStr("user2");
7168 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447169 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7170
danakj8522a25b2016-04-16 00:17:367171 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367172 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197173 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447174
[email protected]255620da2013-08-19 13:14:297175 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447176
7177 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7178
7179 // Make sure we sent the cookie in the restarted transaction.
7180 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7181 != std::string::npos);
7182 }
7183}
7184
[email protected]58e32bb2013-01-21 18:23:257185// Tests that load timing works as expected with auth and the cache.
7186TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557187 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257188
7189 // populate the cache
7190 {
7191 TestDelegate d;
7192 d.set_credentials(AuthCredentials(kUser, kSecret));
7193
danakj8522a25b2016-04-16 00:17:367194 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557195 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197196 r->Start();
[email protected]58e32bb2013-01-21 18:23:257197
[email protected]255620da2013-08-19 13:14:297198 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257199
7200 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7201
7202 LoadTimingInfo load_timing_info_before_auth;
7203 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7204 &load_timing_info_before_auth));
7205 TestLoadTimingNotReused(load_timing_info_before_auth,
7206 CONNECT_TIMING_HAS_DNS_TIMES);
7207
7208 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197209 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257210 // The test server does not support keep alive sockets, so the second
7211 // request with auth should use a new socket.
7212 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7213 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7214 load_timing_info.socket_log_id);
7215 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7216 load_timing_info.connect_timing.connect_start);
7217 }
7218
[email protected]3b23a222013-05-15 21:33:257219 // Repeat request with end-to-end validation. Since auth-basic results in a
7220 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257221 // response should be fetched from the cache.
7222 {
7223 TestDelegate d;
7224 d.set_credentials(AuthCredentials(kUser, kSecret));
7225
danakj8522a25b2016-04-16 00:17:367226 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557227 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197228 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7229 r->Start();
[email protected]58e32bb2013-01-21 18:23:257230
[email protected]255620da2013-08-19 13:14:297231 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257232
7233 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7234
7235 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197236 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257237
[email protected]3b23a222013-05-15 21:33:257238 // Since there was a request that went over the wire, the load timing
7239 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257240 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197241 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257242 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257243 }
7244}
7245
[email protected]316c1e5e2012-09-12 15:17:447246// In this test, we do a POST which the server will 302 redirect.
7247// The subsequent transaction should use GET, and should not send the
7248// Content-Type header.
7249// http://code.google.com/p/chromium/issues/detail?id=843
7250TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557251 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447252
7253 const char kData[] = "hello world";
7254
7255 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367256 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557257 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7258 &d));
[email protected]f7022f32014-08-21 16:32:197259 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077260 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447261
7262 // Set headers (some of which are specific to the POST).
7263 HttpRequestHeaders headers;
7264 headers.AddHeadersFromString(
7265 "Content-Type: multipart/form-data; "
7266 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7267 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7268 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7269 "Accept-Language: en-US,en\r\n"
7270 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7271 "Content-Length: 11\r\n"
7272 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197273 req->SetExtraRequestHeaders(headers);
7274 req->Start();
[email protected]255620da2013-08-19 13:14:297275 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447276
7277 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197278 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447279 EXPECT_EQ("text/html", mime_type);
7280
7281 const std::string& data = d.data_received();
7282
7283 // Check that the post-specific headers were stripped:
7284 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7285 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7286 EXPECT_FALSE(ContainsString(data, "Origin:"));
7287
7288 // These extra request headers should not have been stripped.
7289 EXPECT_TRUE(ContainsString(data, "Accept:"));
7290 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7291 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7292}
7293
jww5fe460ff2015-03-28 00:22:517294// The following tests check that we handle mutating the request for HTTP
7295// redirects as expected.
7296// See https://crbug.com/56373, https://crbug.com/102130, and
7297// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447298
7299TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557300 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447301
tommycli59a63432015-11-06 00:10:557302 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517303 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557304 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447305
7306 HTTPRedirectMethodTest(url, "POST", "GET", true);
7307 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7308 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517309
7310 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7311 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7312 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7313 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7314 std::string());
[email protected]316c1e5e2012-09-12 15:17:447315}
7316
7317TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557318 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447319
tommycli59a63432015-11-06 00:10:557320 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517321 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557322 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447323
7324 HTTPRedirectMethodTest(url, "POST", "GET", true);
7325 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7326 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517327
7328 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7329 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7330 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7331 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7332 std::string());
[email protected]316c1e5e2012-09-12 15:17:447333}
7334
7335TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557336 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447337
tommycli59a63432015-11-06 00:10:557338 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517339 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557340 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447341
7342 HTTPRedirectMethodTest(url, "POST", "GET", true);
7343 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7344 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517345
7346 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7347 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7348 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7349 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7350 std::string());
[email protected]316c1e5e2012-09-12 15:17:447351}
7352
7353TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557354 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447355
tommycli59a63432015-11-06 00:10:557356 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517357 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557358 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447359
7360 HTTPRedirectMethodTest(url, "POST", "POST", true);
7361 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7362 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517363
7364 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7365 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7366 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7367 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447368}
7369
[email protected]0a17aab32014-04-24 03:32:377370TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557371 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377372
tommycli59a63432015-11-06 00:10:557373 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517374 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557375 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377376
7377 HTTPRedirectMethodTest(url, "POST", "POST", true);
7378 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7379 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517380
7381 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7382 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7383 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7384 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377385}
7386
7387// Make sure that 308 responses without bodies are not treated as redirects.
7388// Certain legacy apis that pre-date the response code expect this behavior
7389// (Like Google Drive).
7390TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557391 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377392
7393 TestDelegate d;
tommycli59a63432015-11-06 00:10:557394 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377395
danakj8522a25b2016-04-16 00:17:367396 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367397 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377398
[email protected]f7022f32014-08-21 16:32:197399 request->Start();
[email protected]0a17aab32014-04-24 03:32:377400 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507401 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:377402 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197403 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377404 EXPECT_EQ("This is not a redirect.", d.data_received());
7405}
7406
[email protected]f878230e2014-04-03 15:36:147407TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557408 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147409
tommycli59a63432015-11-06 00:10:557410 GURL original_url(
7411 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7412 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147413
7414 TestDelegate d;
7415 {
danakj8522a25b2016-04-16 00:17:367416 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367417 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147418
[email protected]f7022f32014-08-21 16:32:197419 r->Start();
[email protected]f878230e2014-04-03 15:36:147420 base::RunLoop().Run();
7421
[email protected]f7022f32014-08-21 16:32:197422 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507423 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197424 EXPECT_EQ(original_url, r->original_url());
7425 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147426 }
7427}
7428
[email protected]cba24642014-08-15 20:49:597429TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557430 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597431
tommycli59a63432015-11-06 00:10:557432 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597433 GURL first_party_url("http://example.com");
7434
7435 TestDelegate d;
7436 {
danakj8522a25b2016-04-16 00:17:367437 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367438 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197439 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597440
[email protected]f7022f32014-08-21 16:32:197441 r->Start();
[email protected]cba24642014-08-15 20:49:597442 base::RunLoop().Run();
7443
[email protected]f7022f32014-08-21 16:32:197444 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507445 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197446 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597447 }
7448}
7449
7450TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557451 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597452
tommycli59a63432015-11-06 00:10:557453 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597454 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557455 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597456
7457 TestDelegate d;
7458 {
danakj8522a25b2016-04-16 00:17:367459 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367460 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197461 r->set_first_party_for_cookies(original_first_party_url);
7462 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597463 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7464
[email protected]f7022f32014-08-21 16:32:197465 r->Start();
[email protected]cba24642014-08-15 20:49:597466 base::RunLoop().Run();
7467
[email protected]f7022f32014-08-21 16:32:197468 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507469 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197470 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597471 }
7472}
7473
[email protected]316c1e5e2012-09-12 15:17:447474TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557475 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447476
7477 const char kData[] = "hello world";
7478
7479 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367480 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557481 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197482 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077483 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447484 HttpRequestHeaders headers;
7485 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517486 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197487 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447488
danakj8522a25b2016-04-16 00:17:367489 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557490 req.get(), &default_network_delegate_,
7491 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427492 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7493 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447494
[email protected]f7022f32014-08-21 16:32:197495 req->Start();
[email protected]255620da2013-08-19 13:14:297496 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197497 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447498}
7499
7500TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557501 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447502
7503 const char kData[] = "hello world";
7504
7505 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367506 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557507 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197508 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077509 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447510 HttpRequestHeaders headers;
7511 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517512 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197513 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447514
danakj8522a25b2016-04-16 00:17:367515 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557516 req.get(), &default_network_delegate_,
7517 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097518 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427519 "Very Good Reason"));
7520 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447521
[email protected]f7022f32014-08-21 16:32:197522 req->Start();
[email protected]255620da2013-08-19 13:14:297523 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197524 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447525 EXPECT_EQ(kData, d.data_received());
7526}
7527
7528// Check that default A-L header is sent.
7529TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557530 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447531
[email protected]8790210c2013-12-02 05:29:537532 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247533 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447534 TestURLRequestContext context(true);
7535 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437536 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447537 context.Init();
7538
7539 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367540 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557541 http_test_server()->GetURL("/echoheader?Accept-Language"),
7542 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197543 req->Start();
[email protected]255620da2013-08-19 13:14:297544 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447545 EXPECT_EQ("en", d.data_received());
7546}
7547
7548// Check that an empty A-L header is not sent. http://crbug.com/77365.
7549TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557550 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447551
[email protected]8790210c2013-12-02 05:29:537552 std::string empty_string; // Avoid most vexing parse on line below.
7553 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247554 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447555 TestURLRequestContext context(true);
7556 context.set_network_delegate(&network_delegate);
7557 context.Init();
7558 // We override the language after initialization because empty entries
7559 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437560 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447561
7562 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367563 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557564 http_test_server()->GetURL("/echoheader?Accept-Language"),
7565 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197566 req->Start();
[email protected]255620da2013-08-19 13:14:297567 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447568 EXPECT_EQ("None", d.data_received());
7569}
7570
7571// Check that if request overrides the A-L header, the default is not appended.
7572// See http://crbug.com/20894
7573TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557574 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447575
7576 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367577 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557578 http_test_server()->GetURL("/echoheader?Accept-Language"),
7579 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447580 HttpRequestHeaders headers;
7581 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197582 req->SetExtraRequestHeaders(headers);
7583 req->Start();
[email protected]255620da2013-08-19 13:14:297584 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447585 EXPECT_EQ(std::string("ru"), d.data_received());
7586}
7587
7588// Check that default A-E header is sent.
7589TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557590 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447591
7592 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367593 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557594 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7595 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447596 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197597 req->SetExtraRequestHeaders(headers);
7598 req->Start();
[email protected]255620da2013-08-19 13:14:297599 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447600 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7601}
7602
7603// Check that if request overrides the A-E header, the default is not appended.
7604// See http://crbug.com/47381
7605TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557606 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447607
7608 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367609 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557610 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7611 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447612 HttpRequestHeaders headers;
7613 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197614 req->SetExtraRequestHeaders(headers);
7615 req->Start();
[email protected]255620da2013-08-19 13:14:297616 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447617 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7618 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7619}
7620
[email protected]84f05432013-03-15 01:00:127621// Check that setting the A-C header sends the proper header.
7622TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557623 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447624
7625 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367626 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557627 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7628 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447629 HttpRequestHeaders headers;
7630 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197631 req->SetExtraRequestHeaders(headers);
7632 req->Start();
[email protected]255620da2013-08-19 13:14:297633 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447634 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7635}
7636
7637// Check that default User-Agent header is sent.
7638TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557639 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447640
7641 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367642 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557643 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7644 &d));
[email protected]f7022f32014-08-21 16:32:197645 req->Start();
[email protected]255620da2013-08-19 13:14:297646 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197647 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377648 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447649}
7650
7651// Check that if request overrides the User-Agent header,
7652// the default is not appended.
marqf14fff8d2015-12-02 15:52:297653// TODO(crbug.com/564656) This test is flaky on iOS.
7654#if defined(OS_IOS)
7655#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7656#else
7657#define MAYBE_OverrideUserAgent OverrideUserAgent
7658#endif
7659TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557660 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447661
7662 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367663 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557664 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7665 &d));
[email protected]316c1e5e2012-09-12 15:17:447666 HttpRequestHeaders headers;
7667 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197668 req->SetExtraRequestHeaders(headers);
7669 req->Start();
[email protected]255620da2013-08-19 13:14:297670 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357671 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447672}
7673
[email protected]ee4c30d2012-11-07 15:08:437674// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7675// User-Agent header to be sent but does not send the Accept-Language and
7676// Accept-Charset headers.
7677TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557678 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437679
[email protected]ceefd7fd2012-11-29 00:36:247680 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437681 TestURLRequestContext context(true);
7682 context.set_network_delegate(&network_delegate);
7683 context.Init();
7684 // We override the HttpUserAgentSettings after initialization because empty
7685 // entries get overridden by Init().
7686 context.set_http_user_agent_settings(NULL);
7687
7688 struct {
7689 const char* request;
7690 const char* expected_response;
tommycli59a63432015-11-06 00:10:557691 } tests[] = {{"/echoheader?Accept-Language", "None"},
7692 {"/echoheader?Accept-Charset", "None"},
7693 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437694
viettrungluue4a8b882014-10-16 06:17:387695 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437696 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367697 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557698 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197699 req->Start();
[email protected]255620da2013-08-19 13:14:297700 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437701 EXPECT_EQ(tests[i].expected_response, d.data_received())
7702 << " Request = \"" << tests[i].request << "\"";
7703 }
7704}
7705
[email protected]5033ab82013-03-22 20:17:467706// Make sure that URLRequest passes on its priority updates to
7707// newly-created jobs after the first one.
7708TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557709 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467710
7711 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367712 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557713 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197714 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467715
danakj8522a25b2016-04-16 00:17:367716 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557717 req.get(), &default_network_delegate_,
7718 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427719 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7720 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467721
[email protected]f7022f32014-08-21 16:32:197722 req->SetPriority(LOW);
7723 req->Start();
7724 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467725
mmenkeed0498b2015-12-08 23:20:427726 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367727 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427728 req.get(), &default_network_delegate_, &job_priority));
7729 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467730
7731 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297732 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427733 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467734}
7735
zhongyi18ddddd2017-02-03 19:06:367736TEST_F(URLRequestTest, QuicServerInfoFactoryTest) {
7737 HttpNetworkSession::Params params;
7738
7739 MockClientSocketFactory socket_factory;
7740 MockCryptoClientStreamFactory crypto_client_stream_factory;
7741 MockHostResolver host_resolver;
7742 MockCertVerifier cert_verifier;
7743 CTPolicyEnforcer ct_policy_enforcer;
7744 TransportSecurityState transport_security_state;
7745 std::unique_ptr<CTVerifier> cert_transparency_verifier(
7746 new MultiLogCTVerifier());
7747 std::unique_ptr<ProxyService> proxy_service = ProxyService::CreateDirect();
7748 scoped_refptr<SSLConfigServiceDefaults> ssl_config_service(
7749 new SSLConfigServiceDefaults);
7750 HttpServerPropertiesImpl http_server_properties;
7751 // Set up the quic stream factory.
7752 params.enable_quic = true;
7753 params.client_socket_factory = &socket_factory;
7754 params.quic_crypto_client_stream_factory = &crypto_client_stream_factory;
7755 params.host_resolver = &host_resolver;
7756 params.cert_verifier = &cert_verifier;
7757 params.ct_policy_enforcer = &ct_policy_enforcer;
7758 params.transport_security_state = &transport_security_state;
7759 params.cert_transparency_verifier = cert_transparency_verifier.get();
7760
7761 params.proxy_service = proxy_service.get();
7762 params.ssl_config_service = ssl_config_service.get();
7763 params.http_server_properties = &http_server_properties;
7764
7765 HttpNetworkSession session(params);
7766 DCHECK(session.quic_stream_factory());
7767
7768 std::unique_ptr<HttpNetworkLayer> network_layer1(
7769 new HttpNetworkLayer(&session));
7770
7771 HttpCache main_cache(std::move(network_layer1),
7772 HttpCache::DefaultBackend::InMemory(0), true);
7773
7774 EXPECT_TRUE(session.quic_stream_factory()->has_quic_server_info_factory());
7775
7776 default_context_.set_http_transaction_factory(&main_cache);
7777
7778 QuicServerInfoFactory* quic_server_info_factory =
7779 session.quic_stream_factory()->quic_server_info_factory();
7780 DCHECK(quic_server_info_factory);
7781
7782 QuicServerId server_id("www.google.com", 443, PRIVACY_MODE_DISABLED);
7783 const string server_config_a = "server_config_a";
7784 const string source_address_token_a = "source_address_token_a";
7785 const string cert_sct_a = "cert_sct_a";
7786 const string chlo_hash_a = "chlo_hash_a";
7787 const string server_config_sig_a = "server_config_sig_a";
7788 const string cert_a = "cert_a";
7789 const string cert_b = "cert_b";
7790
7791 {
7792 // Store a QuicServerInfo to the quic server info factory.
7793 TestCompletionCallback cb;
7794 std::unique_ptr<QuicServerInfo> quic_server_info =
7795 quic_server_info_factory->GetForServer(server_id);
7796 quic_server_info->Start();
7797 int rv = quic_server_info->WaitForDataReady(cb.callback());
7798 EXPECT_THAT(cb.GetResult(rv), IsOk());
7799
7800 QuicServerInfo::State* state = quic_server_info->mutable_state();
7801 EXPECT_TRUE(state->certs.empty());
7802
7803 state->server_config = server_config_a;
7804 state->source_address_token = source_address_token_a;
7805 state->cert_sct = cert_sct_a;
7806 state->chlo_hash = chlo_hash_a;
7807 state->server_config_sig = server_config_sig_a;
7808 state->certs.push_back(cert_a);
7809 quic_server_info->Persist();
7810 base::RunLoop().RunUntilIdle();
7811 }
7812
7813 // Retrieve the QuicServerInfo from the quic server info factory and verify
7814 // the data is correct.
7815 {
7816 TestCompletionCallback cb;
7817 std::unique_ptr<QuicServerInfo> quic_server_info =
7818 quic_server_info_factory->GetForServer(server_id);
7819 quic_server_info->Start();
7820 int rv = quic_server_info->WaitForDataReady(cb.callback());
7821 EXPECT_THAT(cb.GetResult(rv), IsOk());
7822
7823 QuicServerInfo::State* state = quic_server_info->mutable_state();
7824 EXPECT_TRUE(quic_server_info->IsDataReady());
7825 EXPECT_EQ(server_config_a, state->server_config);
7826 EXPECT_EQ(source_address_token_a, state->source_address_token);
7827 EXPECT_EQ(cert_sct_a, state->cert_sct);
7828 EXPECT_EQ(chlo_hash_a, state->chlo_hash);
7829 EXPECT_EQ(server_config_sig_a, state->server_config_sig);
7830 EXPECT_EQ(1U, state->certs.size());
7831 EXPECT_EQ(cert_a, state->certs[0]);
7832
7833 // Update the data.
7834 state->certs.push_back(cert_b);
7835 quic_server_info->Persist();
7836 base::RunLoop().RunUntilIdle();
7837 }
7838
7839 {
7840 // Verify data has been successfully updated.
7841 TestCompletionCallback cb;
7842 std::unique_ptr<QuicServerInfo> quic_server_info =
7843 quic_server_info_factory->GetForServer(server_id);
7844 quic_server_info->Start();
7845 int rv = quic_server_info->WaitForDataReady(cb.callback());
7846 EXPECT_THAT(cb.GetResult(rv), IsOk());
7847
7848 QuicServerInfo::State* state = quic_server_info->mutable_state();
7849 EXPECT_TRUE(quic_server_info->IsDataReady());
7850 EXPECT_EQ(2U, state->certs.size());
7851 EXPECT_EQ(cert_a, state->certs[0]);
7852 EXPECT_EQ(cert_b, state->certs[1]);
7853 }
7854}
7855
[email protected]80abdad2014-03-15 00:20:547856// Check that creating a network request while entering/exiting suspend mode
7857// fails as it should. This is the only case where an HttpTransactionFactory
7858// does not return an HttpTransaction.
7859TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7860 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367861 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177862 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547863 network_layer->OnSuspend();
7864
dchengc7eeda422015-12-26 03:56:487865 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427866 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547867
7868 TestURLRequestContext context(true);
7869 context.set_http_transaction_factory(&http_cache);
7870 context.Init();
7871
7872 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367873 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367874 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197875 req->Start();
[email protected]80abdad2014-03-15 00:20:547876 base::RunLoop().Run();
7877
7878 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:507879 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:547880}
7881
mmenke2281f3762015-11-02 20:38:177882namespace {
[email protected]80abdad2014-03-15 00:20:547883
mmenke2281f3762015-11-02 20:38:177884// HttpTransactionFactory that synchronously fails to create transactions.
7885class FailingHttpTransactionFactory : public HttpTransactionFactory {
7886 public:
7887 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7888 : network_session_(network_session) {}
7889
7890 ~FailingHttpTransactionFactory() override {}
7891
7892 // HttpTransactionFactory methods:
7893 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367894 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177895 return ERR_FAILED;
7896 }
7897
7898 HttpCache* GetCache() override { return nullptr; }
7899
7900 HttpNetworkSession* GetSession() override { return network_session_; }
7901
7902 private:
7903 HttpNetworkSession* network_session_;
7904
7905 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7906};
7907
7908} // namespace
7909
7910// Check that when a request that fails to create an HttpTransaction can be
7911// cancelled while the failure notification is pending, and doesn't send two
7912// failure notifications.
7913//
7914// This currently only happens when in suspend mode and there's no cache, but
7915// just use a special HttpTransactionFactory, to avoid depending on those
7916// behaviors.
7917TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7918 FailingHttpTransactionFactory http_transaction_factory(
7919 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547920 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177921 context.set_http_transaction_factory(&http_transaction_factory);
7922 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547923 context.Init();
7924
7925 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367926 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367927 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177928 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7929 // try to create an HttpNetworkTransaction synchronously on start).
7930 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197931 req->Start();
mmenke2281f3762015-11-02 20:38:177932 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547933 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177934 // Run pending error task, if there is one.
7935 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547936
7937 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177938 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507939 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:177940
7941 // NetworkDelegate should see the cancellation, but not the error.
7942 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7943 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547944}
7945
ttuttlec0c828492015-05-15 01:25:557946TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557947 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557948
7949 TestDelegate d;
tommycli59a63432015-11-06 00:10:557950 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367951 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557952 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7953
7954 req->Start();
7955 base::RunLoop().Run();
7956
7957 EXPECT_TRUE(req->response_info().network_accessed);
7958}
7959
7960TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557961 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557962
7963 // Populate the cache.
7964 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367965 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557966 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557967 req->Start();
7968 base::RunLoop().Run();
7969
maksim.sisovb53724b52016-09-16 05:30:507970 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557971 EXPECT_TRUE(req->response_info().network_accessed);
7972 EXPECT_FALSE(req->response_info().was_cached);
7973
tommycli59a63432015-11-06 00:10:557974 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557975 DEFAULT_PRIORITY, &d);
7976 req->Start();
7977 base::RunLoop().Run();
7978
maksim.sisovb53724b52016-09-16 05:30:507979 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557980 EXPECT_FALSE(req->response_info().network_accessed);
7981 EXPECT_TRUE(req->response_info().was_cached);
7982}
7983
7984TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557985 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557986
7987 TestDelegate d;
tommycli59a63432015-11-06 00:10:557988 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367989 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557990 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
jkarlina067deed2016-10-27 14:48:337991 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:557992
7993 req->Start();
7994 base::RunLoop().Run();
7995
7996 EXPECT_FALSE(req->response_info().network_accessed);
7997}
7998
rdsmithbf8c3c12016-11-18 18:16:247999// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:088000// correctly in the absence of contention.
8001TEST_F(URLRequestTestHTTP, ThrottledPriority) {
8002 ASSERT_TRUE(http_test_server()->Start());
8003
8004 TestDelegate d;
8005 GURL test_url(http_test_server()->GetURL("/"));
8006 std::unique_ptr<URLRequest> req(
8007 default_context_.CreateRequest(test_url, THROTTLED, &d));
8008 req->Start();
8009 base::RunLoop().Run();
8010
8011 EXPECT_TRUE(req->status().is_success());
8012}
8013
rdsmithbf8c3c12016-11-18 18:16:248014// A class to hold state for responding to USER_NOTIFY callbacks from
8015// BlockingNetworkDelegate. It also accepts a RunLoop that will be
8016// signaled via QuitWhenIdle() when any request is blocked.
8017//
8018class NotificationCallbackHandler {
8019 public:
8020 // Default constructed object doesn't block anything.
8021 NotificationCallbackHandler() : run_loop_(nullptr) {}
8022
8023 void AddURLRequestToBlockList(const URLRequest* request) {
8024 requests_to_block_.insert(request);
8025 }
8026
8027 Error ShouldBlockRequest(const CompletionCallback& callback,
8028 const URLRequest* request) {
8029 if (requests_to_block_.find(request) == requests_to_block_.end()) {
8030 return OK;
8031 }
8032
8033 DCHECK(blocked_callbacks_.find(request) == blocked_callbacks_.end());
8034 blocked_callbacks_[request] = callback;
8035 if (run_loop_ && blocked_callbacks_.size() == requests_to_block_.size())
8036 run_loop_->QuitWhenIdle();
8037 return ERR_IO_PENDING;
8038 }
8039
8040 // Erases object's memory of blocked callbacks as a side effect.
8041 void GetBlockedCallbacks(
8042 std::map<const URLRequest*, CompletionCallback>* blocked_callbacks) {
8043 blocked_callbacks_.swap(*blocked_callbacks);
8044 }
8045
8046 // Set a RunLoop that, if non-null, will be signaled if any request
8047 // is blocked. It is the callers responsibility to make sure the
8048 // passed object lives past the destruction of this class or
8049 // next call to SetRunLoop().
8050 void SetRunLoop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
8051
8052 private:
8053 std::set<const URLRequest*> requests_to_block_;
8054 std::map<const URLRequest*, CompletionCallback> blocked_callbacks_;
8055
8056 base::RunLoop* run_loop_;
8057
8058 DISALLOW_COPY_AND_ASSIGN(NotificationCallbackHandler);
8059};
8060
8061TEST_F(URLRequestTestHTTP, MultiThrottledPriority) {
8062 ASSERT_TRUE(http_test_server()->Start());
8063
8064 base::RunLoop run_until_request_blocked;
8065
8066 NotificationCallbackHandler notification_handler;
8067 notification_handler.SetRunLoop(&run_until_request_blocked);
8068 BlockingNetworkDelegate network_delegate(
8069 BlockingNetworkDelegate::USER_NOTIFY);
8070 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8071 network_delegate.set_notification_callback(
8072 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8073 // Both objects are owned by this function, and
8074 // |*network_delegate| will be destroyed first, so
8075 // it's safe to pass it an unretained pointer.
8076 base::Unretained(&notification_handler)));
8077
8078 TestURLRequestContext context(true);
8079 context.set_network_delegate(&network_delegate);
8080 context.Init();
8081
8082 // Use different test URLs to make sure all three requests turn into
8083 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8084 // the requests may be waited on separately.
8085 TestDelegate d1;
8086 std::unique_ptr<URLRequest> req1(context.CreateRequest(
8087 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
8088 notification_handler.AddURLRequestToBlockList(req1.get());
8089
8090 TestDelegate d2;
8091 std::unique_ptr<URLRequest> req2(context.CreateRequest(
8092 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
8093 notification_handler.AddURLRequestToBlockList(req2.get());
8094
8095 TestDelegate d3;
8096 std::unique_ptr<URLRequest> req3(context.CreateRequest(
8097 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
8098 req1->Start();
8099 req2->Start();
8100 req3->Start();
8101 run_until_request_blocked.Run();
8102 notification_handler.SetRunLoop(nullptr);
8103
8104 // The first two requests should be blocked based on the notification
8105 // callback, and their status should have blocked the third request
8106 // through throttling.
8107 EXPECT_TRUE(req1->status().is_io_pending());
8108 EXPECT_TRUE(req2->status().is_io_pending());
8109 EXPECT_TRUE(req3->status().is_io_pending());
8110
8111 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8112 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8113 ASSERT_EQ(2u, blocked_callbacks.size());
8114 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8115 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8116
8117 // Unblocking one of the requests blocked on the notification callback
8118 // should let it complete, which should then let the third request
8119 // complete. Unblock the second request, then wait for the third
8120 // request to complete.
8121 // TODO(rdsmith): Find something to wait on other than the third
8122 // requests completion; if there's a bug in throttling, that will
8123 // result in this test hanging rather than failing quickly.
8124 d1.set_quit_on_complete(false);
8125 d2.set_quit_on_complete(false);
8126 d3.set_quit_on_complete(true);
8127 blocked_callbacks[req2.get()].Run(OK);
8128 base::RunLoop().Run();
8129
8130 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8131 EXPECT_EQ(0u, blocked_callbacks.size());
8132 EXPECT_TRUE(req1->status().is_io_pending());
8133 // req3 is only unblocked after req2 completes, so req2's
8134 // success is guaranteed at this point in the function.
8135 EXPECT_EQ(URLRequestStatus::SUCCESS, req2->status().status());
8136 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8137}
8138
8139// Confirm that failing a request unblocks following requests.
8140TEST_F(URLRequestTestHTTP, ThrottledFailure) {
8141 ASSERT_TRUE(http_test_server()->Start());
8142
8143 base::RunLoop run_until_request_blocked;
8144
8145 NotificationCallbackHandler notification_handler;
8146 notification_handler.SetRunLoop(&run_until_request_blocked);
8147 BlockingNetworkDelegate network_delegate(
8148 BlockingNetworkDelegate::USER_NOTIFY);
8149 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8150 network_delegate.set_notification_callback(
8151 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8152 // Both objects are owned by this function, and
8153 // |*network_delegate| will be destroyed first, so
8154 // it's safe to pass it an unretained pointer.
8155 base::Unretained(&notification_handler)));
8156
8157 TestURLRequestContext context(true);
8158 context.set_network_delegate(&network_delegate);
8159 context.Init();
8160
8161 // Use different test URLs to make sure all three requests turn into
8162 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8163 // the requests may be waited on separately.
8164 TestDelegate d1;
8165 std::unique_ptr<URLRequest> req1(context.CreateRequest(
8166 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
8167 notification_handler.AddURLRequestToBlockList(req1.get());
8168
8169 TestDelegate d2;
8170 std::unique_ptr<URLRequest> req2(context.CreateRequest(
8171 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
8172 notification_handler.AddURLRequestToBlockList(req2.get());
8173
8174 TestDelegate d3;
8175 std::unique_ptr<URLRequest> req3(context.CreateRequest(
8176 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
8177 req1->Start();
8178 req2->Start();
8179 req3->Start();
8180 run_until_request_blocked.Run();
8181 notification_handler.SetRunLoop(nullptr);
8182
8183 // The first two requests should be blocked based on the notification
8184 // callback, and their status should have blocked the third request
8185 // through throttling.
8186 EXPECT_TRUE(req1->status().is_io_pending());
8187 EXPECT_TRUE(req2->status().is_io_pending());
8188 EXPECT_TRUE(req3->status().is_io_pending());
8189
8190 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8191 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8192 ASSERT_EQ(2u, blocked_callbacks.size());
8193 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8194 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8195
8196 // Confirm canceling one of the outstanding requests allows the
8197 // blocked request to complete.
8198
8199 // TODO(rdsmith): Find something to wait on other than the third
8200 // requests completion; if there's a bug in throttling, that will
8201 // result in this test hanging rather than failing quickly.
8202 d1.set_quit_on_complete(false);
8203 d2.set_quit_on_complete(false);
8204 d3.set_quit_on_complete(true);
8205 req2->Cancel();
8206 base::RunLoop().Run();
8207
8208 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8209 EXPECT_EQ(0u, blocked_callbacks.size());
8210 EXPECT_TRUE(req1->status().is_io_pending());
8211 EXPECT_EQ(URLRequestStatus::CANCELED, req2->status().status());
8212 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8213}
8214
8215TEST_F(URLRequestTestHTTP, ThrottledRepriUnblock) {
8216 ASSERT_TRUE(http_test_server()->Start());
8217
8218 base::RunLoop run_until_request_blocked;
8219
8220 NotificationCallbackHandler notification_handler;
8221 notification_handler.SetRunLoop(&run_until_request_blocked);
8222 BlockingNetworkDelegate network_delegate(
8223 BlockingNetworkDelegate::USER_NOTIFY);
8224 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8225 network_delegate.set_notification_callback(
8226 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8227 // Both objects are owned by this function, and
8228 // |*network_delegate| will be destroyed first, so
8229 // it's safe to pass it an unretained pointer.
8230 base::Unretained(&notification_handler)));
8231
8232 TestURLRequestContext context(true);
8233 context.set_network_delegate(&network_delegate);
8234 context.Init();
8235
8236 // Use different test URLs to make sure all three requests turn into
8237 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8238 // the requests may be waited on separately.
8239 TestDelegate d1;
8240 std::unique_ptr<URLRequest> req1(context.CreateRequest(
8241 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
8242 notification_handler.AddURLRequestToBlockList(req1.get());
8243
8244 TestDelegate d2;
8245 std::unique_ptr<URLRequest> req2(context.CreateRequest(
8246 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
8247 notification_handler.AddURLRequestToBlockList(req2.get());
8248
8249 TestDelegate d3;
8250 std::unique_ptr<URLRequest> req3(context.CreateRequest(
8251 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
8252 req1->Start();
8253 req2->Start();
8254 req3->Start();
8255 run_until_request_blocked.Run();
8256 notification_handler.SetRunLoop(nullptr);
8257
8258 // The first two requests should be blocked based on the notification
8259 // callback, and their status should have blocked the third request
8260 // through throttling.
8261 EXPECT_TRUE(req1->status().is_io_pending());
8262 EXPECT_TRUE(req2->status().is_io_pending());
8263 EXPECT_TRUE(req3->status().is_io_pending());
8264
8265 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8266 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8267 ASSERT_EQ(2u, blocked_callbacks.size());
8268 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8269 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8270
8271 // Confirm raising the priority of the third request allows it to complete.
8272
8273 // TODO(rdsmith): Find something to wait on other than the third
8274 // requests completion; if there's a bug in throttling, that will
8275 // result in this test hanging rather than failing quickly.
8276 d1.set_quit_on_complete(false);
8277 d2.set_quit_on_complete(false);
8278 d3.set_quit_on_complete(true);
8279 req3->SetPriority(IDLE);
8280 base::RunLoop().Run();
8281
8282 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8283 EXPECT_EQ(0u, blocked_callbacks.size());
8284 EXPECT_TRUE(req1->status().is_io_pending());
8285 EXPECT_TRUE(req2->status().is_io_pending());
8286 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8287}
8288
ricea3a1c71f2016-06-17 10:05:268289TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8290 ASSERT_TRUE(http_test_server()->Start());
8291
8292 TestDelegate d;
8293 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8294 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
8295 req->Start();
8296 base::RunLoop().Run();
8297
8298 EXPECT_EQ(5, req->GetRawBodyBytes());
8299}
8300
8301TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8302 ASSERT_TRUE(http_test_server()->Start());
8303
8304 TestDelegate d;
8305 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8306 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
8307 req->Start();
8308 base::RunLoop().Run();
8309
8310 EXPECT_EQ(30, req->GetRawBodyBytes());
8311}
8312
jamd3f5a3c2016-10-27 18:52:028313// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8314// the delegate isn't called back synchronously.
8315TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8316 ASSERT_TRUE(http_test_server()->Start());
8317 default_network_delegate_.set_before_start_transaction_fails();
8318
8319 TestDelegate d;
8320 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8321 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
8322 req->Start();
8323 DCHECK(!d.response_completed());
8324 base::RunLoop().Run();
8325 DCHECK(d.response_completed());
8326 EXPECT_EQ(ERR_FAILED, d.request_status());
8327}
8328
bengr1bf8e942014-11-07 01:36:508329class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
8330 public:
8331 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
8332 // ideally remove the dependency on URLRequestTestJob, and maybe move these
8333 // tests into the factory tests.
8334 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
8335 }
8336
8337 void SetUpFactory() override {
8338 interceptor_ = new MockURLRequestInterceptor();
8339 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:368340 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:508341 }
8342
8343 MockURLRequestInterceptor* interceptor() const {
8344 return interceptor_;
8345 }
8346
8347 private:
8348 MockURLRequestInterceptor* interceptor_;
8349};
8350
8351TEST_F(URLRequestInterceptorTestHTTP,
8352 NetworkDelegateNotificationOnRedirectIntercept) {
8353 interceptor()->set_intercept_redirect(true);
8354 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8355 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8356
tommycli59a63432015-11-06 00:10:558357 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508358
8359 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368360 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558361 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508362 req->Start();
8363 base::RunLoop().Run();
8364
8365 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8366 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:508367 int status = d.request_status();
8368 EXPECT_EQ(OK, status);
8369 if (status == OK)
bengr1bf8e942014-11-07 01:36:508370 EXPECT_EQ(200, req->response_headers()->response_code());
8371
8372 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8373 EXPECT_EQ(1, d.response_started_count());
8374 EXPECT_EQ(0, d.received_redirect_count());
8375
8376 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008377 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508378 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8379}
8380
8381TEST_F(URLRequestInterceptorTestHTTP,
8382 NetworkDelegateNotificationOnErrorIntercept) {
8383 // Intercept that error and respond with an OK response.
8384 interceptor()->set_intercept_final_response(true);
8385 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8386 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8387 default_network_delegate()->set_can_be_intercepted_on_error(true);
8388
tommycli59a63432015-11-06 00:10:558389 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508390
8391 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368392 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558393 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:368394 &d));
bengr1bf8e942014-11-07 01:36:508395 req->set_method("GET");
8396 req->Start();
8397 base::RunLoop().Run();
8398
8399 EXPECT_TRUE(interceptor()->did_intercept_final());
8400
8401 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508402 int status = d.request_status();
8403 EXPECT_EQ(OK, status);
8404 if (status == OK)
bengr1bf8e942014-11-07 01:36:508405 EXPECT_EQ(200, req->response_headers()->response_code());
8406 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8407 EXPECT_EQ(1, d.response_started_count());
8408 EXPECT_EQ(0, d.received_redirect_count());
8409
8410 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008411 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508412 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
8413}
8414
8415TEST_F(URLRequestInterceptorTestHTTP,
8416 NetworkDelegateNotificationOnResponseIntercept) {
8417 // Intercept that error and respond with an OK response.
8418 interceptor()->set_intercept_final_response(true);
8419
8420 // Intercept with a real URLRequestHttpJob.
8421 interceptor()->set_use_url_request_http_job(true);
8422
tommycli59a63432015-11-06 00:10:558423 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508424
8425 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368426 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558427 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508428 req->set_method("GET");
8429 req->Start();
8430 base::RunLoop().Run();
8431
8432 EXPECT_TRUE(interceptor()->did_intercept_final());
8433
8434 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508435 int status = d.request_status();
8436 EXPECT_EQ(OK, status);
8437 if (status == OK)
bengr1bf8e942014-11-07 01:36:508438 EXPECT_EQ(200, req->response_headers()->response_code());
8439 EXPECT_EQ("hello", d.data_received());
8440 EXPECT_EQ(1, d.response_started_count());
8441 EXPECT_EQ(0, d.received_redirect_count());
8442
8443 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008444 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508445 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
8446}
8447
mkwst0c5eab872014-11-21 14:18:548448class URLRequestTestReferrerPolicy : public URLRequestTest {
8449 public:
8450 URLRequestTestReferrerPolicy() {}
8451
tommycli59a63432015-11-06 00:10:558452 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
8453 origin_server_.reset(new EmbeddedTestServer(type));
8454 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
8455 origin_server_->AddDefaultHandlers(
8456 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8457 } else {
8458 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8459 }
mkwst0c5eab872014-11-21 14:18:548460 ASSERT_TRUE(origin_server_->Start());
8461 }
8462
tommycli59a63432015-11-06 00:10:558463 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8464 net::EmbeddedTestServer::Type dest_type) {
8465 origin_server_.reset(new EmbeddedTestServer(origin_type));
8466 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8467 origin_server_->AddDefaultHandlers(
8468 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8469 } else {
8470 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8471 }
mkwst0c5eab872014-11-21 14:18:548472 ASSERT_TRUE(origin_server_->Start());
8473
tommycli59a63432015-11-06 00:10:558474 destination_server_.reset(new EmbeddedTestServer(dest_type));
8475 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8476 destination_server_->AddDefaultHandlers(
8477 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8478 } else {
8479 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8480 }
mkwst0c5eab872014-11-21 14:18:548481 ASSERT_TRUE(destination_server_->Start());
8482 }
8483
8484 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8485 const GURL& referrer,
8486 const GURL& expected) {
8487 // Create and execute the request: we'll only have a |destination_server_|
8488 // if the origins are meant to be distinct. Otherwise, we'll use the
8489 // |origin_server_| for both endpoints.
8490 GURL destination_url =
tommycli59a63432015-11-06 00:10:558491 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8492 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548493 GURL origin_url =
tommycli59a63432015-11-06 00:10:558494 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548495
8496 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368497 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368498 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548499 req->set_referrer_policy(policy);
8500 req->SetReferrer(referrer.spec());
8501 req->Start();
8502 base::RunLoop().Run();
8503
8504 EXPECT_EQ(1, d.response_started_count());
8505 EXPECT_EQ(1, d.received_redirect_count());
8506 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:508507 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:548508 EXPECT_EQ(200, req->response_headers()->response_code());
8509
8510 EXPECT_EQ(expected.spec(), req->referrer());
8511 if (expected.is_empty())
8512 EXPECT_EQ("None", d.data_received());
8513 else
8514 EXPECT_EQ(expected.spec(), d.data_received());
8515 }
8516
tommycli59a63432015-11-06 00:10:558517 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548518
8519 private:
danakj8522a25b2016-04-16 00:17:368520 std::unique_ptr<EmbeddedTestServer> origin_server_;
8521 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548522};
8523
8524TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558525 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548526
8527 VerifyReferrerAfterRedirect(
8528 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558529 origin_server()->GetURL("/path/to/file.html"),
8530 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548531
8532 VerifyReferrerAfterRedirect(
8533 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558534 origin_server()->GetURL("/path/to/file.html"),
8535 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548536
8537 VerifyReferrerAfterRedirect(
8538 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558539 origin_server()->GetURL("/path/to/file.html"),
8540 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548541
8542 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558543 origin_server()->GetURL("/path/to/file.html"),
8544 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548545}
8546
tommycli59a63432015-11-06 00:10:558547TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8548 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8549 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548550
8551 VerifyReferrerAfterRedirect(
8552 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558553 origin_server()->GetURL("/path/to/file.html"),
8554 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548555
8556 VerifyReferrerAfterRedirect(
8557 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558558 origin_server()->GetURL("/path/to/file.html"),
8559 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548560
8561 VerifyReferrerAfterRedirect(
8562 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558563 origin_server()->GetURL("/path/to/file.html"),
8564 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548565
8566 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558567 origin_server()->GetURL("/path/to/file.html"),
8568 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548569}
8570
8571TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558572 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548573
8574 VerifyReferrerAfterRedirect(
8575 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558576 origin_server()->GetURL("/path/to/file.html"),
8577 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548578
8579 VerifyReferrerAfterRedirect(
8580 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558581 origin_server()->GetURL("/path/to/file.html"),
8582 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548583
8584 VerifyReferrerAfterRedirect(
8585 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558586 origin_server()->GetURL("/path/to/file.html"),
8587 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548588
8589 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558590 origin_server()->GetURL("/path/to/file.html"),
8591 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548592}
8593
tommycli59a63432015-11-06 00:10:558594TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8595 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8596 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548597
8598 VerifyReferrerAfterRedirect(
8599 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558600 origin_server()->GetURL("/path/to/file.html"),
8601 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548602
8603 VerifyReferrerAfterRedirect(
8604 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558605 origin_server()->GetURL("/path/to/file.html"),
8606 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548607
8608 VerifyReferrerAfterRedirect(
8609 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558610 origin_server()->GetURL("/path/to/file.html"),
8611 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548612
8613 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558614 origin_server()->GetURL("/path/to/file.html"),
8615 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548616}
8617
tommycli59a63432015-11-06 00:10:558618TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8619 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8620 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548621
8622 VerifyReferrerAfterRedirect(
8623 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558624 origin_server()->GetURL("/path/to/file.html"),
8625 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548626
8627 VerifyReferrerAfterRedirect(
8628 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558629 origin_server()->GetURL("/path/to/file.html"),
8630 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548631
8632 VerifyReferrerAfterRedirect(
8633 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558634 origin_server()->GetURL("/path/to/file.html"),
8635 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548636
8637 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558638 origin_server()->GetURL("/path/to/file.html"),
8639 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548640}
8641
tommycli59a63432015-11-06 00:10:558642TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8643 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8644 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548645
8646 VerifyReferrerAfterRedirect(
8647 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558648 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548649
8650 VerifyReferrerAfterRedirect(
8651 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558652 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548653
8654 VerifyReferrerAfterRedirect(
8655 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558656 origin_server()->GetURL("/path/to/file.html"),
8657 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548658
8659 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558660 origin_server()->GetURL("/path/to/file.html"),
8661 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548662}
8663
[email protected]73e0bba2009-02-19 22:57:098664class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508665 public:
fdoraya89e673c2017-01-31 21:44:218666 HTTPSRequestTest()
8667 : scoped_task_scheduler_(base::MessageLoop::current()),
8668 default_context_(true) {
[email protected]ef2bf422012-05-11 03:27:098669 default_context_.set_network_delegate(&default_network_delegate_);
8670 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508671 }
dcheng67be2b1f2014-10-27 21:47:298672 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508673
8674 protected:
fdoraya89e673c2017-01-31 21:44:218675 // Required by ChannelIDService.
8676 base::test::ScopedTaskScheduler scoped_task_scheduler_;
[email protected]ceefd7fd2012-11-29 00:36:248677 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098678 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468679};
8680
[email protected]c044616e2013-02-20 02:01:268681TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558682 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8683 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228684 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118685 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468686
[email protected]ea224582008-12-07 20:25:468687 TestDelegate d;
8688 {
danakj8522a25b2016-04-16 00:17:368689 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558690 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198691 r->Start();
8692 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468693
[email protected]255620da2013-08-19 13:14:298694 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468695
8696 EXPECT_EQ(1, d.response_started_count());
8697 EXPECT_FALSE(d.received_data_before_response());
8698 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198699 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198700 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198701 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198702 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198703 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468704 }
[email protected]ea224582008-12-07 20:25:468705}
8706
[email protected]5774ada2010-07-15 06:30:548707TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558708 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8709 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8710 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228711 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118712 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338713
8714 bool err_allowed = true;
8715 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8716 TestDelegate d;
8717 {
8718 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368719 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558720 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338721
[email protected]f7022f32014-08-21 16:32:198722 r->Start();
8723 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338724
[email protected]255620da2013-08-19 13:14:298725 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338726
8727 EXPECT_EQ(1, d.response_started_count());
8728 EXPECT_FALSE(d.received_data_before_response());
8729 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178730 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338731 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198732 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178733 } else {
[email protected]bacff652009-03-31 17:50:338734 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178735 }
[email protected]bacff652009-03-31 17:50:338736 }
8737 }
8738}
8739
[email protected]5774ada2010-07-15 06:30:548740TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558741 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8742 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8743 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228744 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118745 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338746
8747 // Iterate from false to true, just so that we do the opposite of the
8748 // previous test in order to increase test coverage.
8749 bool err_allowed = false;
8750 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8751 TestDelegate d;
8752 {
8753 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368754 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558755 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338756
[email protected]f7022f32014-08-21 16:32:198757 r->Start();
8758 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338759
[email protected]255620da2013-08-19 13:14:298760 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338761
8762 EXPECT_EQ(1, d.response_started_count());
8763 EXPECT_FALSE(d.received_data_before_response());
8764 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178765 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338766 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198767 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178768 } else {
[email protected]bacff652009-03-31 17:50:338769 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178770 }
[email protected]bacff652009-03-31 17:50:338771 }
8772 }
8773}
[email protected]73e0bba2009-02-19 22:57:098774
tommycli59a63432015-11-06 00:10:558775// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8776// security state. (see http://crbug.com/550977).
8777#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448778// This tests that a load of www.google.com with a certificate error sets
8779// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8780// the interstitial to be fatal.
8781TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558782 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8783 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8784 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448785 ASSERT_TRUE(test_server.Start());
8786
8787 // We require that the URL be www.google.com in order to pick up the
8788 // preloaded HSTS entries in the TransportSecurityState. This means that we
8789 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248790 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448791
8792 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248793 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448794 TestURLRequestContext context(true);
8795 context.set_network_delegate(&network_delegate);
8796 context.set_host_resolver(&host_resolver);
8797 TransportSecurityState transport_security_state;
8798 context.set_transport_security_state(&transport_security_state);
8799 context.Init();
8800
8801 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368802 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198803 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368804 test_server.host_port_pair().port())),
8805 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448806
[email protected]f7022f32014-08-21 16:32:198807 r->Start();
8808 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448809
[email protected]255620da2013-08-19 13:14:298810 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448811
8812 EXPECT_EQ(1, d.response_started_count());
8813 EXPECT_FALSE(d.received_data_before_response());
8814 EXPECT_TRUE(d.have_certificate_errors());
8815 EXPECT_TRUE(d.certificate_errors_are_fatal());
8816}
8817
8818// This tests that cached HTTPS page loads do not cause any updates to the
8819// TransportSecurityState.
8820TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8821 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8822 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558823 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8824 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8825 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448826 ASSERT_TRUE(test_server.Start());
8827
[email protected]9e6968d2014-05-07 21:46:268828 // We require that the URL be www.google.com in order to pick up the static
8829 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8830 // that we have to use a MockHostResolver in order to direct www.google.com to
8831 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448832
8833 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248834 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448835 TestURLRequestContext context(true);
8836 context.set_network_delegate(&network_delegate);
8837 context.set_host_resolver(&host_resolver);
8838 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268839
martijnc0d6b622015-06-30 19:14:408840 TransportSecurityState::STSState static_sts_state;
8841 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268842 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408843 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448844 context.set_transport_security_state(&transport_security_state);
8845 context.Init();
8846
martijnc0d6b622015-06-30 19:14:408847 TransportSecurityState::STSState dynamic_sts_state;
8848 TransportSecurityState::PKPState dynamic_pkp_state;
8849 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8850 &dynamic_sts_state));
8851 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8852 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268853
[email protected]316c1e5e2012-09-12 15:17:448854 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368855 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198856 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368857 test_server.host_port_pair().port())),
8858 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448859
[email protected]f7022f32014-08-21 16:32:198860 r->Start();
8861 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448862
[email protected]255620da2013-08-19 13:14:298863 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448864
8865 EXPECT_EQ(1, d.response_started_count());
8866 EXPECT_FALSE(d.received_data_before_response());
8867 EXPECT_TRUE(d.have_certificate_errors());
8868 EXPECT_TRUE(d.certificate_errors_are_fatal());
8869
[email protected]9e6968d2014-05-07 21:46:268870 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408871 TransportSecurityState::STSState new_static_sts_state;
8872 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268873 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408874 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8875 TransportSecurityState::STSState new_dynamic_sts_state;
8876 TransportSecurityState::PKPState new_dynamic_pkp_state;
8877 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8878 "www.google.com", &new_dynamic_sts_state));
8879 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8880 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268881
martijnc0d6b622015-06-30 19:14:408882 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8883 EXPECT_EQ(new_static_sts_state.include_subdomains,
8884 static_sts_state.include_subdomains);
8885 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8886 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488887 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8888 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8889 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448890}
8891
[email protected]8ccc69f2012-11-28 19:52:148892// Make sure HSTS preserves a POST request's method and body.
8893TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8894 static const char kData[] = "hello world";
8895
tommycli59a63432015-11-06 00:10:558896 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8897 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228898 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148899 ASSERT_TRUE(test_server.Start());
8900
8901
8902 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8903 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558904 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228905 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148906 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148907
8908 // Force https for www.somewhere.com.
8909 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208910 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8911 bool include_subdomains = false;
8912 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8913 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148914
8915 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8916
8917 TestURLRequestContext context(true);
8918 context.set_host_resolver(&host_resolver);
8919 context.set_transport_security_state(&transport_security_state);
8920 context.set_network_delegate(&network_delegate);
8921 context.Init();
8922
8923 TestDelegate d;
8924 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8925 // cause a certificate error. Ignore the error.
8926 d.set_allow_certificate_errors(true);
8927
danakj8522a25b2016-04-16 00:17:368928 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198929 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368930 test_server.host_port_pair().port())),
8931 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198932 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078933 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148934
[email protected]f7022f32014-08-21 16:32:198935 req->Start();
[email protected]255620da2013-08-19 13:14:298936 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148937
[email protected]f7022f32014-08-21 16:32:198938 EXPECT_EQ("https", req->url().scheme());
8939 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148940 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408941
8942 LoadTimingInfo load_timing_info;
8943 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8944 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8945 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148946}
8947
rob4e0be1f2014-09-11 23:40:228948// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8949TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8950 static const char kOriginHeaderValue[] = "http://www.example.com";
8951
tommycli59a63432015-11-06 00:10:558952 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8953 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228954 ASSERT_TRUE(test_server.Start());
8955
8956 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8957 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558958 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8959 // default.
rob4e0be1f2014-09-11 23:40:228960 MockHostResolver host_resolver;
8961
8962 TransportSecurityState transport_security_state;
8963 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8964 bool include_subdomains = false;
8965 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8966
8967 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8968
8969 MockCertVerifier cert_verifier;
8970 cert_verifier.set_default_result(OK);
8971
8972 TestURLRequestContext context(true);
8973 context.set_host_resolver(&host_resolver);
8974 context.set_transport_security_state(&transport_security_state);
8975 context.set_network_delegate(&network_delegate);
8976 context.set_cert_verifier(&cert_verifier);
8977 context.Init();
8978
8979 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8980 test_server.host_port_pair().port()));
8981 url::Replacements<char> replacements;
8982 const char kNewScheme[] = "https";
8983 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8984 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8985
8986 TestDelegate d;
8987 // Quit on redirect to allow response header inspection upon redirect.
8988 d.set_quit_on_redirect(true);
8989
danakj8522a25b2016-04-16 00:17:368990 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368991 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228992 // Set Origin header to simulate a cross-origin request.
8993 HttpRequestHeaders request_headers;
8994 request_headers.SetHeader("Origin", kOriginHeaderValue);
8995 req->SetExtraRequestHeaders(request_headers);
8996
8997 req->Start();
8998 base::RunLoop().Run();
8999
9000 EXPECT_EQ(1, d.received_redirect_count());
9001
9002 const HttpResponseHeaders* headers = req->response_headers();
9003 std::string redirect_location;
9004 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
9005 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
9006
9007 std::string received_cors_header;
9008 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
9009 &received_cors_header));
9010 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
9011}
9012
[email protected]316c1e5e2012-09-12 15:17:449013namespace {
9014
9015class SSLClientAuthTestDelegate : public TestDelegate {
9016 public:
9017 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
9018 }
dchengb03027d2014-10-21 12:00:209019 void OnCertificateRequested(URLRequest* request,
9020 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:449021 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:179022 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:449023 }
9024 int on_certificate_requested_count() {
9025 return on_certificate_requested_count_;
9026 }
9027 private:
9028 int on_certificate_requested_count_;
9029};
9030
9031} // namespace
9032
9033// TODO(davidben): Test the rest of the code. Specifically,
9034// - Filtering which certificates to select.
9035// - Sending a certificate back.
9036// - Getting a certificate request in an SSL renegotiation sending the
9037// HTTP request.
9038TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:559039 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9040 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:129041 ssl_config.client_cert_type =
9042 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:559043 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
9044 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:229045 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449046 ASSERT_TRUE(test_server.Start());
9047
9048 SSLClientAuthTestDelegate d;
9049 {
danakj8522a25b2016-04-16 00:17:369050 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559051 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449052
[email protected]f7022f32014-08-21 16:32:199053 r->Start();
9054 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449055
[email protected]255620da2013-08-19 13:14:299056 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449057
9058 EXPECT_EQ(1, d.on_certificate_requested_count());
9059 EXPECT_FALSE(d.received_data_before_response());
9060 EXPECT_EQ(0, d.bytes_received());
9061
9062 // Send no certificate.
9063 // TODO(davidben): Get temporary client cert import (with keys) working on
9064 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:549065 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:449066
[email protected]255620da2013-08-19 13:14:299067 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449068
9069 EXPECT_EQ(1, d.response_started_count());
9070 EXPECT_FALSE(d.received_data_before_response());
9071 EXPECT_NE(0, d.bytes_received());
9072 }
9073}
9074
9075TEST_F(HTTPSRequestTest, ResumeTest) {
9076 // Test that we attempt a session resume when making two connections to the
9077 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:229078 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449079 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229080 SpawnedTestServer test_server(
9081 SpawnedTestServer::TYPE_HTTPS,
9082 ssl_options,
9083 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449084 ASSERT_TRUE(test_server.Start());
9085
9086 SSLClientSocket::ClearSessionCache();
9087
9088 {
9089 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369090 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369091 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449092
[email protected]f7022f32014-08-21 16:32:199093 r->Start();
9094 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449095
[email protected]255620da2013-08-19 13:14:299096 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449097
9098 EXPECT_EQ(1, d.response_started_count());
9099 }
9100
9101 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9102 CloseAllConnections();
9103
9104 {
9105 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369106 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369107 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449108
[email protected]f7022f32014-08-21 16:32:199109 r->Start();
9110 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449111
[email protected]255620da2013-08-19 13:14:299112 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449113
9114 // The response will look like;
9115 // insert abc
9116 // lookup abc
9117 // insert xyz
9118 //
9119 // With a newline at the end which makes the split think that there are
9120 // four lines.
9121
9122 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:299123 std::vector<std::string> lines = base::SplitString(
9124 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449125 ASSERT_EQ(4u, lines.size()) << d.data_received();
9126
9127 std::string session_id;
9128
9129 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299130 std::vector<std::string> parts = base::SplitString(
9131 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449132 ASSERT_EQ(2u, parts.size());
9133 if (i == 0) {
9134 EXPECT_EQ("insert", parts[0]);
9135 session_id = parts[1];
9136 } else {
9137 EXPECT_EQ("lookup", parts[0]);
9138 EXPECT_EQ(session_id, parts[1]);
9139 }
9140 }
9141 }
9142}
9143
Adam Langley32352ad2014-10-14 22:31:009144// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
9145// the result of fetching "ssl-session-cache" from the test server, indicates
9146// that exactly two different sessions were inserted, with no lookups etc.
9147static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:299148 std::vector<std::string> lines = base::SplitString(
9149 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009150 ASSERT_EQ(3u, lines.size()) << session_info;
9151
9152 std::string session_id;
9153 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299154 std::vector<std::string> parts = base::SplitString(
9155 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009156 ASSERT_EQ(2u, parts.size());
9157 EXPECT_EQ("insert", parts[0]);
9158 if (i == 0) {
9159 session_id = parts[1];
9160 } else {
9161 EXPECT_NE(session_id, parts[1]);
9162 }
9163 }
9164}
9165
[email protected]316c1e5e2012-09-12 15:17:449166TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
9167 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
9168 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:229169 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449170 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229171 SpawnedTestServer test_server(
9172 SpawnedTestServer::TYPE_HTTPS,
9173 ssl_options,
9174 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449175 ASSERT_TRUE(test_server.Start());
9176
9177 SSLClientSocket::ClearSessionCache();
9178
9179 {
9180 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369181 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369182 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449183
[email protected]f7022f32014-08-21 16:32:199184 r->Start();
9185 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449186
[email protected]255620da2013-08-19 13:14:299187 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449188
9189 EXPECT_EQ(1, d.response_started_count());
9190 }
9191
9192 // Now create a new HttpCache with a different ssl_session_cache_shard value.
9193 HttpNetworkSession::Params params;
9194 params.host_resolver = default_context_.host_resolver();
9195 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:119196 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:209197 params.cert_transparency_verifier =
9198 default_context_.cert_transparency_verifier();
9199 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:449200 params.proxy_service = default_context_.proxy_service();
9201 params.ssl_config_service = default_context_.ssl_config_service();
9202 params.http_auth_handler_factory =
9203 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:449204 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:449205
mmenkee65e7af2015-10-13 17:16:429206 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:369207 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:429208 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:449209
9210 default_context_.set_http_transaction_factory(cache.get());
9211
9212 {
9213 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369214 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369215 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449216
[email protected]f7022f32014-08-21 16:32:199217 r->Start();
9218 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449219
[email protected]255620da2013-08-19 13:14:299220 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449221
9222 // The response will look like;
9223 // insert abc
9224 // insert xyz
9225 //
9226 // With a newline at the end which makes the split think that there are
9227 // three lines.
9228
9229 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009230 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449231 }
9232}
9233
[email protected]48d2b7c52014-06-27 01:16:559234class HTTPSFallbackTest : public testing::Test {
9235 public:
Adam Langley32352ad2014-10-14 22:31:009236 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:299237 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:559238
9239 protected:
9240 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
9241 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:009242 context_.Init();
9243 delegate_.set_allow_certificate_errors(true);
9244
[email protected]48d2b7c52014-06-27 01:16:559245 SpawnedTestServer test_server(
9246 SpawnedTestServer::TYPE_HTTPS,
9247 ssl_options,
9248 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9249 ASSERT_TRUE(test_server.Start());
9250
tommycli59a63432015-11-06 00:10:559251 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
9252 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:559253 request_->Start();
9254
9255 base::RunLoop().Run();
9256 }
9257
[email protected]48d2b7c52014-06-27 01:16:559258 void ExpectFailure(int error) {
9259 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509260 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:559261 }
9262
9263 private:
9264 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:479265 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369266 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:559267};
9268
davidbenb127ca82015-06-15 19:05:429269// Tests the TLS 1.0 fallback doesn't happen.
9270TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:559271 SpawnedTestServer::SSLOptions ssl_options(
9272 SpawnedTestServer::SSLOptions::CERT_OK);
9273 ssl_options.tls_intolerant =
9274 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
9275
9276 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:559277 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:429278}
9279
davidben5a312152016-06-27 22:11:479280// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:559281TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:429282 SpawnedTestServer::SSLOptions ssl_options(
9283 SpawnedTestServer::SSLOptions::CERT_OK);
9284 ssl_options.tls_intolerant =
9285 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
9286
9287 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:559288 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
9289}
9290
[email protected]a8fed1742013-12-27 02:14:249291class HTTPSSessionTest : public testing::Test {
9292 public:
fdoraya89e673c2017-01-31 21:44:219293 HTTPSSessionTest()
9294 : scoped_task_scheduler_(base::MessageLoop::current()),
9295 default_context_(true) {
[email protected]cba24642014-08-15 20:49:599296 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249297
9298 default_context_.set_network_delegate(&default_network_delegate_);
9299 default_context_.set_cert_verifier(&cert_verifier_);
9300 default_context_.Init();
9301 }
dcheng67be2b1f2014-10-27 21:47:299302 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:249303
9304 protected:
fdoraya89e673c2017-01-31 21:44:219305 // Required by ChannelIDService.
9306 base::test::ScopedTaskScheduler scoped_task_scheduler_;
[email protected]a8fed1742013-12-27 02:14:249307 MockCertVerifier cert_verifier_;
9308 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
9309 TestURLRequestContext default_context_;
9310};
9311
9312// Tests that session resumption is not attempted if an invalid certificate
9313// is presented.
9314TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
9315 SpawnedTestServer::SSLOptions ssl_options;
9316 ssl_options.record_resume = true;
9317 SpawnedTestServer test_server(
9318 SpawnedTestServer::TYPE_HTTPS,
9319 ssl_options,
9320 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9321 ASSERT_TRUE(test_server.Start());
9322
9323 SSLClientSocket::ClearSessionCache();
9324
9325 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:599326 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:249327 {
9328 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369329 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369330 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249331
[email protected]f7022f32014-08-21 16:32:199332 r->Start();
9333 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249334
9335 base::RunLoop().Run();
9336
9337 EXPECT_EQ(1, d.response_started_count());
9338 }
9339
9340 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9341 CloseAllConnections();
9342
9343 // Now change the certificate to be acceptable (so that the response is
9344 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:599345 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249346 {
9347 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369348 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369349 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249350
[email protected]f7022f32014-08-21 16:32:199351 r->Start();
9352 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249353
9354 base::RunLoop().Run();
9355
9356 // The response will look like;
9357 // insert abc
9358 // insert xyz
9359 //
9360 // With a newline at the end which makes the split think that there are
9361 // three lines.
9362 //
9363 // If a session was presented (eg: a bug), then the response would look
9364 // like;
9365 // insert abc
9366 // lookup abc
9367 // insert xyz
9368
9369 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009370 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:249371 }
9372}
9373
[email protected]dffe8242012-03-20 15:14:279374// This the fingerprint of the "Testing CA" certificate used by the testserver.
9375// See net/data/ssl/certificates/ocsp-test-root.pem.
mattm3b4376f12016-10-03 21:07:159376static const SHA1HashValue kOCSPTestCertFingerprint = {{
mattm0b12a6f2016-11-29 19:57:169377 0x80, 0x37, 0xe7, 0xee, 0x12, 0x19, 0xeb, 0x10, 0x79, 0x36,
9378 0x00, 0x48, 0x57, 0x5a, 0xa6, 0x1e, 0x2b, 0x24, 0x1a, 0xd7,
mattm3b4376f12016-10-03 21:07:159379}};
[email protected]dffe8242012-03-20 15:14:279380
[email protected]51523f52013-07-31 21:57:289381// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
9382// testserver.
mattm0b12a6f2016-11-29 19:57:169383static const SHA256HashValue kOCSPTestCertSPKI = {{
9384 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
9385 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
9386 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
9387}};
[email protected]51523f52013-07-31 21:57:289388
[email protected]dffe8242012-03-20 15:14:279389// This is the policy OID contained in the certificates that testserver
9390// generates.
9391static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
9392
9393class HTTPSOCSPTest : public HTTPSRequestTest {
9394 public:
9395 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:099396 : context_(true),
[email protected]b6f2de32012-08-17 04:35:089397 ev_test_policy_(
9398 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
9399 kOCSPTestCertFingerprint,
9400 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:029401 }
9402
dcheng67be2b1f2014-10-27 21:47:299403 void SetUp() override {
rsleevid6de8302016-06-21 01:33:209404 context_.SetCTPolicyEnforcer(
9405 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
9406 SetupContext();
[email protected]ef2bf422012-05-11 03:27:099407 context_.Init();
[email protected]dffe8242012-03-20 15:14:279408
[email protected]cba24642014-08-15 20:49:599409 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:209410 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:429411 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:509412 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:279413
svaldez2135be52016-04-20 16:34:539414#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:099415 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:279416 EnsureNSSHttpIOInit();
9417#endif
9418 }
9419
dadrian612337a2016-07-20 22:36:589420 void DoConnectionWithDelegate(
9421 const SpawnedTestServer::SSLOptions& ssl_options,
9422 TestDelegate* delegate,
9423 SSLInfo* out_ssl_info) {
9424 // Always overwrite |out_ssl_info|.
9425 out_ssl_info->Reset();
9426
[email protected]ce7d0cbc2013-05-03 18:57:229427 SpawnedTestServer test_server(
9428 SpawnedTestServer::TYPE_HTTPS,
9429 ssl_options,
9430 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:279431 ASSERT_TRUE(test_server.Start());
9432
dadrian612337a2016-07-20 22:36:589433 delegate->set_allow_certificate_errors(true);
9434 std::unique_ptr<URLRequest> r(context_.CreateRequest(
9435 test_server.GetURL("/"), DEFAULT_PRIORITY, delegate));
[email protected]f7022f32014-08-21 16:32:199436 r->Start();
[email protected]dffe8242012-03-20 15:14:279437
[email protected]255620da2013-08-19 13:14:299438 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:589439 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:279440
dadrian612337a2016-07-20 22:36:589441 *out_ssl_info = r->ssl_info();
9442 }
9443
9444 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
9445 CertStatus* out_cert_status) {
9446 // Always overwrite |out_cert_status|.
9447 *out_cert_status = 0;
9448
9449 TestDelegate d;
9450 SSLInfo ssl_info;
9451 ASSERT_NO_FATAL_FAILURE(
9452 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
9453
9454 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:279455 }
9456
dcheng67be2b1f2014-10-27 21:47:299457 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:539458#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:279459 ShutdownNSSHttpIO();
9460#endif
9461 }
9462
[email protected]a13234c2012-03-20 21:45:029463 protected:
rsleevid6de8302016-06-21 01:33:209464 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9465 public:
9466 AllowAnyCertCTPolicyEnforcer() = default;
9467 ~AllowAnyCertCTPolicyEnforcer() override = default;
9468
9469 ct::CertPolicyCompliance DoesConformToCertPolicy(
9470 X509Certificate* cert,
9471 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209472 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209473 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9474 }
9475
9476 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9477 X509Certificate* cert,
9478 const ct::EVCertsWhitelist* ev_whitelist,
9479 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209480 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209481 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9482 }
9483 };
[email protected]a13234c2012-03-20 21:45:029484 // SetupContext configures the URLRequestContext that will be used for making
9485 // connetions to testserver. This can be overridden in test subclasses for
9486 // different behaviour.
rsleevid6de8302016-06-21 01:33:209487 virtual void SetupContext() {
9488 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149489 true /* check for EV */, true /* online revocation checking */,
9490 false /* require rev. checking for local
9491 anchors */,
9492 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029493 }
9494
danakj8522a25b2016-04-16 00:17:369495 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099496 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369497 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279498};
9499
[email protected]a13234c2012-03-20 21:45:029500static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:209501#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:029502 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9503 // have that ability on other platforms.
9504 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9505#else
9506 return 0;
9507#endif
9508}
9509
[email protected]3a86a712013-07-30 07:16:209510// SystemSupportsHardFailRevocationChecking returns true iff the current
9511// operating system supports revocation checking and can distinguish between
9512// situations where a given certificate lacks any revocation information (eg:
9513// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9514// revocation information cannot be obtained (eg: the CRL was unreachable).
9515// If it does not, then tests which rely on 'hard fail' behaviour should be
9516// skipped.
9517static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539518#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209519 return true;
9520#else
9521 return false;
9522#endif
9523}
9524
[email protected]a13234c2012-03-20 21:45:029525// SystemUsesChromiumEVMetadata returns true iff the current operating system
9526// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9527// several tests are effected because our testing EV certificate won't be
9528// recognised as EV.
9529static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329530#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579531 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9532 return false;
mattm1a282f52016-11-10 21:49:429533#elif defined(OS_ANDROID)
9534 // On Android, we use the system to tell us whether a certificate is EV or not
9535 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019536 return false;
9537#else
9538 return true;
9539#endif
9540}
9541
mattmaf868e72016-09-23 23:25:209542// Returns the expected CertStatus for tests that expect an online revocation
9543// check failure as a result of checking a test EV cert, which will not
9544// actually trigger an online revocation check on some platforms.
9545static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
9546 if (SystemUsesChromiumEVMetadata()) {
9547 return ExpectedCertStatusForFailedOnlineRevocationCheck();
9548 } else {
9549 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
9550 // be enabled, and thus there will not be a revocation check to fail.
9551 return 0u;
9552 }
9553}
9554
[email protected]b6f2de32012-08-17 04:35:089555static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339556#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029557 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9558 return false;
9559#else
9560 return true;
9561#endif
9562}
9563
davidbend1fb2f12014-11-08 02:51:009564static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339565#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039566 return true;
mathpc992e602015-10-21 20:34:039567#else
9568 return false;
9569#endif
davidbend1fb2f12014-11-08 02:51:009570}
9571
[email protected]dffe8242012-03-20 15:14:279572TEST_F(HTTPSOCSPTest, Valid) {
9573 if (!SystemSupportsOCSP()) {
9574 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9575 return;
9576 }
9577
[email protected]ce7d0cbc2013-05-03 18:57:229578 SpawnedTestServer::SSLOptions ssl_options(
9579 SpawnedTestServer::SSLOptions::CERT_AUTO);
9580 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279581
[email protected]924e9f92012-12-16 22:00:539582 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129583 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279584
9585 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9586
[email protected]a13234c2012-03-20 21:45:029587 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9588 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279589
9590 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9591}
9592
9593TEST_F(HTTPSOCSPTest, Revoked) {
9594 if (!SystemSupportsOCSP()) {
9595 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9596 return;
9597 }
9598
[email protected]ce7d0cbc2013-05-03 18:57:229599 SpawnedTestServer::SSLOptions ssl_options(
9600 SpawnedTestServer::SSLOptions::CERT_AUTO);
9601 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279602
9603 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129604 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279605
[email protected]dffe8242012-03-20 15:14:279606 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279607 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9608 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9609}
9610
9611TEST_F(HTTPSOCSPTest, Invalid) {
9612 if (!SystemSupportsOCSP()) {
9613 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9614 return;
9615 }
9616
[email protected]ce7d0cbc2013-05-03 18:57:229617 SpawnedTestServer::SSLOptions ssl_options(
9618 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589619 ssl_options.ocsp_status =
9620 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:279621
[email protected]924e9f92012-12-16 22:00:539622 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129623 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279624
[email protected]a13234c2012-03-20 21:45:029625 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279626 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279627
9628 // Without a positive OCSP response, we shouldn't show the EV status.
9629 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9630 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9631}
[email protected]a13234c2012-03-20 21:45:029632
davidbend1fb2f12014-11-08 02:51:009633TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039634 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009635 LOG(WARNING)
9636 << "Skipping test because system doesn't support OCSP stapling";
9637 return;
9638 }
9639
9640 SpawnedTestServer::SSLOptions ssl_options(
9641 SpawnedTestServer::SSLOptions::CERT_AUTO);
9642 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9643 ssl_options.staple_ocsp_response = true;
9644 ssl_options.ocsp_server_unavailable = true;
9645
9646 CertStatus cert_status;
9647 DoConnection(ssl_options, &cert_status);
9648
9649 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9650
9651 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9652 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9653
9654 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9655}
9656
davidben6c3191b2014-11-21 22:38:049657// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489658#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049659#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9660#else
9661#define MAYBE_RevokedStapled RevokedStapled
9662#endif
9663TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039664 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009665 LOG(WARNING)
9666 << "Skipping test because system doesn't support OCSP stapling";
9667 return;
9668 }
9669
9670 SpawnedTestServer::SSLOptions ssl_options(
9671 SpawnedTestServer::SSLOptions::CERT_AUTO);
9672 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9673 ssl_options.staple_ocsp_response = true;
9674 ssl_options.ocsp_server_unavailable = true;
9675
9676 CertStatus cert_status;
9677 DoConnection(ssl_options, &cert_status);
9678
9679 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9680 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9681 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9682}
9683
dadriand476e652016-07-26 21:33:249684TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
9685 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9686 https_test_server.SetSSLConfig(
9687 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9688 https_test_server.ServeFilesFromSourceDirectory(
9689 base::FilePath(kTestFilePath));
9690 ASSERT_TRUE(https_test_server.Start());
9691
9692 // Set up a MockCertVerifier to accept the certificate that the server sends,
9693 // but not provide any OCSP information.
9694 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9695 ASSERT_TRUE(cert);
9696 MockCertVerifier cert_verifier;
9697 CertVerifyResult verify_result;
9698 verify_result.verified_cert = cert;
9699 verify_result.is_issued_by_known_root = true;
9700 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9701 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9702
9703 // Catch the Expect-Staple report.
9704 TransportSecurityState transport_security_state;
9705 MockCertificateReportSender mock_report_sender;
9706 transport_security_state.SetReportSender(&mock_report_sender);
9707
9708 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9709 // that the request can be sent to a site on the Expect-Staple preload list.
9710 MockHostResolver host_resolver;
9711 TestNetworkDelegate network_delegate;
9712 TestURLRequestContext context(true);
9713 context.set_host_resolver(&host_resolver);
9714 context.set_transport_security_state(&transport_security_state);
9715 context.set_network_delegate(&network_delegate);
9716 context.set_cert_verifier(&cert_verifier);
9717 context.Init();
9718
9719 // Now send a request to trigger the violation.
9720 TestDelegate d;
9721 GURL url = https_test_server.GetURL("/");
9722 GURL::Replacements replace_host;
9723 replace_host.SetHostStr(kExpectStapleStaticHostname);
9724 url = url.ReplaceComponents(replace_host);
9725 std::unique_ptr<URLRequest> violating_request(
9726 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9727 violating_request->Start();
9728 base::RunLoop().Run();
9729
9730 // Confirm a report was sent.
9731 EXPECT_FALSE(mock_report_sender.latest_report().empty());
9732 EXPECT_EQ(GURL(kExpectStapleReportURI),
9733 mock_report_sender.latest_report_uri());
9734}
9735
estark13e0b312016-12-22 23:52:329736// Tests that Expect-Staple reports are not sent for connections on which there
9737// is a certificate error.
9738TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
9739 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9740 https_test_server.SetSSLConfig(
9741 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9742 https_test_server.ServeFilesFromSourceDirectory(
9743 base::FilePath(kTestFilePath));
9744 ASSERT_TRUE(https_test_server.Start());
9745
9746 // Set up a MockCertVerifier to report an error for the certificate
9747 // and indicate that there was no stapled OCSP response.
9748 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9749 ASSERT_TRUE(cert);
9750 MockCertVerifier cert_verifier;
9751 CertVerifyResult verify_result;
9752 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
9753 verify_result.verified_cert = cert;
9754 verify_result.is_issued_by_known_root = true;
9755 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9756 cert_verifier.AddResultForCert(cert.get(), verify_result,
9757 ERR_CERT_DATE_INVALID);
9758
9759 // Set up a mock report sender so that the test can check that an
9760 // Expect-Staple report is not sent.
9761 TransportSecurityState transport_security_state;
9762 MockCertificateReportSender mock_report_sender;
9763 transport_security_state.SetReportSender(&mock_report_sender);
9764
9765 TestNetworkDelegate network_delegate;
9766 TestURLRequestContext context(true);
9767
9768 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
9769 MockHostResolver host_resolver;
9770 context.set_host_resolver(&host_resolver);
9771
9772 context.set_transport_security_state(&transport_security_state);
9773 context.set_network_delegate(&network_delegate);
9774 context.set_cert_verifier(&cert_verifier);
9775 context.Init();
9776
9777 // Make a connection to |kExpectStapleStaticHostname|. Because the
9778 // |verify_result| used with the |cert_verifier| will indicate a certificate
9779 // error, an Expect-Staple report should not be sent.
9780 TestDelegate d;
9781 GURL url = https_test_server.GetURL("/");
9782 GURL::Replacements replace_host;
9783 replace_host.SetHostStr(kExpectStapleStaticHostname);
9784 url = url.ReplaceComponents(replace_host);
9785 std::unique_ptr<URLRequest> violating_request(
9786 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9787 violating_request->Start();
9788 base::RunLoop().Run();
9789
9790 // Confirm a report was not sent.
9791 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9792 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9793}
9794
dadriand476e652016-07-26 21:33:249795TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
9796 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9797 https_test_server.SetSSLConfig(
9798 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9799 https_test_server.ServeFilesFromSourceDirectory(
9800 base::FilePath(kTestFilePath));
9801 ASSERT_TRUE(https_test_server.Start());
9802
9803 // Set up a MockCertVerifier to accept the certificate that the server sends,
9804 // and provide GOOD revocation status.
9805 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9806 ASSERT_TRUE(cert);
9807 MockCertVerifier cert_verifier;
9808 CertVerifyResult verify_result;
9809 verify_result.verified_cert = cert;
9810 verify_result.is_issued_by_known_root = true;
9811 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
9812 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
9813 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9814
9815 // Catch the Expect-Staple report.
9816 TransportSecurityState transport_security_state;
9817 MockCertificateReportSender mock_report_sender;
9818 transport_security_state.SetReportSender(&mock_report_sender);
9819
9820 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9821 // that the request can be sent to a site on the Expect-Staple preload list.
9822 MockHostResolver host_resolver;
9823 TestNetworkDelegate network_delegate;
9824 TestURLRequestContext context(true);
9825 context.set_host_resolver(&host_resolver);
9826 context.set_transport_security_state(&transport_security_state);
9827 context.set_network_delegate(&network_delegate);
9828 context.set_cert_verifier(&cert_verifier);
9829 context.Init();
9830
9831 // This request should not not trigger an Expect-Staple violation.
9832 TestDelegate d;
9833 GURL url = https_test_server.GetURL("/");
9834 GURL::Replacements replace_host;
9835 replace_host.SetHostStr(kExpectStapleStaticHostname);
9836 url = url.ReplaceComponents(replace_host);
9837 std::unique_ptr<URLRequest> ok_request(
9838 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9839 ok_request->Start();
9840 base::RunLoop().Run();
9841
9842 // Check that no report was sent.
9843 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9844 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9845}
9846
estark13e0b312016-12-22 23:52:329847// Tests that an Expect-Staple report is not sent when OCSP details are not
9848// checked on the connection.
9849TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
9850 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9851 https_test_server.SetSSLConfig(
9852 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9853 https_test_server.ServeFilesFromSourceDirectory(
9854 base::FilePath(kTestFilePath));
9855 ASSERT_TRUE(https_test_server.Start());
9856
9857 // Set up a MockCertVerifier to accept the certificate that the server sends,
9858 // and set |ocsp_result| to indicate that OCSP stapling details were not
9859 // checked on the connection.
9860 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9861 ASSERT_TRUE(cert);
9862 MockCertVerifier cert_verifier;
9863 CertVerifyResult verify_result;
9864 verify_result.verified_cert = cert;
9865 verify_result.is_issued_by_known_root = true;
9866 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
9867 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9868
9869 // Set up a mock report sender so that the test can check that an
9870 // Expect-Staple report is not sent.
9871 TransportSecurityState transport_security_state;
9872 MockCertificateReportSender mock_report_sender;
9873 transport_security_state.SetReportSender(&mock_report_sender);
9874
9875 TestNetworkDelegate network_delegate;
9876 TestURLRequestContext context(true);
9877
9878 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
9879 MockHostResolver host_resolver;
9880 context.set_host_resolver(&host_resolver);
9881
9882 context.set_transport_security_state(&transport_security_state);
9883 context.set_network_delegate(&network_delegate);
9884 context.set_cert_verifier(&cert_verifier);
9885 context.Init();
9886
9887 // Make a connection to |kExpectStapleStaticHostname|. Because the
9888 // |verify_result| used with the |cert_verifier| will indicate that OCSP
9889 // stapling details were not checked on the connection, an Expect-Staple
9890 // report should not be sent.
9891 TestDelegate d;
9892 GURL url = https_test_server.GetURL("/");
9893 GURL::Replacements replace_host;
9894 replace_host.SetHostStr(kExpectStapleStaticHostname);
9895 url = url.ReplaceComponents(replace_host);
9896 std::unique_ptr<URLRequest> ok_request(
9897 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9898 ok_request->Start();
9899 base::RunLoop().Run();
9900
9901 // Check that no report was sent.
9902 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9903 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9904}
9905
dadrian612337a2016-07-20 22:36:589906static const struct OCSPVerifyTestData {
9907 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
9908 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
9909 OCSPVerifyResult::ResponseStatus response_status;
9910 bool has_revocation_status;
9911 OCSPRevocationStatus cert_status;
9912} kOCSPVerifyData[] = {
9913
9914 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9915 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9916 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9917 OCSPVerifyResult::PROVIDED,
9918 true,
9919 OCSPRevocationStatus::GOOD},
9920
9921 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9922 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9923 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9924 OCSPVerifyResult::INVALID_DATE,
9925 false,
9926 OCSPRevocationStatus::UNKNOWN},
9927
9928 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9929 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9930 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9931 OCSPVerifyResult::INVALID_DATE,
9932 false,
9933 OCSPRevocationStatus::UNKNOWN},
9934
9935 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9936 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9937 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9938 OCSPVerifyResult::INVALID_DATE,
9939 false,
9940 OCSPRevocationStatus::UNKNOWN},
9941
9942 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9943 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9944 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9945 OCSPVerifyResult::INVALID_DATE,
9946 false,
9947 OCSPRevocationStatus::UNKNOWN},
9948
9949 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
9950 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9951 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9952 OCSPVerifyResult::ERROR_RESPONSE,
9953 false,
9954 OCSPRevocationStatus::UNKNOWN},
9955
9956 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
9957 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9958 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9959 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
9960 false,
9961 OCSPRevocationStatus::UNKNOWN},
9962
9963 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
9964 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9965 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9966 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
9967 false,
9968 OCSPRevocationStatus::UNKNOWN},
9969
9970 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9971 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9972 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9973 OCSPVerifyResult::INVALID_DATE,
9974 false,
9975 OCSPRevocationStatus::UNKNOWN},
9976
9977 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9978 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9979 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9980 OCSPVerifyResult::PROVIDED,
9981 true,
9982 OCSPRevocationStatus::UNKNOWN},
9983
9984 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9985 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9986 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9987 OCSPVerifyResult::INVALID_DATE,
9988 false,
9989 OCSPRevocationStatus::UNKNOWN},
9990
9991 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9992 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9993 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9994 OCSPVerifyResult::INVALID_DATE,
9995 false,
9996 OCSPRevocationStatus::UNKNOWN},
9997
9998 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9999 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10000 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
10001 OCSPVerifyResult::BAD_PRODUCED_AT,
10002 false,
10003 OCSPRevocationStatus::UNKNOWN},
10004
10005 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10006 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10007 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10008 OCSPVerifyResult::BAD_PRODUCED_AT,
10009 false,
10010 OCSPRevocationStatus::UNKNOWN},
10011
10012 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10013 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10014 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
10015 OCSPVerifyResult::BAD_PRODUCED_AT,
10016 false,
10017 OCSPRevocationStatus::UNKNOWN},
10018
10019 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10020 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10021 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10022 OCSPVerifyResult::PROVIDED,
10023 true,
10024 OCSPRevocationStatus::REVOKED},
10025
10026 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10027 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
10028 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10029 OCSPVerifyResult::INVALID_DATE,
10030 false,
10031 OCSPRevocationStatus::UNKNOWN},
10032
10033 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10034 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10035 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10036 OCSPVerifyResult::INVALID_DATE,
10037 false,
10038 OCSPRevocationStatus::UNKNOWN},
10039
10040 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10041 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10042 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10043 OCSPVerifyResult::PROVIDED,
10044 true,
10045 OCSPRevocationStatus::GOOD},
10046
10047 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10048 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10049 {SpawnedTestServer::SSLOptions::OCSP_OK,
10050 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10051 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10052 OCSPVerifyResult::PROVIDED,
10053 true,
10054 OCSPRevocationStatus::GOOD},
10055
10056 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10057 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10058 {SpawnedTestServer::SSLOptions::OCSP_OK,
10059 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10060 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10061 OCSPVerifyResult::PROVIDED,
10062 true,
10063 OCSPRevocationStatus::GOOD},
10064
10065 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10066 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10067 {SpawnedTestServer::SSLOptions::OCSP_OK,
10068 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10069 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10070 OCSPVerifyResult::PROVIDED,
10071 true,
10072 OCSPRevocationStatus::GOOD},
10073
10074 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
10075 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
10076 {SpawnedTestServer::SSLOptions::OCSP_OK,
10077 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
10078 {SpawnedTestServer::SSLOptions::OCSP_OK,
10079 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
10080 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10081 OCSPVerifyResult::INVALID_DATE,
10082 false,
10083 OCSPRevocationStatus::UNKNOWN},
10084
10085 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10086 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10087 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10088 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10089 {SpawnedTestServer::SSLOptions::OCSP_OK,
10090 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10091 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10092 OCSPVerifyResult::PROVIDED,
10093 true,
10094 OCSPRevocationStatus::REVOKED},
10095
10096 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10097 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10098 {SpawnedTestServer::SSLOptions::OCSP_OK,
10099 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10100 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10101 OCSPVerifyResult::PROVIDED,
10102 true,
10103 OCSPRevocationStatus::UNKNOWN},
10104
10105 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
10106 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
10107 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
10108 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
10109 {SpawnedTestServer::SSLOptions::OCSP_OK,
10110 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10111 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10112 OCSPVerifyResult::PROVIDED,
10113 true,
10114 OCSPRevocationStatus::UNKNOWN},
10115
10116 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10117 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10118 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10119 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10120 false,
10121 OCSPRevocationStatus::UNKNOWN},
10122
10123 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10124 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10125 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10126 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10127 false,
10128 OCSPRevocationStatus::UNKNOWN},
10129
10130};
10131
10132class HTTPSOCSPVerifyTest
10133 : public HTTPSOCSPTest,
10134 public testing::WithParamInterface<OCSPVerifyTestData> {};
10135
10136TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10137 SpawnedTestServer::SSLOptions ssl_options(
10138 SpawnedTestServer::SSLOptions::CERT_AUTO);
10139 OCSPVerifyTestData test = GetParam();
10140
10141 ssl_options.ocsp_responses = test.ocsp_responses;
10142 ssl_options.ocsp_produced = test.ocsp_produced;
10143 ssl_options.staple_ocsp_response = true;
10144
10145 SSLInfo ssl_info;
10146 OCSPErrorTestDelegate delegate;
10147 ASSERT_NO_FATAL_FAILURE(
10148 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10149
10150 // The SSLInfo must be extracted from |delegate| on error, due to how
10151 // URLRequest caches certificate errors.
10152 if (delegate.have_certificate_errors()) {
10153 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10154 ssl_info = delegate.ssl_info();
10155 }
10156
10157 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10158
10159 if (test.has_revocation_status)
10160 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
10161}
10162
10163INSTANTIATE_TEST_CASE_P(OCSPVerify,
10164 HTTPSOCSPVerifyTest,
10165 testing::ValuesIn(kOCSPVerifyData));
10166
mattm0b12a6f2016-11-29 19:57:1610167static bool SystemSupportsAIA() {
10168#if defined(OS_ANDROID)
10169 return false;
10170#else
10171 return true;
10172#endif
10173}
10174
10175class HTTPSAIATest : public HTTPSOCSPTest {
10176 public:
10177 void SetupContext() override {
10178 context_.set_ssl_config_service(new TestSSLConfigService(
10179 false /* check for EV */, false /* online revocation checking */,
10180 false /* require rev. checking for local anchors */,
10181 false /* token binding enabled */));
10182 }
10183};
10184
10185TEST_F(HTTPSAIATest, AIAFetching) {
10186 SpawnedTestServer::SSLOptions ssl_options(
10187 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
10188 SpawnedTestServer test_server(
10189 SpawnedTestServer::TYPE_HTTPS, ssl_options,
10190 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10191 ASSERT_TRUE(test_server.Start());
10192
10193 TestDelegate d;
10194 d.set_allow_certificate_errors(true);
10195 std::unique_ptr<URLRequest> r(context_.CreateRequest(
10196 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
10197
10198 r->Start();
10199 EXPECT_TRUE(r->is_pending());
10200
10201 base::RunLoop().Run();
10202
10203 EXPECT_EQ(1, d.response_started_count());
10204
10205 CertStatus cert_status = r->ssl_info().cert_status;
10206 if (SystemSupportsAIA()) {
10207 EXPECT_EQ(OK, d.request_status());
10208 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10209 ASSERT_TRUE(r->ssl_info().cert);
10210 EXPECT_EQ(2u, r->ssl_info().cert->GetIntermediateCertificates().size());
10211 } else {
10212 EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID,
10213 cert_status & CERT_STATUS_ALL_ERRORS);
10214 }
10215 ASSERT_TRUE(r->ssl_info().unverified_cert);
10216 EXPECT_EQ(
10217 0u, r->ssl_info().unverified_cert->GetIntermediateCertificates().size());
10218}
10219
[email protected]3a86a712013-07-30 07:16:2010220class HTTPSHardFailTest : public HTTPSOCSPTest {
10221 protected:
rsleevid6de8302016-06-21 01:33:2010222 void SetupContext() override {
10223 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410224 false /* check for EV */, false /* online revocation checking */,
10225 true /* require rev. checking for local
10226 anchors */,
10227 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2010228 }
10229};
10230
[email protected]3a86a712013-07-30 07:16:2010231TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
10232 if (!SystemSupportsOCSP()) {
10233 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10234 return;
10235 }
10236
10237 if (!SystemSupportsHardFailRevocationChecking()) {
10238 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
10239 << "revocation checking";
10240 return;
10241 }
10242
10243 SpawnedTestServer::SSLOptions ssl_options(
10244 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810245 ssl_options.ocsp_status =
10246 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2010247
10248 CertStatus cert_status;
10249 DoConnection(ssl_options, &cert_status);
10250
10251 EXPECT_EQ(CERT_STATUS_REVOKED,
10252 cert_status & CERT_STATUS_REVOKED);
10253
10254 // Without a positive OCSP response, we shouldn't show the EV status.
10255 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10256}
10257
[email protected]a13234c2012-03-20 21:45:0210258class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
10259 protected:
rsleevid6de8302016-06-21 01:33:2010260 void SetupContext() override {
10261 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410262 true /* check for EV */, false /* online revocation checking */,
10263 false /* require rev. checking for local
10264 anchors */,
10265 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210266 }
10267};
10268
10269TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
10270 if (!SystemSupportsOCSP()) {
10271 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10272 return;
10273 }
10274
[email protected]ce7d0cbc2013-05-03 18:57:2210275 SpawnedTestServer::SSLOptions ssl_options(
10276 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810277 ssl_options.ocsp_status =
10278 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210279 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10280
[email protected]924e9f92012-12-16 22:00:5310281 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210282 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210283
mattmaf868e72016-09-23 23:25:2010284 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210285 cert_status & CERT_STATUS_ALL_ERRORS);
10286
10287 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810288 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10289 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210290}
10291
[email protected]be0fff62013-08-29 23:37:4810292TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
10293 if (!SystemSupportsOCSP()) {
10294 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10295 return;
10296 }
10297
10298 SpawnedTestServer::SSLOptions ssl_options(
10299 SpawnedTestServer::SSLOptions::CERT_AUTO);
10300 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10301 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10302
10303 CertStatus cert_status;
10304 DoConnection(ssl_options, &cert_status);
10305
mattm1a282f52016-11-10 21:49:4210306// Currently only works for Windows and OS X. When using NSS, it's not
10307// possible to determine whether the check failed because of actual
10308// revocation or because there was an OCSP failure.
10309#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4810310 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10311#else
10312 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10313#endif
10314
10315 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10316 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10317 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10318}
10319
[email protected]a13234c2012-03-20 21:45:0210320TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
10321 if (!SystemSupportsOCSP()) {
10322 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10323 return;
10324 }
10325
[email protected]ce7d0cbc2013-05-03 18:57:2210326 SpawnedTestServer::SSLOptions ssl_options(
10327 SpawnedTestServer::SSLOptions::CERT_AUTO);
10328 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0210329 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10330
10331 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210332 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210333
10334 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10335
10336 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10337 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0810338 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10339 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210340}
10341
10342TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
10343 if (!SystemSupportsOCSP()) {
10344 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10345 return;
10346 }
10347
[email protected]ce7d0cbc2013-05-03 18:57:2210348 SpawnedTestServer::SSLOptions ssl_options(
10349 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810350 ssl_options.ocsp_status =
10351 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210352 SSLConfigService::SetCRLSet(
10353 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10354
10355 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210356 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210357
mattmaf868e72016-09-23 23:25:2010358 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210359 cert_status & CERT_STATUS_ALL_ERRORS);
10360
10361 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810362 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10363 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210364}
10365
[email protected]51523f52013-07-31 21:57:2810366TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
10367 if (!SystemSupportsOCSP()) {
10368 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10369 return;
10370 }
10371
10372 SpawnedTestServer::SSLOptions ssl_options(
10373 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810374 ssl_options.ocsp_status =
10375 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:2810376 SSLConfigService::SetCRLSet(
10377 scoped_refptr<CRLSet>(CRLSet::ForTesting(
10378 false, &kOCSPTestCertSPKI, "")));
10379
10380 CertStatus cert_status;
10381 DoConnection(ssl_options, &cert_status);
10382
10383 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
10384 // revocation check for EV.
10385 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10386 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10387 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10388 EXPECT_FALSE(
10389 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10390}
10391
10392TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
10393 if (!SystemSupportsOCSP()) {
10394 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10395 return;
10396 }
10397
[email protected]ce7d0cbc2013-05-03 18:57:2210398 SpawnedTestServer::SSLOptions ssl_options(
10399 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810400 ssl_options.ocsp_status =
10401 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210402 SSLConfigService::SetCRLSet(
10403 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
10404
[email protected]51523f52013-07-31 21:57:2810405 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1210406 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210407
[email protected]51523f52013-07-31 21:57:2810408 // Even with a fresh CRLSet, we should still do online revocation checks when
10409 // the certificate chain isn't covered by the CRLSet, which it isn't in this
10410 // test.
mattmaf868e72016-09-23 23:25:2010411 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2810412 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0210413
[email protected]51523f52013-07-31 21:57:2810414 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0210415 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2810416 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210417}
10418
[email protected]b6f2de32012-08-17 04:35:0810419TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
10420 // Test that when EV verification is requested, but online revocation
10421 // checking is disabled, and the leaf certificate is not in fact EV, that
10422 // no revocation checking actually happens.
10423 if (!SystemSupportsOCSP()) {
10424 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10425 return;
10426 }
10427
10428 // Unmark the certificate's OID as EV, which should disable revocation
10429 // checking (as per the user preference)
10430 ev_test_policy_.reset();
10431
[email protected]ce7d0cbc2013-05-03 18:57:2210432 SpawnedTestServer::SSLOptions ssl_options(
10433 SpawnedTestServer::SSLOptions::CERT_AUTO);
10434 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:0810435 SSLConfigService::SetCRLSet(
10436 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10437
10438 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210439 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:0810440
10441 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10442
10443 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10444 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10445}
10446
[email protected]a13234c2012-03-20 21:45:0210447class HTTPSCRLSetTest : public HTTPSOCSPTest {
10448 protected:
rsleevid6de8302016-06-21 01:33:2010449 void SetupContext() override {
10450 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410451 false /* check for EV */, false /* online revocation checking */,
10452 false /* require rev. checking for local
10453 anchors */,
10454 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210455 }
10456};
10457
10458TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2210459 SpawnedTestServer::SSLOptions ssl_options(
10460 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810461 ssl_options.ocsp_status =
10462 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210463 SSLConfigService::SetCRLSet(
10464 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10465
[email protected]924e9f92012-12-16 22:00:5310466 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210467 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210468
10469 // If we're not trying EV verification then, even if the CRLSet has expired,
10470 // we don't fall back to online revocation checks.
10471 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10472 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10473 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10474}
[email protected]51523f52013-07-31 21:57:2810475
10476TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:3010477#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2810478 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
10479 return;
10480#endif
10481
10482 SpawnedTestServer::SSLOptions ssl_options(
10483 SpawnedTestServer::SSLOptions::CERT_AUTO);
10484 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10485 ssl_options.cert_serial = 10;
10486 SSLConfigService::SetCRLSet(
10487 scoped_refptr<CRLSet>(CRLSet::ForTesting(
10488 false, &kOCSPTestCertSPKI, "\x0a")));
10489
10490 CertStatus cert_status = 0;
10491 DoConnection(ssl_options, &cert_status);
10492
10493 // If the certificate is recorded as revoked in the CRLSet, that should be
10494 // reflected without online revocation checking.
10495 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10496 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10497 EXPECT_FALSE(
10498 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10499}
[email protected]316c1e5e2012-09-12 15:17:4410500#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2710501
brettwa1228ebb2016-10-28 03:51:3410502#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:4710503// These tests aren't passing on Android. Either the RemoteTestServer isn't
10504// starting up successfully, or it can't access the test files.
10505// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3110506class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1110507 public:
[email protected]d9fca99a2012-02-24 16:16:2010508 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0510509 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5510510 SpawnedTestServer::kLocalhost,
10511 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4710512 // Can't use |default_context_|'s HostResolver to set up the
10513 // FTPTransactionFactory because it hasn't been created yet.
10514 default_context_.set_host_resolver(&host_resolver_);
10515 }
10516
10517 // URLRequestTest interface:
10518 void SetUpFactory() override {
10519 // Add FTP support to the default URLRequestContext.
10520 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0510521 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4710522 }
10523
10524 std::string GetTestFileContents() {
10525 base::FilePath path;
10526 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
10527 path = path.Append(kTestFilePath);
10528 path = path.AppendASCII(kFtpTestFile);
10529 std::string contents;
10530 EXPECT_TRUE(base::ReadFileToString(path, &contents));
10531 return contents;
[email protected]95409e12010-08-17 20:07:1110532 }
10533
[email protected]b89ca032009-08-31 21:41:3110534 protected:
mmenkecd4c7532016-10-19 18:36:0510535 // Note that this is destroyed before the FtpProtocolHandler that references
10536 // it, which is owned by the parent class. Since no requests are made during
10537 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4710538 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4710539
tommycli59a63432015-11-06 00:10:5510540 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3110541};
10542
[email protected]d2a133182012-08-05 16:44:0810543// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0910544TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0810545 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0810546
10547 TestDelegate d;
10548 {
danakj8522a25b2016-04-16 00:17:3610549 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:3610550 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910551 r->Start();
10552 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0810553
[email protected]255620da2013-08-19 13:14:2910554 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0810555
[email protected]f7022f32014-08-21 16:32:1910556 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5010557 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0810558 }
10559}
10560
mmenke9f2ec60c2015-06-01 20:59:4710561TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5510562 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110563
[email protected]a25e90e2009-09-09 17:05:3710564 TestDelegate d;
10565 {
danakj8522a25b2016-04-16 00:17:3610566 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510567 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910568 r->Start();
10569 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3710570
[email protected]255620da2013-08-19 13:14:2910571 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3710572
[email protected]f7022f32014-08-21 16:32:1910573 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3710574 EXPECT_EQ(1, d.response_started_count());
10575 EXPECT_FALSE(d.received_data_before_response());
10576 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5510577 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910578 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510579 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910580 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3710581 }
10582}
10583
mmenke9f2ec60c2015-06-01 20:59:4710584TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5510585 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110586
[email protected]dd265012009-01-08 20:45:2710587 TestDelegate d;
10588 {
danakj8522a25b2016-04-16 00:17:3610589 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510590 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910591 r->Start();
10592 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710593
[email protected]255620da2013-08-19 13:14:2910594 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710595
[email protected]f7022f32014-08-21 16:32:1910596 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710597 EXPECT_EQ(1, d.response_started_count());
10598 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710599 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5510600 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910601 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510602 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910603 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2710604 }
10605}
10606
mmenke9f2ec60c2015-06-01 20:59:4710607TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5510608 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110609
[email protected]dd265012009-01-08 20:45:2710610 TestDelegate d;
10611 {
danakj8522a25b2016-04-16 00:17:3610612 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510613 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10614 "chrome"),
10615 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910616 r->Start();
10617 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710618
[email protected]255620da2013-08-19 13:14:2910619 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710620
[email protected]f7022f32014-08-21 16:32:1910621 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4710622 EXPECT_EQ(1, d.response_started_count());
10623 EXPECT_FALSE(d.received_data_before_response());
10624 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5510625 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910626 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510627 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910628 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2510629
10630 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1910631 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2510632 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2710633 }
10634}
10635
mmenke9f2ec60c2015-06-01 20:59:4710636TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5510637 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110638
[email protected]dd265012009-01-08 20:45:2710639 TestDelegate d;
10640 {
danakj8522a25b2016-04-16 00:17:3610641 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510642 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10643 "wrong_password"),
davidben151423e2015-03-23 18:48:3610644 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910645 r->Start();
10646 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710647
[email protected]255620da2013-08-19 13:14:2910648 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710649
[email protected]f7022f32014-08-21 16:32:1910650 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710651 EXPECT_EQ(1, d.response_started_count());
10652 EXPECT_FALSE(d.received_data_before_response());
10653 EXPECT_EQ(d.bytes_received(), 0);
10654 }
10655}
10656
mmenke9f2ec60c2015-06-01 20:59:4710657TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5510658 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110659
[email protected]8b8a197d2009-08-26 15:57:5810660 TestDelegate d;
10661 // Set correct login credentials. The delegate will be asked for them when
10662 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810663 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810664 {
danakj8522a25b2016-04-16 00:17:3610665 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510666 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10667 "wrong_password"),
davidben151423e2015-03-23 18:48:3610668 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910669 r->Start();
10670 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810671
[email protected]255620da2013-08-19 13:14:2910672 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810673
[email protected]f7022f32014-08-21 16:32:1910674 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810675 EXPECT_EQ(1, d.response_started_count());
10676 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710677 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810678 }
10679}
10680
mmenke9f2ec60c2015-06-01 20:59:4710681TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5510682 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110683
[email protected]dd265012009-01-08 20:45:2710684 TestDelegate d;
10685 {
danakj8522a25b2016-04-16 00:17:3610686 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510687 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10688 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710689 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910690 r->Start();
10691 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710692
[email protected]255620da2013-08-19 13:14:2910693 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710694
[email protected]f7022f32014-08-21 16:32:1910695 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710696 EXPECT_EQ(1, d.response_started_count());
10697 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710698 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2710699 }
10700}
[email protected]8b8a197d2009-08-26 15:57:5810701
mmenke9f2ec60c2015-06-01 20:59:4710702TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5510703 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110704
[email protected]8b8a197d2009-08-26 15:57:5810705 TestDelegate d;
10706 // Set correct login credentials. The delegate will be asked for them when
10707 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810708 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810709 {
danakj8522a25b2016-04-16 00:17:3610710 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510711 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10712 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710713 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910714 r->Start();
10715 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810716
[email protected]255620da2013-08-19 13:14:2910717 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810718
[email protected]f7022f32014-08-21 16:32:1910719 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810720 EXPECT_EQ(1, d.response_started_count());
10721 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710722 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810723 }
10724}
[email protected]60a3df52009-09-22 16:13:2410725
mmenke9f2ec60c2015-06-01 20:59:4710726TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510727 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110728
danakj8522a25b2016-04-16 00:17:3610729 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410730 {
10731 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610732 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510733 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10734 "chrome"),
10735 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910736 r->Start();
10737 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410738
[email protected]255620da2013-08-19 13:14:2910739 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410740
[email protected]f7022f32014-08-21 16:32:1910741 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410742 EXPECT_EQ(1, d->response_started_count());
10743 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710744 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410745 }
10746
10747 d.reset(new TestDelegate);
10748 {
10749 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610750 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510751 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910752 r->Start();
10753 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410754
[email protected]255620da2013-08-19 13:14:2910755 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410756
[email protected]f7022f32014-08-21 16:32:1910757 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410758 EXPECT_EQ(1, d->response_started_count());
10759 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710760 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410761 }
10762}
10763
mmenke9f2ec60c2015-06-01 20:59:4710764TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510765 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110766
danakj8522a25b2016-04-16 00:17:3610767 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410768 // Set correct login credentials. The delegate will be asked for them when
10769 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810770 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410771 {
danakj8522a25b2016-04-16 00:17:3610772 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510773 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10774 "wrong_password"),
davidben151423e2015-03-23 18:48:3610775 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910776 r->Start();
10777 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410778
[email protected]255620da2013-08-19 13:14:2910779 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410780
[email protected]f7022f32014-08-21 16:32:1910781 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410782 EXPECT_EQ(1, d->response_started_count());
10783 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710784 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410785 }
10786
10787 // Use a new delegate without explicit credentials. The cached ones should be
10788 // used.
10789 d.reset(new TestDelegate);
10790 {
10791 // Don't pass wrong credentials in the URL, they would override valid cached
10792 // ones.
danakj8522a25b2016-04-16 00:17:3610793 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510794 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910795 r->Start();
10796 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410797
[email protected]255620da2013-08-19 13:14:2910798 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410799
[email protected]f7022f32014-08-21 16:32:1910800 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410801 EXPECT_EQ(1, d->response_started_count());
10802 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710803 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410804 }
10805}
ricea3a1c71f2016-06-17 10:05:2610806
10807TEST_F(URLRequestTestFTP, RawBodyBytes) {
10808 ASSERT_TRUE(ftp_test_server_.Start());
10809
10810 TestDelegate d;
10811 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10812 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10813 req->Start();
10814 base::RunLoop().Run();
10815
10816 EXPECT_EQ(6, req->GetRawBodyBytes());
10817}
10818
brettwa1228ebb2016-10-28 03:51:3410819#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110820
ttuttlec0c828492015-05-15 01:25:5510821TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10822 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610823 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510824 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10825
10826 EXPECT_FALSE(req->response_info().network_accessed);
10827
10828 req->Start();
10829 base::RunLoop().Run();
10830
10831 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10832 EXPECT_FALSE(req->response_info().network_accessed);
10833}
10834
10835TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10836 MockHostResolver host_resolver;
10837 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10838 TestURLRequestContext context(true);
10839 context.set_network_delegate(&network_delegate);
10840 context.set_host_resolver(&host_resolver);
10841 host_resolver.rules()->AddSimulatedFailure("*");
10842 context.Init();
10843
10844 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610845 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510846 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10847
10848 EXPECT_FALSE(req->response_info().network_accessed);
10849
10850 req->Start();
10851 base::RunLoop().Run();
10852 EXPECT_TRUE(req->response_info().network_accessed);
10853}
10854
mmenkeed0498b2015-12-08 23:20:4210855// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210856// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210857TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210858 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610859 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210860 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10861
danakj8522a25b2016-04-16 00:17:3610862 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210863 req.get(), &default_network_delegate_,
10864 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210865 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10866 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210867
10868 req->Start();
10869 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210870 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5010871 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2210872 EXPECT_EQ(0, d.received_redirect_count());
10873}
10874
[email protected]7461a402011-03-24 23:19:5110875} // namespace net