blob: e5c941f48b2c3098d04697f08b7446c4aa3f9126 [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"
gabf767595f2016-05-11 18:50:3546#include "base/threading/thread_task_runner_handle.h"
estark06e0dac2015-08-07 21:56:0147#include "base/values.h"
mmenkecbc2b712014-10-09 20:29:0748#include "net/base/chunked_upload_data_stream.h"
tfarina43a416b2016-01-06 21:48:0749#include "net/base/directory_listing.h"
mmenkecbc2b712014-10-09 20:29:0750#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2552#include "net/base/load_timing_info.h"
53#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0654#include "net/base/net_errors.h"
initial.commit586acc5fe2008-07-26 22:42:5255#include "net/base/net_module.h"
[email protected]2ca01e52013-10-31 22:05:1956#include "net/base/request_priority.h"
[email protected]f288ef02012-12-15 20:28:2857#include "net/base/upload_bytes_element_reader.h"
58#include "net/base/upload_data_stream.h"
59#include "net/base/upload_file_element_reader.h"
tfarina7a4a7fd2016-01-20 14:23:4460#include "net/base/url_util.h"
rsleevid6de8302016-06-21 01:33:2061#include "net/cert/ct_policy_enforcer.h"
estark1614475f2016-03-10 03:46:4762#include "net/cert/ct_policy_status.h"
rsleevi22cae1672016-12-28 01:53:3663#include "net/cert/do_nothing_ct_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1164#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2465#include "net/cert/mock_cert_verifier.h"
eranmdcec9632016-10-10 14:16:1066#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1167#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4968#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0669#include "net/cookies/cookie_monster.h"
70#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5271#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5372#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3873#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5274#include "net/http/http_cache.h"
75#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1976#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2577#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2178#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0079#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0080#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1981#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5182#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4683#include "net/log/test_net_log_entry.h"
84#include "net/log/test_net_log_util.h"
brettwa1228ebb2016-10-28 03:51:3485#include "net/net_features.h"
tbansalca83c002016-04-28 20:56:2886#include "net/nqe/external_estimate_provider.h"
tbansal2ecbbc72016-10-06 17:15:4787#include "net/proxy/proxy_server.h"
[email protected]63de95b2008-12-10 04:11:2788#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1989#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1490#include "net/ssl/channel_id_service.h"
91#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:5792#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:5593#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:1494#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:1195#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3696#include "net/test/embedded_test_server/embedded_test_server.h"
97#include "net/test/embedded_test_server/http_request.h"
98#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:0199#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:21100#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43101#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:50102#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:34103#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43104#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52105#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50106#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14107#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50108#include "net/url_request/url_request_intercepting_job_factory.h"
109#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49110#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51111#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47112#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44113#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01114#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52115#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15116#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52117
brettwa1228ebb2016-10-28 03:51:34118#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55119#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29120#include "net/url_request/file_protocol_handler.h"
121#include "net/url_request/url_request_file_dir_job.h"
122#endif
123
brettwa1228ebb2016-10-28 03:51:34124#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47125#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29126#include "net/url_request/ftp_protocol_handler.h"
127#endif
128
[email protected]dffe8242012-03-20 15:14:27129#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48130#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56131#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27132#endif
133
robpercival214763f2016-07-01 23:27:01134using net::test::IsError;
135using net::test::IsOk;
136
[email protected]ad65a3e2013-12-25 18:18:01137using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33138using base::Time;
halton.huoe4e45742014-12-08 07:55:46139using std::string;
[email protected]e1acf6f2008-10-27 20:43:33140
[email protected]7461a402011-03-24 23:19:51141namespace net {
142
initial.commit586acc5fe2008-07-26 22:42:52143namespace {
144
[email protected]42cba2fb2013-03-29 19:58:57145const base::string16 kChrome(ASCIIToUTF16("chrome"));
146const base::string16 kSecret(ASCIIToUTF16("secret"));
147const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44148
mmenke9f2ec60c2015-06-01 20:59:47149const base::FilePath::CharType kTestFilePath[] =
150 FILE_PATH_LITERAL("net/data/url_request_unittest");
151
brettwa1228ebb2016-10-28 03:51:34152#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:47153// Test file used in most FTP tests.
154const char kFtpTestFile[] = "BullRunSpeech.txt";
155#endif
156
[email protected]2bba3252013-04-08 19:50:59157// Tests load timing information in the case a fresh connection was used, with
158// no proxy.
[email protected]cba24642014-08-15 20:49:59159void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25160 int connect_timing_flags) {
161 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19162 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25163
164 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165 EXPECT_FALSE(load_timing_info.request_start.is_null());
166
167 EXPECT_LE(load_timing_info.request_start,
168 load_timing_info.connect_timing.connect_start);
169 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
170 connect_timing_flags);
171 EXPECT_LE(load_timing_info.connect_timing.connect_end,
172 load_timing_info.send_start);
173 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
174 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
175
[email protected]58e32bb2013-01-21 18:23:25176 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
177 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
178}
179
[email protected]2bba3252013-04-08 19:50:59180// Same as above, but with proxy times.
181void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59182 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59183 int connect_timing_flags) {
184 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19185 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59186
187 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
188 EXPECT_FALSE(load_timing_info.request_start.is_null());
189
190 EXPECT_LE(load_timing_info.request_start,
191 load_timing_info.proxy_resolve_start);
192 EXPECT_LE(load_timing_info.proxy_resolve_start,
193 load_timing_info.proxy_resolve_end);
194 EXPECT_LE(load_timing_info.proxy_resolve_end,
195 load_timing_info.connect_timing.connect_start);
196 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
197 connect_timing_flags);
198 EXPECT_LE(load_timing_info.connect_timing.connect_end,
199 load_timing_info.send_start);
200 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
201 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
202}
203
204// Same as above, but with a reused socket and proxy times.
205void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59206 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59207 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19208 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59209
210 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
211 EXPECT_FALSE(load_timing_info.request_start.is_null());
212
213 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
214
215 EXPECT_LE(load_timing_info.request_start,
216 load_timing_info.proxy_resolve_start);
217 EXPECT_LE(load_timing_info.proxy_resolve_start,
218 load_timing_info.proxy_resolve_end);
219 EXPECT_LE(load_timing_info.proxy_resolve_end,
220 load_timing_info.send_start);
221 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
222 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
223}
224
brettwa1228ebb2016-10-28 03:51:34225#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25226// Tests load timing information in the case of a cache hit, when no cache
227// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17228base::StringPiece TestNetResourceProvider(int key) {
229 return "header";
230}
231
232void FillBuffer(char* buffer, size_t len) {
233 static bool called = false;
234 if (!called) {
235 called = true;
236 int seed = static_cast<int>(Time::Now().ToInternalValue());
237 srand(seed);
238 }
239
240 for (size_t i = 0; i < len; i++) {
241 buffer[i] = static_cast<char>(rand());
242 if (!buffer[i])
243 buffer[i] = 'g';
244 }
245}
xunjielia6888202015-04-14 21:34:25246#endif
[email protected]e3a85452013-11-14 01:46:17247
[email protected]3b23a222013-05-15 21:33:25248void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59249 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25250 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19251 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25252
253 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
254 EXPECT_FALSE(load_timing_info.request_start.is_null());
255
256 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
257 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
258 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
259 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
260
261 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
262 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
263}
264
brettwa1228ebb2016-10-28 03:51:34265#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25266// Tests load timing in the case that there is no HTTP response. This can be
267// used to test in the case of errors or non-HTTP requests.
268void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59269 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25270 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19271 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25272
273 // Only the request times should be non-null.
274 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
275 EXPECT_FALSE(load_timing_info.request_start.is_null());
276
277 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
278
279 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
280 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
281 EXPECT_TRUE(load_timing_info.send_start.is_null());
282 EXPECT_TRUE(load_timing_info.send_end.is_null());
283 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
284}
xunjielia6888202015-04-14 21:34:25285#endif
[email protected]58e32bb2013-01-21 18:23:25286
mmenkefb18c772015-09-30 22:22:50287// Test power monitor source that can simulate entering suspend mode. Can't use
288// the one in base/ because it insists on bringing its own MessageLoop.
289class TestPowerMonitorSource : public base::PowerMonitorSource {
290 public:
291 TestPowerMonitorSource() {}
292 ~TestPowerMonitorSource() override {}
293
294 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
295
296 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
297
298 bool IsOnBatteryPowerImpl() override { return false; }
299
300 private:
301 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
302};
303
mmenkeed0498b2015-12-08 23:20:42304// Job that allows monitoring of its priority.
305class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
306 public:
307 // The latest priority of the job is always written to |request_priority_|.
308 PriorityMonitoringURLRequestJob(URLRequest* request,
309 NetworkDelegate* network_delegate,
310 RequestPriority* request_priority)
311 : URLRequestTestJob(request, network_delegate),
312 request_priority_(request_priority) {
313 *request_priority_ = DEFAULT_PRIORITY;
314 }
315
316 void SetPriority(RequestPriority priority) override {
317 *request_priority_ = priority;
318 URLRequestTestJob::SetPriority(priority);
319 }
320
321 private:
322 RequestPriority* const request_priority_;
323};
324
[email protected]71c64f62008-11-15 04:36:51325// Do a case-insensitive search through |haystack| for |needle|.
326bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50327 std::string::const_iterator it = std::search(
328 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
329 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51330 return it != haystack.end();
331}
332
danakj8522a25b2016-04-16 00:17:36333std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
334 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28335 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48336 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23337}
338
[email protected]96adadb2010-08-28 01:16:17339// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51340void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17341 // -1 means unknown. 0 means no encryption.
342 EXPECT_GT(ssl_info.security_bits, 0);
343
344 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14345 uint16_t cipher_suite =
346 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29347 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17348}
349
[email protected]79e1fd62013-06-20 06:50:04350void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
351 const GURL& host_url) {
352 std::string sent_value;
353
354 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
355 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
356
357 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
358 EXPECT_EQ("keep-alive", sent_value);
359}
360
[email protected]dc5a5cf2012-09-26 02:49:30361// A network delegate that allows the user to choose a subset of request stages
362// to block in. When blocking, the delegate can do one of the following:
363// * synchronously return a pre-specified error code, or
364// * asynchronously return that value via an automatically called callback,
365// or
366// * block and wait for the user to do a callback.
367// Additionally, the user may also specify a redirect URL -- then each request
368// with the current URL different from the redirect target will be redirected
369// to that target, in the on-before-URL-request stage, independent of whether
370// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12371class BlockingNetworkDelegate : public TestNetworkDelegate {
372 public:
[email protected]dc5a5cf2012-09-26 02:49:30373 // Stages in which the delegate can block.
374 enum Stage {
[email protected]9045b8822012-01-13 20:35:35375 NOT_BLOCKED = 0,
376 ON_BEFORE_URL_REQUEST = 1 << 0,
377 ON_BEFORE_SEND_HEADERS = 1 << 1,
378 ON_HEADERS_RECEIVED = 1 << 2,
379 ON_AUTH_REQUIRED = 1 << 3
380 };
381
[email protected]dc5a5cf2012-09-26 02:49:30382 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59383 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30384 enum BlockMode {
385 SYNCHRONOUS, // No callback, returns specified return values.
386 AUTO_CALLBACK, // |this| posts a task to run the callback using the
387 // specified return codes.
388 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
389 // |auth_retval_| are ignored. In every blocking stage the
390 // message loop is quit.
rdsmithbf8c3c12016-11-18 18:16:24391 USER_NOTIFY, // User is notified by a provided callback of the
392 // blocking, and synchronously returns instructions
393 // for handling it.
[email protected]dc5a5cf2012-09-26 02:49:30394 };
395
rdsmithbf8c3c12016-11-18 18:16:24396 using NotificationCallback =
397 base::Callback<Error(const CompletionCallback&, const URLRequest*)>;
398
399 using NotificationAuthCallback =
400 base::Callback<NetworkDelegate::AuthRequiredResponse(const AuthCallback&,
401 const URLRequest*)>;
402
[email protected]dc5a5cf2012-09-26 02:49:30403 // Creates a delegate which does not block at all.
404 explicit BlockingNetworkDelegate(BlockMode block_mode);
405
406 // For users to trigger a callback returning |response|.
407 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
408 // Only call if |block_mode_| == USER_CALLBACK.
409 void DoCallback(int response);
410 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
411
412 // Setters.
413 void set_retval(int retval) {
414 ASSERT_NE(USER_CALLBACK, block_mode_);
415 ASSERT_NE(ERR_IO_PENDING, retval);
416 ASSERT_NE(OK, retval);
417 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35418 }
419
[email protected]dc5a5cf2012-09-26 02:49:30420 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
421 // |auth_credentials_| will be passed with the response.
422 void set_auth_retval(AuthRequiredResponse auth_retval) {
423 ASSERT_NE(USER_CALLBACK, block_mode_);
424 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
425 auth_retval_ = auth_retval;
426 }
427 void set_auth_credentials(const AuthCredentials& auth_credentials) {
428 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35429 }
430
[email protected]dc5a5cf2012-09-26 02:49:30431 void set_redirect_url(const GURL& url) {
432 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35433 }
434
[email protected]dc5a5cf2012-09-26 02:49:30435 void set_block_on(int block_on) {
436 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35437 }
438
rdsmithbf8c3c12016-11-18 18:16:24439 // Only valid if |block_mode_| == USER_NOTIFY
440 void set_notification_callback(
441 const NotificationCallback& notification_callback) {
442 notification_callback_ = notification_callback;
443 }
444
445 void set_notification_auth_callback(
446 const NotificationAuthCallback& notification_auth_callback) {
447 notification_auth_callback_ = notification_auth_callback;
448 }
449
[email protected]dc5a5cf2012-09-26 02:49:30450 // Allows the user to check in which state did we block.
451 Stage stage_blocked_for_callback() const {
452 EXPECT_EQ(USER_CALLBACK, block_mode_);
453 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35454 }
455
456 private:
[email protected]dc5a5cf2012-09-26 02:49:30457 void RunCallback(int response, const CompletionCallback& callback);
458 void RunAuthCallback(AuthRequiredResponse response,
459 const AuthCallback& callback);
460
[email protected]9045b8822012-01-13 20:35:35461 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20462 int OnBeforeURLRequest(URLRequest* request,
463 const CompletionCallback& callback,
464 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35465
ryansturm2343cb62016-06-15 01:09:00466 int OnBeforeStartTransaction(URLRequest* request,
467 const CompletionCallback& callback,
468 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35469
dchengb03027d2014-10-21 12:00:20470 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35471 URLRequest* request,
472 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32473 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16474 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13475 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35476
dchengb03027d2014-10-21 12:00:20477 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35478 URLRequest* request,
479 const AuthChallengeInfo& auth_info,
480 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13481 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35482
[email protected]dc5a5cf2012-09-26 02:49:30483 // Resets the callbacks and |stage_blocked_for_callback_|.
484 void Reset();
[email protected]9045b8822012-01-13 20:35:35485
[email protected]dc5a5cf2012-09-26 02:49:30486 // Checks whether we should block in |stage|. If yes, returns an error code
487 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
rdsmithbf8c3c12016-11-18 18:16:24488 int MaybeBlockStage(Stage stage,
489 const URLRequest* request,
490 const CompletionCallback& callback);
[email protected]dc5a5cf2012-09-26 02:49:30491
492 // Configuration parameters, can be adjusted by public methods:
493 const BlockMode block_mode_;
494
495 // Values returned on blocking stages when mode is SYNCHRONOUS or
496 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
497 int retval_; // To be returned in non-auth stages.
498 AuthRequiredResponse auth_retval_;
499
[email protected]5f714132014-03-26 10:41:16500 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30501 int block_on_; // Bit mask: in which stages to block.
502
503 // |auth_credentials_| will be copied to |*target_auth_credential_| on
504 // callback.
505 AuthCredentials auth_credentials_;
506 AuthCredentials* target_auth_credentials_;
507
508 // Internal variables, not set by not the user:
509 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
510 // USER_CALLBACK).
511 Stage stage_blocked_for_callback_;
512
513 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35514 CompletionCallback callback_;
515 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30516
rdsmithbf8c3c12016-11-18 18:16:24517 // Callback to request user instructions for blocking.
518 NotificationCallback notification_callback_;
519 NotificationAuthCallback notification_auth_callback_;
520
[email protected]dc5a5cf2012-09-26 02:49:30521 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
522
523 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35524};
525
[email protected]dc5a5cf2012-09-26 02:49:30526BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
527 : block_mode_(block_mode),
528 retval_(OK),
529 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
530 block_on_(0),
531 target_auth_credentials_(NULL),
532 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32533 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30534}
535
536void BlockingNetworkDelegate::DoCallback(int response) {
537 ASSERT_EQ(USER_CALLBACK, block_mode_);
538 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
539 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
540 CompletionCallback callback = callback_;
541 Reset();
542 RunCallback(response, callback);
543}
544
545void BlockingNetworkDelegate::DoAuthCallback(
546 NetworkDelegate::AuthRequiredResponse response) {
547 ASSERT_EQ(USER_CALLBACK, block_mode_);
548 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
549 AuthCallback auth_callback = auth_callback_;
550 Reset();
551 RunAuthCallback(response, auth_callback);
552}
553
554void BlockingNetworkDelegate::RunCallback(int response,
555 const CompletionCallback& callback) {
556 callback.Run(response);
557}
558
559void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
560 const AuthCallback& callback) {
561 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
562 ASSERT_TRUE(target_auth_credentials_ != NULL);
563 *target_auth_credentials_ = auth_credentials_;
564 }
565 callback.Run(response);
566}
567
568int BlockingNetworkDelegate::OnBeforeURLRequest(
569 URLRequest* request,
570 const CompletionCallback& callback,
571 GURL* new_url) {
572 if (redirect_url_ == request->url())
573 return OK; // We've already seen this request and redirected elsewhere.
574
575 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
576
577 if (!redirect_url_.is_empty())
578 *new_url = redirect_url_;
579
rdsmithbf8c3c12016-11-18 18:16:24580 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30581}
582
ryansturm2343cb62016-06-15 01:09:00583int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30584 URLRequest* request,
585 const CompletionCallback& callback,
586 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00587 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30588
rdsmithbf8c3c12016-11-18 18:16:24589 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30590}
591
592int BlockingNetworkDelegate::OnHeadersReceived(
593 URLRequest* request,
594 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32595 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16596 scoped_refptr<HttpResponseHeaders>* override_response_headers,
597 GURL* allowed_unsafe_redirect_url) {
598 TestNetworkDelegate::OnHeadersReceived(request,
599 callback,
600 original_response_headers,
601 override_response_headers,
602 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30603
rdsmithbf8c3c12016-11-18 18:16:24604 return MaybeBlockStage(ON_HEADERS_RECEIVED, request, callback);
[email protected]dc5a5cf2012-09-26 02:49:30605}
606
607NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
608 URLRequest* request,
609 const AuthChallengeInfo& auth_info,
610 const AuthCallback& callback,
611 AuthCredentials* credentials) {
612 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
613 credentials);
614 // Check that the user has provided callback for the previous blocked stage.
615 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
616
617 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
618 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
619 }
620
621 target_auth_credentials_ = credentials;
622
623 switch (block_mode_) {
624 case SYNCHRONOUS:
625 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
626 *target_auth_credentials_ = auth_credentials_;
627 return auth_retval_;
628
629 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45630 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30631 FROM_HERE,
632 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
633 weak_factory_.GetWeakPtr(), auth_retval_, callback));
634 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
635
636 case USER_CALLBACK:
637 auth_callback_ = callback;
638 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45639 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17640 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30641 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24642
643 case USER_NOTIFY:
644 // If the callback returns ERR_IO_PENDING, the user has accepted
645 // responsibility for running the callback in the future.
646 return notification_auth_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30647 }
648 NOTREACHED();
649 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
650}
651
652void BlockingNetworkDelegate::Reset() {
653 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
654 stage_blocked_for_callback_ = NOT_BLOCKED;
655 callback_.Reset();
656 auth_callback_.Reset();
657}
658
659int BlockingNetworkDelegate::MaybeBlockStage(
660 BlockingNetworkDelegate::Stage stage,
rdsmithbf8c3c12016-11-18 18:16:24661 const URLRequest* request,
[email protected]dc5a5cf2012-09-26 02:49:30662 const CompletionCallback& callback) {
663 // Check that the user has provided callback for the previous blocked stage.
664 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
665
666 if ((block_on_ & stage) == 0) {
667 return OK;
668 }
669
670 switch (block_mode_) {
671 case SYNCHRONOUS:
672 EXPECT_NE(OK, retval_);
673 return retval_;
674
675 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45676 base::ThreadTaskRunnerHandle::Get()->PostTask(
677 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
678 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30679 return ERR_IO_PENDING;
680
681 case USER_CALLBACK:
682 callback_ = callback;
683 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45684 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17685 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30686 return ERR_IO_PENDING;
rdsmithbf8c3c12016-11-18 18:16:24687
688 case USER_NOTIFY:
689 // If the callback returns ERR_IO_PENDING, the user has accepted
690 // responsibility for running the callback in the future.
691 return notification_callback_.Run(callback, request);
[email protected]dc5a5cf2012-09-26 02:49:30692 }
693 NOTREACHED();
694 return 0;
695}
696
[email protected]d5a4dd62012-05-23 01:41:04697class TestURLRequestContextWithProxy : public TestURLRequestContext {
698 public:
699 // Does not own |delegate|.
700 TestURLRequestContextWithProxy(const std::string& proxy,
701 NetworkDelegate* delegate)
702 : TestURLRequestContext(true) {
703 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
704 set_network_delegate(delegate);
705 Init();
706 }
dchengb03027d2014-10-21 12:00:20707 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04708};
709
stefanocsbd5be5202016-06-10 03:37:55710// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01711// URI and report to be sent.
712class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55713 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01714 public:
715 MockCertificateReportSender() {}
716 ~MockCertificateReportSender() override {}
717
meacer8c164432016-11-15 03:56:49718 void Send(
719 const GURL& report_uri,
720 base::StringPiece content_type,
721 base::StringPiece report,
722 const base::Callback<void()>& success_callback,
723 const base::Callback<void(const GURL&, int)>& error_callback) override {
estark06e0dac2015-08-07 21:56:01724 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44725 report.CopyToString(&latest_report_);
726 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01727 }
estark06e0dac2015-08-07 21:56:01728 const GURL& latest_report_uri() { return latest_report_uri_; }
729 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44730 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01731
732 private:
733 GURL latest_report_uri_;
734 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44735 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01736};
737
estarkcd39c11f2015-10-19 19:46:36738class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
739 public:
740 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34741 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36742};
743
dadrian612337a2016-07-20 22:36:58744// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
745// This is needed because after the certificate failure, the URLRequest will
746// retry the connection, and return a partial SSLInfo with a cached cert status.
747// The partial SSLInfo does not have the OCSP information filled out.
748class OCSPErrorTestDelegate : public TestDelegate {
749 public:
750 void OnSSLCertificateError(URLRequest* request,
751 const SSLInfo& ssl_info,
752 bool fatal) override {
753 ssl_info_ = ssl_info;
754 on_ssl_certificate_error_called_ = true;
755 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
756 }
757
758 bool on_ssl_certificate_error_called() {
759 return on_ssl_certificate_error_called_;
760 }
761
762 SSLInfo ssl_info() { return ssl_info_; }
763
764 private:
765 bool on_ssl_certificate_error_called_ = false;
766 SSLInfo ssl_info_;
767};
768
[email protected]d5a4dd62012-05-23 01:41:04769} // namespace
770
[email protected]a592c0432012-12-01 18:10:29771// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48772class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00773 public:
[email protected]ef2bf422012-05-11 03:27:09774 URLRequestTest() : default_context_(true) {
775 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25776 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50777 job_factory_impl_ = new URLRequestJobFactoryImpl();
778 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50779 }
bengr1bf8e942014-11-07 01:36:50780
dcheng67be2b1f2014-10-27 21:47:29781 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18782 // URLRequestJobs may post clean-up tasks on destruction.
783 base::RunLoop().RunUntilIdle();
784 }
[email protected]87a09a92011-07-14 15:50:50785
dcheng2339883c2014-12-23 00:23:05786 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50787 SetUpFactory();
788 default_context_.set_job_factory(job_factory_.get());
789 default_context_.Init();
790 PlatformTest::SetUp();
791 }
792
793 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20794 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36795 "data", base::WrapUnique(new DataProtocolHandler));
brettwa1228ebb2016-10-28 03:51:34796#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
bengr1bf8e942014-11-07 01:36:50797 job_factory_impl_->SetProtocolHandler(
ricea2deef682016-09-09 08:04:07798 "file", base::MakeUnique<FileProtocolHandler>(
799 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50800#endif
801 }
802
803 TestNetworkDelegate* default_network_delegate() {
804 return &default_network_delegate_;
805 }
806
807 const TestURLRequestContext& default_context() const {
808 return default_context_;
809 }
810
811
[email protected]3c5ca8c2011-09-29 01:14:51812 // Adds the TestJobInterceptor to the default context.
813 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23814 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20815 job_factory_impl_->SetProtocolHandler("http", nullptr);
816 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36817 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23818 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51819 }
820
[email protected]87a09a92011-07-14 15:50:50821 protected:
vishal.b62985ca92015-04-17 08:45:51822 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24823 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50824 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36825 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09826 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48827};
828
[email protected]316c1e5e2012-09-12 15:17:44829TEST_F(URLRequestTest, AboutBlankTest) {
830 TestDelegate d;
831 {
danakj8522a25b2016-04-16 00:17:36832 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36833 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44834
[email protected]f7022f32014-08-21 16:32:19835 r->Start();
836 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44837
[email protected]255620da2013-08-19 13:14:29838 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44839
[email protected]f7022f32014-08-21 16:32:19840 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44841 EXPECT_FALSE(d.received_data_before_response());
842 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19843 EXPECT_EQ("", r->GetSocketAddress().host());
844 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04845
846 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19847 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44848 }
849}
850
851TEST_F(URLRequestTest, DataURLImageTest) {
852 TestDelegate d;
853 {
854 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36855 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
856 GURL("data:image/png;base64,"
857 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
858 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
859 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
860 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
861 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
862 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
863 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
864 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
865 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
866 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
867 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
868 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
869 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
870 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
871 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
872 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
873 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
874 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
875 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36876 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44877
[email protected]f7022f32014-08-21 16:32:19878 r->Start();
879 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44880
[email protected]255620da2013-08-19 13:14:29881 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44882
[email protected]f7022f32014-08-21 16:32:19883 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44884 EXPECT_FALSE(d.received_data_before_response());
885 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19886 EXPECT_EQ("", r->GetSocketAddress().host());
887 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04888
889 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19890 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44891 }
892}
893
brettwa1228ebb2016-10-28 03:51:34894#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44895TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15896 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04897
898#if defined(OS_ANDROID)
899 // Android devices are not guaranteed to be able to read /proc/self/exe
900 // Use /etc/hosts instead
901 app_path = base::FilePath("/etc/hosts");
902#else
[email protected]316c1e5e2012-09-12 15:17:44903 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04904#endif // OS_ANDROID
905
[email protected]316c1e5e2012-09-12 15:17:44906 GURL app_url = FilePathToFileURL(app_path);
907
908 TestDelegate d;
909 {
danakj8522a25b2016-04-16 00:17:36910 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36911 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44912
[email protected]f7022f32014-08-21 16:32:19913 r->Start();
914 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44915
[email protected]255620da2013-08-19 13:14:29916 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44917
avibf0746c2015-12-09 19:53:14918 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49919 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44920
[email protected]f7022f32014-08-21 16:32:19921 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44922 EXPECT_EQ(1, d.response_started_count());
923 EXPECT_FALSE(d.received_data_before_response());
924 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19925 EXPECT_EQ("", r->GetSocketAddress().host());
926 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04927
928 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19929 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44930 }
931}
932
[email protected]ba40bb762012-12-17 07:11:04933TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15934 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04935 PathService::Get(base::FILE_EXE, &app_path);
936 GURL app_url = FilePathToFileURL(app_path);
937
938 TestDelegate d;
939 {
danakj8522a25b2016-04-16 00:17:36940 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36941 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04942
[email protected]f7022f32014-08-21 16:32:19943 r->Start();
944 EXPECT_TRUE(r->is_pending());
945 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04946 }
[email protected]79e1fd62013-06-20 06:50:04947 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04948 // destroyed.
[email protected]255620da2013-08-19 13:14:29949 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04950}
951
[email protected]316c1e5e2012-09-12 15:17:44952TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
953 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36954 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44955 FillBuffer(buffer.get(), buffer_size);
956
[email protected]6cdfd7f2013-02-08 20:40:15957 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52958 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44959 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30960 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44961
avibf0746c2015-12-09 19:53:14962 int64_t file_size;
[email protected]56285702013-12-04 18:22:49963 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44964
965 const size_t first_byte_position = 500;
966 const size_t last_byte_position = buffer_size - first_byte_position;
967 const size_t content_length = last_byte_position - first_byte_position + 1;
968 std::string partial_buffer_string(buffer.get() + first_byte_position,
969 buffer.get() + last_byte_position + 1);
970
971 TestDelegate d;
972 {
danakj8522a25b2016-04-16 00:17:36973 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36974 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44975
976 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38977 headers.SetHeader(
978 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59979 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38980 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19981 r->SetExtraRequestHeaders(headers);
982 r->Start();
983 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44984
[email protected]255620da2013-08-19 13:14:29985 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19986 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44987 EXPECT_EQ(1, d.response_started_count());
988 EXPECT_FALSE(d.received_data_before_response());
989 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
990 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
991 EXPECT_TRUE(partial_buffer_string == d.data_received());
992 }
993
[email protected]dd3aa792013-07-16 19:10:23994 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44995}
996
997TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
998 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36999 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441000 FillBuffer(buffer.get(), buffer_size);
1001
[email protected]6cdfd7f2013-02-08 20:40:151002 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521003 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441004 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301005 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441006
avibf0746c2015-12-09 19:53:141007 int64_t file_size;
[email protected]56285702013-12-04 18:22:491008 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441009
1010 const size_t first_byte_position = 500;
1011 const size_t last_byte_position = buffer_size - 1;
1012 const size_t content_length = last_byte_position - first_byte_position + 1;
1013 std::string partial_buffer_string(buffer.get() + first_byte_position,
1014 buffer.get() + last_byte_position + 1);
1015
1016 TestDelegate d;
1017 {
danakj8522a25b2016-04-16 00:17:361018 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361019 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441020
1021 HttpRequestHeaders headers;
1022 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:591023 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:381024 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:191025 r->SetExtraRequestHeaders(headers);
1026 r->Start();
1027 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441028
[email protected]255620da2013-08-19 13:14:291029 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:191030 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441031 EXPECT_EQ(1, d.response_started_count());
1032 EXPECT_FALSE(d.received_data_before_response());
1033 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
1034 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
1035 EXPECT_TRUE(partial_buffer_string == d.data_received());
1036 }
1037
[email protected]dd3aa792013-07-16 19:10:231038 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441039}
1040
1041TEST_F(URLRequestTest, FileTestMultipleRanges) {
1042 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361043 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441044 FillBuffer(buffer.get(), buffer_size);
1045
[email protected]6cdfd7f2013-02-08 20:40:151046 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521047 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441048 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301049 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441050
avibf0746c2015-12-09 19:53:141051 int64_t file_size;
[email protected]56285702013-12-04 18:22:491052 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441053
1054 TestDelegate d;
1055 {
danakj8522a25b2016-04-16 00:17:361056 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361057 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441058
1059 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381060 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191061 r->SetExtraRequestHeaders(headers);
1062 r->Start();
1063 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441064
[email protected]255620da2013-08-19 13:14:291065 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441066 EXPECT_TRUE(d.request_failed());
1067 }
1068
[email protected]dd3aa792013-07-16 19:10:231069 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441070}
1071
[email protected]3ca8b362013-11-11 22:18:071072TEST_F(URLRequestTest, AllowFileURLs) {
1073 base::ScopedTempDir temp_dir;
1074 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1075 base::FilePath test_file;
vabrb8582322016-09-09 08:05:371076 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.GetPath(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071077 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301078 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591079 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071080
1081 {
1082 TestDelegate d;
1083 TestNetworkDelegate network_delegate;
1084 network_delegate.set_can_access_files(true);
1085 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361086 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361087 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191088 r->Start();
[email protected]3ca8b362013-11-11 22:18:071089 base::RunLoop().Run();
1090 EXPECT_FALSE(d.request_failed());
1091 EXPECT_EQ(test_data, d.data_received());
1092 }
1093
1094 {
1095 TestDelegate d;
1096 TestNetworkDelegate network_delegate;
1097 network_delegate.set_can_access_files(false);
1098 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361099 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361100 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191101 r->Start();
[email protected]3ca8b362013-11-11 22:18:071102 base::RunLoop().Run();
1103 EXPECT_TRUE(d.request_failed());
1104 EXPECT_EQ("", d.data_received());
1105 }
1106}
1107
[email protected]316c1e5e2012-09-12 15:17:441108
1109TEST_F(URLRequestTest, FileDirCancelTest) {
1110 // Put in mock resource provider.
1111 NetModule::SetResourceProvider(TestNetResourceProvider);
1112
1113 TestDelegate d;
1114 {
[email protected]6cdfd7f2013-02-08 20:40:151115 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441116 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1117 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1118 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1119
danakj8522a25b2016-04-16 00:17:361120 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361121 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191122 req->Start();
1123 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441124
1125 d.set_cancel_in_received_data_pending(true);
1126
[email protected]255620da2013-08-19 13:14:291127 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441128 }
1129
1130 // Take out mock resource provider.
1131 NetModule::SetResourceProvider(NULL);
1132}
1133
[email protected]5f9581402013-10-30 13:08:321134TEST_F(URLRequestTest, FileDirOutputSanity) {
1135 // Verify the general sanity of the the output of the file:
1136 // directory lister by checking for the output of a known existing
1137 // file.
1138 const char sentinel_name[] = "filedir-sentinel";
1139
1140 base::FilePath path;
1141 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471142 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321143
1144 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361145 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361146 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191147 req->Start();
[email protected]5f9581402013-10-30 13:08:321148 base::RunLoop().Run();
1149
1150 // Generate entry for the sentinel file.
1151 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581152 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491153 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321154 EXPECT_GT(info.size, 0);
1155 std::string sentinel_output = GetDirectoryListingEntry(
1156 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1157 std::string(sentinel_name),
1158 false /* is_dir */,
1159 info.size,
1160 info.last_modified);
1161
1162 ASSERT_LT(0, d.bytes_received());
1163 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501164 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321165 // Check for the entry generated for the "sentinel" file.
1166 const std::string& data = d.data_received();
1167 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1168}
1169
[email protected]316c1e5e2012-09-12 15:17:441170TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1171 // There is an implicit redirect when loading a file path that matches a
1172 // directory and does not end with a slash. Ensure that following such
1173 // redirects does not crash. See http://crbug.com/18686.
1174
[email protected]6cdfd7f2013-02-08 20:40:151175 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441176 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471177 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441178
1179 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361180 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361181 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191182 req->Start();
[email protected]255620da2013-08-19 13:14:291183 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441184
1185 ASSERT_EQ(1, d.received_redirect_count());
1186 ASSERT_LT(0, d.bytes_received());
1187 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501188 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441189}
1190
1191#if defined(OS_WIN)
1192// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1193TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1194 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361195 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361196 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191197 req->Start();
[email protected]255620da2013-08-19 13:14:291198 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441199
1200 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501201 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441202}
[email protected]5ecf7cb282014-05-11 01:49:551203#endif // defined(OS_WIN)
1204
brettwa1228ebb2016-10-28 03:51:341205#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:551206
1207TEST_F(URLRequestTest, InvalidUrlTest) {
1208 TestDelegate d;
1209 {
danakj8522a25b2016-04-16 00:17:361210 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361211 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551212
[email protected]f7022f32014-08-21 16:32:191213 r->Start();
1214 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551215
1216 base::RunLoop().Run();
1217 EXPECT_TRUE(d.request_failed());
1218 }
1219}
1220
jochen0e3b3a62014-09-16 18:31:231221TEST_F(URLRequestTest, InvalidReferrerTest) {
1222 TestURLRequestContext context;
1223 TestNetworkDelegate network_delegate;
1224 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1225 context.set_network_delegate(&network_delegate);
1226 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361227 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361228 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231229 req->SetReferrer("https://somewhere.com/");
1230
1231 req->Start();
1232 base::RunLoop().Run();
1233 EXPECT_TRUE(d.request_failed());
1234}
1235
[email protected]5ecf7cb282014-05-11 01:49:551236#if defined(OS_WIN)
1237TEST_F(URLRequestTest, ResolveShortcutTest) {
1238 base::FilePath app_path;
1239 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471240 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551241 app_path = app_path.AppendASCII("with-headers.html");
1242
1243 std::wstring lnk_path = app_path.value() + L".lnk";
1244
1245 base::win::ScopedCOMInitializer com_initializer;
1246
1247 // Temporarily create a shortcut for test
1248 {
1249 base::win::ScopedComPtr<IShellLink> shell;
1250 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1251 CLSCTX_INPROC_SERVER)));
1252 base::win::ScopedComPtr<IPersistFile> persist;
1253 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1254 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1255 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1256 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1257 }
1258
1259 TestDelegate d;
1260 {
danakj8522a25b2016-04-16 00:17:361261 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361262 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551263
[email protected]f7022f32014-08-21 16:32:191264 r->Start();
1265 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551266
1267 base::RunLoop().Run();
1268
1269 WIN32_FILE_ATTRIBUTE_DATA data;
1270 GetFileAttributesEx(app_path.value().c_str(),
1271 GetFileExInfoStandard, &data);
1272 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1273 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1274 FILE_ATTRIBUTE_NORMAL, NULL);
1275 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361276 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551277 DWORD read_size;
1278 BOOL result;
1279 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1280 &read_size, NULL);
1281 std::string content(buffer.get(), read_size);
1282 CloseHandle(file);
1283
[email protected]f7022f32014-08-21 16:32:191284 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551285 EXPECT_EQ(1, d.received_redirect_count());
1286 EXPECT_EQ(content, d.data_received());
1287 }
1288
1289 // Clean the shortcut
1290 DeleteFile(lnk_path.c_str());
1291}
1292#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441293
1294// Custom URLRequestJobs for use with interceptor tests
1295class RestartTestJob : public URLRequestTestJob {
1296 public:
1297 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1298 : URLRequestTestJob(request, network_delegate, true) {}
1299 protected:
dchengb03027d2014-10-21 12:00:201300 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441301 private:
dchengb03027d2014-10-21 12:00:201302 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441303};
1304
1305class CancelTestJob : public URLRequestTestJob {
1306 public:
1307 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1308 : URLRequestTestJob(request, network_delegate, true) {}
1309 protected:
dchengb03027d2014-10-21 12:00:201310 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441311 private:
dchengb03027d2014-10-21 12:00:201312 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441313};
1314
1315class CancelThenRestartTestJob : public URLRequestTestJob {
1316 public:
1317 explicit CancelThenRestartTestJob(URLRequest* request,
1318 NetworkDelegate* network_delegate)
1319 : URLRequestTestJob(request, network_delegate, true) {
1320 }
1321 protected:
dchengb03027d2014-10-21 12:00:201322 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441323 request_->Cancel();
1324 this->NotifyRestartRequired();
1325 }
1326 private:
dchengb03027d2014-10-21 12:00:201327 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441328};
1329
bengr1bf8e942014-11-07 01:36:501330// An Interceptor for use with interceptor tests.
1331class MockURLRequestInterceptor : public URLRequestInterceptor {
1332 public:
1333 // Static getters for canned response header and data strings.
1334 static std::string ok_data() {
1335 return URLRequestTestJob::test_data_1();
1336 }
1337
1338 static std::string ok_headers() {
1339 return URLRequestTestJob::test_headers();
1340 }
1341
1342 static std::string redirect_data() {
1343 return std::string();
1344 }
1345
1346 static std::string redirect_headers() {
1347 return URLRequestTestJob::test_redirect_headers();
1348 }
1349
1350 static std::string error_data() {
1351 return std::string("ohhh nooooo mr. bill!");
1352 }
1353
1354 static std::string error_headers() {
1355 return URLRequestTestJob::test_error_headers();
1356 }
1357
1358 MockURLRequestInterceptor()
1359 : intercept_main_request_(false), restart_main_request_(false),
1360 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1361 simulate_main_network_error_(false),
1362 intercept_redirect_(false), cancel_redirect_request_(false),
1363 intercept_final_response_(false), cancel_final_request_(false),
1364 use_url_request_http_job_(false),
1365 did_intercept_main_(false), did_restart_main_(false),
1366 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1367 did_simulate_error_main_(false),
1368 did_intercept_redirect_(false), did_cancel_redirect_(false),
1369 did_intercept_final_(false), did_cancel_final_(false) {
1370 }
1371
1372 ~MockURLRequestInterceptor() override {
1373 }
1374
1375 // URLRequestInterceptor implementation:
1376 URLRequestJob* MaybeInterceptRequest(
1377 URLRequest* request,
1378 NetworkDelegate* network_delegate) const override {
1379 if (restart_main_request_) {
1380 restart_main_request_ = false;
1381 did_restart_main_ = true;
1382 return new RestartTestJob(request, network_delegate);
1383 }
1384 if (cancel_main_request_) {
1385 cancel_main_request_ = false;
1386 did_cancel_main_ = true;
1387 return new CancelTestJob(request, network_delegate);
1388 }
1389 if (cancel_then_restart_main_request_) {
1390 cancel_then_restart_main_request_ = false;
1391 did_cancel_then_restart_main_ = true;
1392 return new CancelThenRestartTestJob(request, network_delegate);
1393 }
1394 if (simulate_main_network_error_) {
1395 simulate_main_network_error_ = false;
1396 did_simulate_error_main_ = true;
1397 if (use_url_request_http_job_) {
1398 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1399 }
1400 // This job will result in error since the requested URL is not one of the
1401 // URLs supported by these tests.
1402 return new URLRequestTestJob(request, network_delegate, true);
1403 }
1404 if (!intercept_main_request_)
1405 return nullptr;
1406 intercept_main_request_ = false;
1407 did_intercept_main_ = true;
1408 URLRequestTestJob* job = new URLRequestTestJob(request,
1409 network_delegate,
1410 main_headers_,
1411 main_data_,
1412 true);
1413 job->set_load_timing_info(main_request_load_timing_info_);
1414 return job;
1415 }
1416
1417 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1418 NetworkDelegate* network_delegate,
1419 const GURL& location) const override {
1420 if (cancel_redirect_request_) {
1421 cancel_redirect_request_ = false;
1422 did_cancel_redirect_ = true;
1423 return new CancelTestJob(request, network_delegate);
1424 }
1425 if (!intercept_redirect_)
1426 return nullptr;
1427 intercept_redirect_ = false;
1428 did_intercept_redirect_ = true;
1429 if (use_url_request_http_job_) {
1430 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1431 }
1432 return new URLRequestTestJob(request,
1433 network_delegate,
1434 redirect_headers_,
1435 redirect_data_,
1436 true);
1437 }
1438
1439 URLRequestJob* MaybeInterceptResponse(
1440 URLRequest* request,
1441 NetworkDelegate* network_delegate) const override {
1442 if (cancel_final_request_) {
1443 cancel_final_request_ = false;
1444 did_cancel_final_ = true;
1445 return new CancelTestJob(request, network_delegate);
1446 }
1447 if (!intercept_final_response_)
1448 return nullptr;
1449 intercept_final_response_ = false;
1450 did_intercept_final_ = true;
1451 if (use_url_request_http_job_) {
1452 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1453 }
1454 return new URLRequestTestJob(request,
1455 network_delegate,
1456 final_headers_,
1457 final_data_,
1458 true);
1459 }
1460
1461 void set_intercept_main_request(bool intercept_main_request) {
1462 intercept_main_request_ = intercept_main_request;
1463 }
1464
1465 void set_main_headers(const std::string& main_headers) {
1466 main_headers_ = main_headers;
1467 }
1468
1469 void set_main_data(const std::string& main_data) {
1470 main_data_ = main_data;
1471 }
1472
1473 void set_main_request_load_timing_info(
1474 const LoadTimingInfo& main_request_load_timing_info) {
1475 main_request_load_timing_info_ = main_request_load_timing_info;
1476 }
1477
1478 void set_restart_main_request(bool restart_main_request) {
1479 restart_main_request_ = restart_main_request;
1480 }
1481
1482 void set_cancel_main_request(bool cancel_main_request) {
1483 cancel_main_request_ = cancel_main_request;
1484 }
1485
1486 void set_cancel_then_restart_main_request(
1487 bool cancel_then_restart_main_request) {
1488 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1489 }
1490
1491 void set_simulate_main_network_error(bool simulate_main_network_error) {
1492 simulate_main_network_error_ = simulate_main_network_error;
1493 }
1494
1495 void set_intercept_redirect(bool intercept_redirect) {
1496 intercept_redirect_ = intercept_redirect;
1497 }
1498
1499 void set_redirect_headers(const std::string& redirect_headers) {
1500 redirect_headers_ = redirect_headers;
1501 }
1502
1503 void set_redirect_data(const std::string& redirect_data) {
1504 redirect_data_ = redirect_data;
1505 }
1506
1507 void set_cancel_redirect_request(bool cancel_redirect_request) {
1508 cancel_redirect_request_ = cancel_redirect_request;
1509 }
1510
1511 void set_intercept_final_response(bool intercept_final_response) {
1512 intercept_final_response_ = intercept_final_response;
1513 }
1514
1515 void set_final_headers(const std::string& final_headers) {
1516 final_headers_ = final_headers;
1517 }
1518
1519 void set_final_data(const std::string& final_data) {
1520 final_data_ = final_data;
1521 }
1522
1523 void set_cancel_final_request(bool cancel_final_request) {
1524 cancel_final_request_ = cancel_final_request;
1525 }
1526
1527 void set_use_url_request_http_job(bool use_url_request_http_job) {
1528 use_url_request_http_job_ = use_url_request_http_job;
1529 }
1530
1531 bool did_intercept_main() const {
1532 return did_intercept_main_;
1533 }
1534
1535 bool did_restart_main() const {
1536 return did_restart_main_;
1537 }
1538
1539 bool did_cancel_main() const {
1540 return did_cancel_main_;
1541 }
1542
1543 bool did_cancel_then_restart_main() const {
1544 return did_cancel_then_restart_main_;
1545 }
1546
1547 bool did_simulate_error_main() const {
1548 return did_simulate_error_main_;
1549 }
1550
1551 bool did_intercept_redirect() const {
1552 return did_intercept_redirect_;
1553 }
1554
1555 bool did_cancel_redirect() const {
1556 return did_cancel_redirect_;
1557 }
1558
1559 bool did_intercept_final() const {
1560 return did_intercept_final_;
1561 }
1562
1563 bool did_cancel_final() const {
1564 return did_cancel_final_;
1565 }
1566
1567 private:
1568 // Indicate whether to intercept the main request, and if so specify the
1569 // response to return and the LoadTimingInfo to use.
1570 mutable bool intercept_main_request_;
1571 mutable std::string main_headers_;
1572 mutable std::string main_data_;
1573 mutable LoadTimingInfo main_request_load_timing_info_;
1574
1575 // These indicate actions that can be taken within MaybeInterceptRequest.
1576 mutable bool restart_main_request_;
1577 mutable bool cancel_main_request_;
1578 mutable bool cancel_then_restart_main_request_;
1579 mutable bool simulate_main_network_error_;
1580
1581 // Indicate whether to intercept redirects, and if so specify the response to
1582 // return.
1583 mutable bool intercept_redirect_;
1584 mutable std::string redirect_headers_;
1585 mutable std::string redirect_data_;
1586
1587 // Cancel the request within MaybeInterceptRedirect.
1588 mutable bool cancel_redirect_request_;
1589
1590 // Indicate whether to intercept the final response, and if so specify the
1591 // response to return.
1592 mutable bool intercept_final_response_;
1593 mutable std::string final_headers_;
1594 mutable std::string final_data_;
1595
1596 // Cancel the final request within MaybeInterceptResponse.
1597 mutable bool cancel_final_request_;
1598
1599 // Instruct the interceptor to use a real URLRequestHTTPJob.
1600 mutable bool use_url_request_http_job_;
1601
1602 // These indicate if the interceptor did something or not.
1603 mutable bool did_intercept_main_;
1604 mutable bool did_restart_main_;
1605 mutable bool did_cancel_main_;
1606 mutable bool did_cancel_then_restart_main_;
1607 mutable bool did_simulate_error_main_;
1608 mutable bool did_intercept_redirect_;
1609 mutable bool did_cancel_redirect_;
1610 mutable bool did_intercept_final_;
1611 mutable bool did_cancel_final_;
1612};
1613
1614// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1615class URLRequestInterceptorTest : public URLRequestTest {
1616 public:
1617 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1618 }
1619
1620 ~URLRequestInterceptorTest() override {
1621 // URLRequestJobs may post clean-up tasks on destruction.
1622 base::RunLoop().RunUntilIdle();
1623 }
1624
1625 void SetUpFactory() override {
1626 interceptor_ = new MockURLRequestInterceptor();
1627 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361628 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501629 }
1630
1631 MockURLRequestInterceptor* interceptor() const {
1632 return interceptor_;
1633 }
1634
1635 private:
1636 MockURLRequestInterceptor* interceptor_;
1637};
1638
1639TEST_F(URLRequestInterceptorTest, Intercept) {
1640 // Intercept the main request and respond with a simple response.
1641 interceptor()->set_intercept_main_request(true);
1642 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1643 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361645 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361646 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501647 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1648 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1649 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1650 req->SetUserData(nullptr, user_data0);
1651 req->SetUserData(&user_data1, user_data1);
1652 req->SetUserData(&user_data2, user_data2);
1653 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191654 req->Start();
[email protected]255620da2013-08-19 13:14:291655 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591656
bengr1bf8e942014-11-07 01:36:501657 // Make sure we can retrieve our specific user data.
1658 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1659 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1660 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591661
bengr1bf8e942014-11-07 01:36:501662 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501663 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501664 EXPECT_EQ(200, req->response_headers()->response_code());
1665 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1666 EXPECT_EQ(1, d.response_started_count());
1667 EXPECT_EQ(0, d.received_redirect_count());
1668}
[email protected]2bba3252013-04-08 19:50:591669
bengr1bf8e942014-11-07 01:36:501670TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1671 // Intercept the main request and respond with a redirect.
1672 interceptor()->set_intercept_main_request(true);
1673 interceptor()->set_main_headers(
1674 MockURLRequestInterceptor::redirect_headers());
1675 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1676
1677 // Intercept that redirect and respond with a final OK response.
1678 interceptor()->set_intercept_redirect(true);
1679 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1680 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1681
1682 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361683 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361684 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501685 req->set_method("GET");
1686 req->Start();
1687 base::RunLoop().Run();
1688
1689 // Check that the interceptor got called as expected.
1690 EXPECT_TRUE(interceptor()->did_intercept_main());
1691 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1692
1693 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501694 int status = d.request_status();
1695 EXPECT_EQ(OK, status);
1696 if (status == OK)
bengr1bf8e942014-11-07 01:36:501697 EXPECT_EQ(200, req->response_headers()->response_code());
1698
1699 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1700 EXPECT_EQ(1, d.response_started_count());
1701 EXPECT_EQ(0, d.received_redirect_count());
1702}
1703
1704TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1705 // Intercept the main request to generate a server error response.
1706 interceptor()->set_intercept_main_request(true);
1707 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1708 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1709
1710 // Intercept that error and respond with an OK response.
1711 interceptor()->set_intercept_final_response(true);
1712 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1713 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1714
1715 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361716 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361717 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501718 req->set_method("GET");
1719 req->Start();
1720 base::RunLoop().Run();
1721
1722 // Check that the interceptor got called as expected.
1723 EXPECT_TRUE(interceptor()->did_intercept_main());
1724 EXPECT_TRUE(interceptor()->did_intercept_final());
1725
1726 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501727 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501728 EXPECT_EQ(200, req->response_headers()->response_code());
1729 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1730 EXPECT_EQ(1, d.response_started_count());
1731 EXPECT_EQ(0, d.received_redirect_count());
1732}
1733
1734TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1735 // Intercept the main request to simulate a network error.
1736 interceptor()->set_simulate_main_network_error(true);
1737
1738 // Intercept that error and respond with an OK response.
1739 interceptor()->set_intercept_final_response(true);
1740 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1741 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1742
1743 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361744 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361745 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501746 req->set_method("GET");
1747 req->Start();
1748 base::RunLoop().Run();
1749
1750 // Check that the interceptor got called as expected.
1751 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1752 EXPECT_TRUE(interceptor()->did_intercept_final());
1753
1754 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501755 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501756 EXPECT_EQ(200, req->response_headers()->response_code());
1757 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1758 EXPECT_EQ(1, d.response_started_count());
1759 EXPECT_EQ(0, d.received_redirect_count());
1760}
1761
1762TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1763 // Restart the main request.
1764 interceptor()->set_restart_main_request(true);
1765
1766 // then intercept the new main request and respond with an OK response
1767 interceptor()->set_intercept_main_request(true);
1768 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1769 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1770
1771 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361772 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361773 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501774 req->set_method("GET");
1775 req->Start();
1776 base::RunLoop().Run();
1777
1778 // Check that the interceptor got called as expected.
1779 EXPECT_TRUE(interceptor()->did_restart_main());
1780 EXPECT_TRUE(interceptor()->did_intercept_main());
1781
1782 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501783 int status = d.request_status();
1784 EXPECT_EQ(OK, status);
1785 if (status == OK)
bengr1bf8e942014-11-07 01:36:501786 EXPECT_EQ(200, req->response_headers()->response_code());
1787
1788 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1789 EXPECT_EQ(1, d.response_started_count());
1790 EXPECT_EQ(0, d.received_redirect_count());
1791}
1792
1793TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1794 // Intercept the main request and cancel from within the restarted job.
1795 interceptor()->set_cancel_main_request(true);
1796
1797 // Set up to intercept the final response and override it with an OK response.
1798 interceptor()->set_intercept_final_response(true);
1799 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1800 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1801
1802 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361803 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361804 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501805 req->set_method("GET");
1806 req->Start();
1807 base::RunLoop().Run();
1808
1809 // Check that the interceptor got called as expected.
1810 EXPECT_TRUE(interceptor()->did_cancel_main());
1811 EXPECT_FALSE(interceptor()->did_intercept_final());
1812
1813 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501814 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501815}
1816
1817TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1818 // Intercept the main request and respond with a redirect.
1819 interceptor()->set_intercept_main_request(true);
1820 interceptor()->set_main_headers(
1821 MockURLRequestInterceptor::redirect_headers());
1822 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1823
1824 // Intercept the redirect and cancel from within that job.
1825 interceptor()->set_cancel_redirect_request(true);
1826
1827 // Set up to intercept the final response and override it with an OK response.
1828 interceptor()->set_intercept_final_response(true);
1829 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1830 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1831
1832 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361833 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361834 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501835 req->set_method("GET");
1836 req->Start();
1837 base::RunLoop().Run();
1838
1839 // Check that the interceptor got called as expected.
1840 EXPECT_TRUE(interceptor()->did_intercept_main());
1841 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1842 EXPECT_FALSE(interceptor()->did_intercept_final());
1843
1844 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501845 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501846}
1847
1848TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1849 // Intercept the main request to simulate a network error.
1850 interceptor()->set_simulate_main_network_error(true);
1851
1852 // Set up to intercept final the response and cancel from within that job.
1853 interceptor()->set_cancel_final_request(true);
1854
1855 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361856 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361857 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501858 req->set_method("GET");
1859 req->Start();
1860 base::RunLoop().Run();
1861
1862 // Check that the interceptor got called as expected.
1863 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1864 EXPECT_TRUE(interceptor()->did_cancel_final());
1865
1866 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501867 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501868}
1869
1870TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1871 // Intercept the main request and cancel then restart from within that job.
1872 interceptor()->set_cancel_then_restart_main_request(true);
1873
1874 // Set up to intercept the final response and override it with an OK response.
1875 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501876 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1877 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501878
1879 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361880 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361881 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501882 req->set_method("GET");
1883 req->Start();
1884 base::RunLoop().Run();
1885
1886 // Check that the interceptor got called as expected.
1887 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1888 EXPECT_FALSE(interceptor()->did_intercept_final());
1889
1890 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501891 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:591892}
1893
1894// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1895// reused. |connect_time_flags| is used to indicate if there should be dns
1896// or SSL times, and |used_proxy| is used for proxy times.
1897LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1898 int connect_time_flags,
1899 bool used_proxy) {
1900 LoadTimingInfo load_timing;
1901 load_timing.socket_log_id = 1;
1902
1903 if (used_proxy) {
1904 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1905 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1906 }
1907
1908 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1909 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1910 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1911 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1912 }
1913 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1914 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1915 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1916 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1917 }
1918 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1919
1920 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1921 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1922 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1923 return load_timing;
1924}
1925
1926// Same as above, but in the case of a reused socket.
1927LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1928 bool used_proxy) {
1929 LoadTimingInfo load_timing;
1930 load_timing.socket_log_id = 1;
1931 load_timing.socket_reused = true;
1932
1933 if (used_proxy) {
1934 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1935 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1936 }
1937
1938 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1939 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1940 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1941 return load_timing;
1942}
1943
bengr1bf8e942014-11-07 01:36:501944LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1945 const LoadTimingInfo& job_load_timing,
1946 const URLRequestContext& context,
1947 MockURLRequestInterceptor* interceptor) {
1948 interceptor->set_intercept_main_request(true);
1949 interceptor->set_main_request_load_timing_info(job_load_timing);
1950 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361951 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361952 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501953 req->Start();
1954 base::RunLoop().Run();
1955
1956 LoadTimingInfo resulting_load_timing;
1957 req->GetLoadTimingInfo(&resulting_load_timing);
1958
1959 // None of these should be modified by the URLRequest.
1960 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1961 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1962 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1963 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1964 EXPECT_EQ(job_load_timing.receive_headers_end,
1965 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571966 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1967 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501968
1969 return resulting_load_timing;
1970}
1971
[email protected]2bba3252013-04-08 19:50:591972// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501973TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591974 base::TimeTicks now = base::TimeTicks::Now();
1975 LoadTimingInfo job_load_timing =
1976 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1977
[email protected]2ca01e52013-10-31 22:05:191978 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501979 RunURLRequestInterceptorLoadTimingTest(
1980 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591981
1982 // Nothing should have been changed by the URLRequest.
1983 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1984 load_timing_result.proxy_resolve_start);
1985 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1986 load_timing_result.proxy_resolve_end);
1987 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1988 load_timing_result.connect_timing.dns_start);
1989 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1990 load_timing_result.connect_timing.dns_end);
1991 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1992 load_timing_result.connect_timing.connect_start);
1993 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1994 load_timing_result.connect_timing.connect_end);
1995 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1996 load_timing_result.connect_timing.ssl_start);
1997 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1998 load_timing_result.connect_timing.ssl_end);
1999
2000 // Redundant sanity check.
2001 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2002}
2003
2004// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502005TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592006 base::TimeTicks now = base::TimeTicks::Now();
2007 LoadTimingInfo job_load_timing =
2008 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2009
[email protected]2ca01e52013-10-31 22:05:192010 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502011 RunURLRequestInterceptorLoadTimingTest(
2012 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592013
2014 // Nothing should have been changed by the URLRequest.
2015 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2016 load_timing_result.proxy_resolve_start);
2017 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2018 load_timing_result.proxy_resolve_end);
2019 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2020 load_timing_result.connect_timing.dns_start);
2021 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2022 load_timing_result.connect_timing.dns_end);
2023 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2024 load_timing_result.connect_timing.connect_start);
2025 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2026 load_timing_result.connect_timing.connect_end);
2027 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2028 load_timing_result.connect_timing.ssl_start);
2029 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2030 load_timing_result.connect_timing.ssl_end);
2031
2032 // Redundant sanity check.
2033 TestLoadTimingNotReusedWithProxy(load_timing_result,
2034 CONNECT_TIMING_HAS_SSL_TIMES);
2035}
2036
2037// Make sure that URLRequest correctly adjusts proxy times when they're before
2038// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102039// the case of reusing a SPDY session. The connected socket is not considered
2040// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592041//
2042// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502043TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592044 base::TimeTicks now = base::TimeTicks::Now();
2045 LoadTimingInfo job_load_timing =
2046 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2047 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2048 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2049 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2050 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2051 job_load_timing.connect_timing.connect_start =
2052 now - base::TimeDelta::FromDays(2);
2053 job_load_timing.connect_timing.connect_end =
2054 now - base::TimeDelta::FromDays(1);
2055
[email protected]2ca01e52013-10-31 22:05:192056 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502057 RunURLRequestInterceptorLoadTimingTest(
2058 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592059
2060 // Proxy times, connect times, and DNS times should all be replaced with
2061 // request_start.
2062 EXPECT_EQ(load_timing_result.request_start,
2063 load_timing_result.proxy_resolve_start);
2064 EXPECT_EQ(load_timing_result.request_start,
2065 load_timing_result.proxy_resolve_end);
2066 EXPECT_EQ(load_timing_result.request_start,
2067 load_timing_result.connect_timing.dns_start);
2068 EXPECT_EQ(load_timing_result.request_start,
2069 load_timing_result.connect_timing.dns_end);
2070 EXPECT_EQ(load_timing_result.request_start,
2071 load_timing_result.connect_timing.connect_start);
2072 EXPECT_EQ(load_timing_result.request_start,
2073 load_timing_result.connect_timing.connect_end);
2074
2075 // Other times should have been left null.
2076 TestLoadTimingNotReusedWithProxy(load_timing_result,
2077 CONNECT_TIMING_HAS_DNS_TIMES);
2078}
2079
2080// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502081TEST_F(URLRequestInterceptorTest,
2082 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592083 base::TimeTicks now = base::TimeTicks::Now();
2084 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2085 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2086 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2087
[email protected]2ca01e52013-10-31 22:05:192088 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502089 RunURLRequestInterceptorLoadTimingTest(
2090 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592091
2092 // Proxy times and connect times should all be replaced with request_start.
2093 EXPECT_EQ(load_timing_result.request_start,
2094 load_timing_result.proxy_resolve_start);
2095 EXPECT_EQ(load_timing_result.request_start,
2096 load_timing_result.proxy_resolve_end);
2097
2098 // Other times should have been left null.
2099 TestLoadTimingReusedWithProxy(load_timing_result);
2100}
2101
2102// Make sure that URLRequest correctly adjusts connect times when they're before
2103// |request_start|, due to reusing a connected socket. The connected socket is
2104// not considered reused in this test (May be a preconnect).
2105//
2106// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502107TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592108 base::TimeTicks now = base::TimeTicks::Now();
2109 LoadTimingInfo job_load_timing =
2110 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2111 job_load_timing.connect_timing.connect_start =
2112 now - base::TimeDelta::FromDays(1);
2113 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2114 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2115 job_load_timing.connect_timing.connect_end =
2116 now - base::TimeDelta::FromDays(4);
2117
[email protected]2ca01e52013-10-31 22:05:192118 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502119 RunURLRequestInterceptorLoadTimingTest(
2120 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592121
2122 // Connect times, and SSL times should be replaced with request_start.
2123 EXPECT_EQ(load_timing_result.request_start,
2124 load_timing_result.connect_timing.connect_start);
2125 EXPECT_EQ(load_timing_result.request_start,
2126 load_timing_result.connect_timing.ssl_start);
2127 EXPECT_EQ(load_timing_result.request_start,
2128 load_timing_result.connect_timing.ssl_end);
2129 EXPECT_EQ(load_timing_result.request_start,
2130 load_timing_result.connect_timing.connect_end);
2131
2132 // Other times should have been left null.
2133 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2134}
2135
2136// Make sure that URLRequest correctly adjusts connect times when they're before
2137// |request_start|, due to reusing a connected socket in the case that there
2138// are also proxy times. The connected socket is not considered reused in this
2139// test (May be a preconnect).
2140//
2141// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502142TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592143 base::TimeTicks now = base::TimeTicks::Now();
2144 LoadTimingInfo job_load_timing =
2145 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2146 job_load_timing.connect_timing.connect_start =
2147 now - base::TimeDelta::FromDays(1);
2148 job_load_timing.connect_timing.connect_end =
2149 now - base::TimeDelta::FromDays(2);
2150
[email protected]2ca01e52013-10-31 22:05:192151 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502152 RunURLRequestInterceptorLoadTimingTest(
2153 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592154
2155 // Connect times should be replaced with proxy_resolve_end.
2156 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2157 load_timing_result.connect_timing.connect_start);
2158 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2159 load_timing_result.connect_timing.connect_end);
2160
2161 // Other times should have been left null.
2162 TestLoadTimingNotReusedWithProxy(load_timing_result,
2163 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2164}
2165
[email protected]316c1e5e2012-09-12 15:17:442166// Check that two different URL requests have different identifiers.
2167TEST_F(URLRequestTest, Identifiers) {
2168 TestDelegate d;
2169 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362170 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362171 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362172 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362173 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442174
mmenke19378d22014-09-09 04:12:592175 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442176}
2177
blundellb8163592f2015-12-16 14:22:422178#if defined(OS_IOS)
2179// TODO(droger): Check that a failure to connect to the proxy is reported to
2180// the network delegate. crbug.com/496743
2181#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2182#else
2183#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2184#endif
2185TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442186 MockHostResolver host_resolver;
2187 host_resolver.rules()->AddSimulatedFailure("*");
2188
[email protected]ceefd7fd2012-11-29 00:36:242189 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442190 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2191
2192 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362193 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362194 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192195 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442196
[email protected]f7022f32014-08-21 16:32:192197 req->Start();
[email protected]255620da2013-08-19 13:14:292198 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442199
2200 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152201 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472202 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502203 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442204
2205 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012206 EXPECT_THAT(network_delegate.last_error(),
2207 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442208 EXPECT_EQ(1, network_delegate.completed_requests());
2209}
2210
[email protected]cba24642014-08-15 20:49:592211// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442212// content is empty.
2213TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2214 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362215 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362216 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192217 req->Start();
[email protected]255620da2013-08-19 13:14:292218 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442219 EXPECT_EQ("", d.data_received());
2220 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2221}
2222
[email protected]5033ab82013-03-22 20:17:462223// Make sure that SetPriority actually sets the URLRequest's priority
2224// correctly, both before and after start.
2225TEST_F(URLRequestTest, SetPriorityBasic) {
2226 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362227 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362228 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192229 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462230
[email protected]f7022f32014-08-21 16:32:192231 req->SetPriority(LOW);
2232 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462233
[email protected]f7022f32014-08-21 16:32:192234 req->Start();
2235 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462236
[email protected]f7022f32014-08-21 16:32:192237 req->SetPriority(MEDIUM);
2238 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462239}
2240
2241// Make sure that URLRequest calls SetPriority on a job before calling
2242// Start on it.
2243TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2244 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362245 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362246 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192247 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462248
mmenkeed0498b2015-12-08 23:20:422249 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362250 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422251 req.get(), &default_network_delegate_, &job_priority));
2252 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2253 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462254
[email protected]f7022f32014-08-21 16:32:192255 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462256
[email protected]f7022f32014-08-21 16:32:192257 req->Start();
mmenkeed0498b2015-12-08 23:20:422258 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462259}
2260
2261// Make sure that URLRequest passes on its priority updates to its
2262// job.
2263TEST_F(URLRequestTest, SetJobPriority) {
2264 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362265 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362266 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462267
mmenkeed0498b2015-12-08 23:20:422268 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362269 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422270 req.get(), &default_network_delegate_, &job_priority));
2271 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462272
[email protected]f7022f32014-08-21 16:32:192273 req->SetPriority(LOW);
2274 req->Start();
mmenkeed0498b2015-12-08 23:20:422275 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462276
[email protected]f7022f32014-08-21 16:32:192277 req->SetPriority(MEDIUM);
2278 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422279 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462280}
2281
[email protected]bb1c4662013-11-14 00:00:072282// Setting the IGNORE_LIMITS load flag should be okay if the priority
2283// is MAXIMUM_PRIORITY.
2284TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2285 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362286 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362287 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192288 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072289
mmenkeed0498b2015-12-08 23:20:422290 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362291 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422292 req.get(), &default_network_delegate_, &job_priority));
2293 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072294
[email protected]f7022f32014-08-21 16:32:192295 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2296 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072297
[email protected]f7022f32014-08-21 16:32:192298 req->SetPriority(MAXIMUM_PRIORITY);
2299 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072300
[email protected]f7022f32014-08-21 16:32:192301 req->Start();
2302 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422303 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072304}
2305
nick5d570de92015-05-04 20:16:162306namespace {
2307
2308// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552309class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442310 public:
tommycli59a63432015-11-06 00:10:552311 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2312 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272313 }
tommycli59a63432015-11-06 00:10:552314
2315 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2316};
tommyclieae5f75f2015-11-05 19:07:272317
nick5d570de92015-05-04 20:16:162318} // namespace
2319
[email protected]f2f31b32013-01-16 23:24:092320TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442321 LocalHttpTestServer test_server;
2322 ASSERT_TRUE(test_server.Start());
2323
2324 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362325 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502326 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442327
2328 // Set up a cookie.
2329 {
2330 TestNetworkDelegate network_delegate;
2331 context.set_network_delegate(&network_delegate);
2332 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362333 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552334 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362335 &d));
[email protected]f7022f32014-08-21 16:32:192336 req->Start();
[email protected]255620da2013-08-19 13:14:292337 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442338 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2339 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2340 EXPECT_EQ(1, network_delegate.set_cookie_count());
2341 }
2342
2343 // Verify that the cookie is set.
2344 {
2345 TestNetworkDelegate network_delegate;
2346 context.set_network_delegate(&network_delegate);
2347 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362348 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552349 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192350 req->Start();
[email protected]255620da2013-08-19 13:14:292351 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442352
2353 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2354 != std::string::npos);
2355 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2356 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2357 }
2358}
2359
[email protected]f2f31b32013-01-16 23:24:092360TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442361 LocalHttpTestServer test_server;
2362 ASSERT_TRUE(test_server.Start());
2363
2364 // Set up a cookie.
2365 {
2366 TestNetworkDelegate network_delegate;
2367 default_context_.set_network_delegate(&network_delegate);
2368 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362369 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552370 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362371 &d));
[email protected]f7022f32014-08-21 16:32:192372 req->Start();
[email protected]255620da2013-08-19 13:14:292373 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442374 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2375 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2376 }
2377
2378 // Verify that the cookie is set.
2379 {
2380 TestNetworkDelegate network_delegate;
2381 default_context_.set_network_delegate(&network_delegate);
2382 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362383 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552384 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192385 req->Start();
[email protected]255620da2013-08-19 13:14:292386 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442387
2388 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2389 != std::string::npos);
2390 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2391 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2392 }
2393
2394 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2395 {
2396 TestNetworkDelegate network_delegate;
2397 default_context_.set_network_delegate(&network_delegate);
2398 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362399 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552400 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192401 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2402 req->Start();
[email protected]255620da2013-08-19 13:14:292403 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442404
2405 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2406 == std::string::npos);
2407
2408 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2409 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2410 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2411 }
2412}
2413
2414TEST_F(URLRequestTest, DoNotSaveCookies) {
2415 LocalHttpTestServer test_server;
2416 ASSERT_TRUE(test_server.Start());
2417
2418 // Set up a cookie.
2419 {
2420 TestNetworkDelegate network_delegate;
2421 default_context_.set_network_delegate(&network_delegate);
2422 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362423 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552424 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362425 &d));
[email protected]f7022f32014-08-21 16:32:192426 req->Start();
[email protected]255620da2013-08-19 13:14:292427 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442428
2429 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2430 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2431 EXPECT_EQ(1, network_delegate.set_cookie_count());
2432 }
2433
2434 // Try to set-up another cookie and update the previous cookie.
2435 {
2436 TestNetworkDelegate network_delegate;
2437 default_context_.set_network_delegate(&network_delegate);
2438 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362439 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552440 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362441 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192442 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2443 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442444
[email protected]255620da2013-08-19 13:14:292445 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442446
2447 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2448 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2449 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2450 EXPECT_EQ(0, network_delegate.set_cookie_count());
2451 }
2452
2453 // Verify the cookies weren't saved or updated.
2454 {
2455 TestNetworkDelegate network_delegate;
2456 default_context_.set_network_delegate(&network_delegate);
2457 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362458 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552459 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192460 req->Start();
[email protected]255620da2013-08-19 13:14:292461 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442462
2463 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2464 == std::string::npos);
2465 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2466 != std::string::npos);
2467
2468 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2469 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2470 EXPECT_EQ(0, network_delegate.set_cookie_count());
2471 }
2472}
2473
2474TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2475 LocalHttpTestServer test_server;
2476 ASSERT_TRUE(test_server.Start());
2477
2478 // Set up a cookie.
2479 {
2480 TestNetworkDelegate network_delegate;
2481 default_context_.set_network_delegate(&network_delegate);
2482 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362483 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552484 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362485 &d));
[email protected]f7022f32014-08-21 16:32:192486 req->Start();
[email protected]255620da2013-08-19 13:14:292487 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442488
2489 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2490 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2491 }
2492
2493 // Verify that the cookie is set.
2494 {
2495 TestNetworkDelegate network_delegate;
2496 default_context_.set_network_delegate(&network_delegate);
2497 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362498 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552499 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192500 req->Start();
[email protected]255620da2013-08-19 13:14:292501 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442502
2503 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2504 != std::string::npos);
2505
2506 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2507 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2508 }
2509
2510 // Verify that the cookie isn't sent.
2511 {
2512 TestNetworkDelegate network_delegate;
2513 default_context_.set_network_delegate(&network_delegate);
2514 TestDelegate d;
2515 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362516 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552517 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192518 req->Start();
[email protected]255620da2013-08-19 13:14:292519 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442520
2521 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2522 == std::string::npos);
2523
[email protected]22e045f2013-09-20 03:54:032524 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442525 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2526 }
2527}
2528
marqf14fff8d2015-12-02 15:52:292529// TODO(crbug.com/564656) This test is flaky on iOS.
2530#if defined(OS_IOS)
2531#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2532#else
2533#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2534#endif
[email protected]316c1e5e2012-09-12 15:17:442535TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2536 LocalHttpTestServer test_server;
2537 ASSERT_TRUE(test_server.Start());
2538
2539 // Set up a cookie.
2540 {
2541 TestNetworkDelegate network_delegate;
2542 default_context_.set_network_delegate(&network_delegate);
2543 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362544 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552545 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362546 &d));
[email protected]f7022f32014-08-21 16:32:192547 req->Start();
[email protected]255620da2013-08-19 13:14:292548 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442549
2550 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2551 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2552 }
2553
2554 // Try to set-up another cookie and update the previous cookie.
2555 {
2556 TestNetworkDelegate network_delegate;
2557 default_context_.set_network_delegate(&network_delegate);
2558 TestDelegate d;
2559 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362560 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552561 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362562 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192563 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442564
[email protected]255620da2013-08-19 13:14:292565 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442566
2567 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2568 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2569 }
2570
2571 // Verify the cookies weren't saved or updated.
2572 {
2573 TestNetworkDelegate network_delegate;
2574 default_context_.set_network_delegate(&network_delegate);
2575 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362576 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552577 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192578 req->Start();
[email protected]255620da2013-08-19 13:14:292579 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442580
2581 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2582 == std::string::npos);
2583 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2584 != std::string::npos);
2585
2586 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2587 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2588 }
2589}
2590
2591TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2592 LocalHttpTestServer test_server;
2593 ASSERT_TRUE(test_server.Start());
2594
2595 // Set up an empty cookie.
2596 {
2597 TestNetworkDelegate network_delegate;
2598 default_context_.set_network_delegate(&network_delegate);
2599 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362600 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552601 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192602 req->Start();
[email protected]255620da2013-08-19 13:14:292603 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442604
2605 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2606 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2607 EXPECT_EQ(0, network_delegate.set_cookie_count());
2608 }
2609}
2610
2611TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2612 LocalHttpTestServer test_server;
2613 ASSERT_TRUE(test_server.Start());
2614
2615 // Set up a cookie.
2616 {
2617 TestNetworkDelegate network_delegate;
2618 default_context_.set_network_delegate(&network_delegate);
2619 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362620 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552621 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362622 &d));
[email protected]f7022f32014-08-21 16:32:192623 req->Start();
[email protected]255620da2013-08-19 13:14:292624 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442625
2626 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2627 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2628 }
2629
2630 // Verify that the cookie is set.
2631 {
2632 TestNetworkDelegate network_delegate;
2633 default_context_.set_network_delegate(&network_delegate);
2634 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362635 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552636 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192637 req->Start();
[email protected]255620da2013-08-19 13:14:292638 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442639
2640 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2641 != std::string::npos);
2642
2643 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2644 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2645 }
2646
2647 // Verify that the cookie isn't sent.
2648 {
2649 TestNetworkDelegate network_delegate;
2650 default_context_.set_network_delegate(&network_delegate);
2651 TestDelegate d;
2652 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362653 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552654 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192655 req->Start();
[email protected]255620da2013-08-19 13:14:292656 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442657
2658 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2659 == std::string::npos);
2660
[email protected]22e045f2013-09-20 03:54:032661 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442662 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2663 }
2664}
2665
2666TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2667 LocalHttpTestServer test_server;
2668 ASSERT_TRUE(test_server.Start());
2669
2670 // Set up a cookie.
2671 {
2672 TestNetworkDelegate network_delegate;
2673 default_context_.set_network_delegate(&network_delegate);
2674 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362675 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552676 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362677 &d));
[email protected]f7022f32014-08-21 16:32:192678 req->Start();
[email protected]255620da2013-08-19 13:14:292679 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442680
2681 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2682 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2683 }
2684
2685 // Try to set-up another cookie and update the previous cookie.
2686 {
2687 TestNetworkDelegate network_delegate;
2688 default_context_.set_network_delegate(&network_delegate);
2689 TestDelegate d;
2690 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362691 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552692 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362693 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192694 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442695
[email protected]255620da2013-08-19 13:14:292696 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442697
2698 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2699 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2700 }
2701
2702 // Verify the cookies weren't saved or updated.
2703 {
2704 TestNetworkDelegate network_delegate;
2705 default_context_.set_network_delegate(&network_delegate);
2706 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362707 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552708 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192709 req->Start();
[email protected]255620da2013-08-19 13:14:292710 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442711
2712 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2713 == std::string::npos);
2714 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2715 != std::string::npos);
2716
2717 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2718 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2719 }
2720}
2721
mkwstc5fa7762016-03-28 09:28:232722TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262723 LocalHttpTestServer test_server;
2724 ASSERT_TRUE(test_server.Start());
2725
mkwst202534e32016-01-15 16:07:152726 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152727 default_context_.set_network_delegate(&network_delegate);
2728
mkwstf71d0bd2016-03-21 14:15:242729 const std::string kHost = "example.test";
2730 const std::string kSubHost = "subdomain.example.test";
2731 const std::string kCrossHost = "cross-origin.test";
2732
2733 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262734 {
mkwst3f3daac2015-02-26 20:15:262735 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362736 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242737 test_server.GetURL(kHost,
2738 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2739 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362740 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262741 req->Start();
2742 base::RunLoop().Run();
2743 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2744 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242745 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262746 }
2747
mkwstf71d0bd2016-03-21 14:15:242748 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262749 {
mkwst3f3daac2015-02-26 20:15:262750 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362751 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242752 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2753 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2754 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262755 req->Start();
2756 base::RunLoop().Run();
2757
mkwstf71d0bd2016-03-21 14:15:242758 EXPECT_NE(std::string::npos,
2759 d.data_received().find("StrictSameSiteCookie=1"));
2760 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262761 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2762 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2763 }
2764
clamyfd58ca072016-12-21 17:18:322765 // Verify that both cookies are sent when the request has no initiator (can
2766 // happen for main frame browser-initiated navigations).
2767 {
2768 TestDelegate d;
2769 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
2770 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2771 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2772 req->Start();
2773 base::RunLoop().Run();
2774
2775 EXPECT_NE(std::string::npos,
2776 d.data_received().find("StrictSameSiteCookie=1"));
2777 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2778 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2779 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2780 }
2781
mkwstf71d0bd2016-03-21 14:15:242782 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262783 {
mkwst3f3daac2015-02-26 20:15:262784 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362785 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242786 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2787 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2788 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152789 req->Start();
2790 base::RunLoop().Run();
2791
mkwstf71d0bd2016-03-21 14:15:242792 EXPECT_NE(std::string::npos,
2793 d.data_received().find("StrictSameSiteCookie=1"));
2794 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152795 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2796 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2797 }
2798
mkwstf71d0bd2016-03-21 14:15:242799 // Verify that neither cookie is not sent for cross-site requests.
2800 {
2801 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362802 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242803 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2804 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2805 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2806 req->Start();
2807 base::RunLoop().Run();
2808
2809 EXPECT_EQ(std::string::npos,
2810 d.data_received().find("StrictSameSiteCookie=1"));
2811 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2812 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2813 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2814 }
2815
2816 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152817 // method is "safe".
2818 {
2819 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362820 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242821 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2822 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2823 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2824 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152825 req->Start();
2826 base::RunLoop().Run();
2827
mkwstf71d0bd2016-03-21 14:15:242828 EXPECT_EQ(std::string::npos,
2829 d.data_received().find("StrictSameSiteCookie=1"));
2830 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152831 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2832 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2833 }
2834
mkwstf71d0bd2016-03-21 14:15:242835 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152836 // method is unsafe (e.g. POST).
2837 {
2838 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362839 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242840 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2841 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2842 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152843 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262844 req->Start();
2845 base::RunLoop().Run();
2846
mkwstf71d0bd2016-03-21 14:15:242847 EXPECT_EQ(std::string::npos,
2848 d.data_received().find("StrictSameSiteCookie=1"));
2849 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262850 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2851 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2852 }
2853}
2854
estark557a5eb82015-12-01 22:57:102855// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362856TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552857 EmbeddedTestServer http_server;
2858 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362859 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552860 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2861 https_server.AddDefaultHandlers(
2862 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2863 ASSERT_TRUE(http_server.Start());
2864 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362865
estarkb15166b2015-12-18 16:56:382866 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362867 TestURLRequestContext context(true);
2868 context.set_network_delegate(&network_delegate);
2869 context.Init();
2870
estarkb15166b2015-12-18 16:56:382871 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362872 {
2873 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362874 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102875 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362876 DEFAULT_PRIORITY, &d));
2877 req->Start();
2878 base::RunLoop().Run();
2879 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2880 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2881 }
2882
2883 // Verify that the cookie is not set.
2884 {
2885 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362886 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552887 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362888 req->Start();
2889 base::RunLoop().Run();
2890
jww79aceda2015-12-07 01:56:342891 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2892 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362893 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2894 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2895 }
2896}
2897
estarkb15166b2015-12-18 16:56:382898TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552899 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2900 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362901 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552902 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362903
2904 TestNetworkDelegate network_delegate;
2905 TestURLRequestContext context(true);
2906 context.set_network_delegate(&network_delegate);
2907 context.Init();
2908
estarkb15166b2015-12-18 16:56:382909 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362910 {
2911 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362912 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102913 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552914 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362915 req->Start();
2916 base::RunLoop().Run();
2917 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2918 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2919 }
2920
2921 // Verify that the cookie is not set.
2922 {
2923 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362924 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552925 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362926 req->Start();
2927 base::RunLoop().Run();
2928
jww79aceda2015-12-07 01:56:342929 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362930 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2931 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2932 }
2933}
2934
estarkb15166b2015-12-18 16:56:382935TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552936 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2937 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362938 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552939 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362940
estarkb15166b2015-12-18 16:56:382941 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362942 TestURLRequestContext context(true);
2943 context.set_network_delegate(&network_delegate);
2944 context.Init();
2945
estarkb15166b2015-12-18 16:56:382946 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362947 {
2948 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362949 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102950 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552951 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362952 req->Start();
2953 base::RunLoop().Run();
2954 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2955 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2956 }
2957
2958 // Verify that the cookie is set.
2959 {
2960 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362961 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552962 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362963 req->Start();
2964 base::RunLoop().Run();
2965
jww79aceda2015-12-07 01:56:342966 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2967 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2968 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2969 }
2970}
2971
2972// Tests that secure cookies can't be set on non-secure origins if strict secure
2973// cookies are enabled.
2974TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2975 EmbeddedTestServer http_server;
2976 http_server.AddDefaultHandlers(
2977 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2978 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2979 https_server.AddDefaultHandlers(
2980 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2981 ASSERT_TRUE(http_server.Start());
2982 ASSERT_TRUE(https_server.Start());
2983
2984 TestExperimentalFeaturesNetworkDelegate network_delegate;
2985 TestURLRequestContext context(true);
2986 context.set_network_delegate(&network_delegate);
2987 context.Init();
2988
2989 // Try to set a Secure cookie, with experimental features enabled.
2990 {
2991 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362992 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342993 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2994 DEFAULT_PRIORITY, &d));
2995 req->Start();
2996 base::RunLoop().Run();
2997 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2998 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2999 }
3000
3001 // Verify that the cookie is not set.
3002 {
3003 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363004 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343005 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
3006 req->Start();
3007 base::RunLoop().Run();
3008
3009 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
3010 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3011 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3012 }
3013}
3014
3015// Tests that secure cookies can be set on secure origins even if strict secure
3016// cookies are enabled.
3017TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
3018 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
3019 https_server.AddDefaultHandlers(
3020 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3021 ASSERT_TRUE(https_server.Start());
3022
3023 TestExperimentalFeaturesNetworkDelegate network_delegate;
3024 TestURLRequestContext context(true);
3025 context.set_network_delegate(&network_delegate);
3026 context.Init();
3027
3028 // Try to set a Secure cookie, with experimental features enabled.
3029 {
3030 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363031 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343032 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
3033 DEFAULT_PRIORITY, &d));
3034 req->Start();
3035 base::RunLoop().Run();
3036 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3037 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3038 }
3039
3040 // Verify that the cookie is not set.
3041 {
3042 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363043 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:343044 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
3045 req->Start();
3046 base::RunLoop().Run();
3047
3048 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:363049 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
3050 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
3051 }
3052}
3053
mmenkefb18c772015-09-30 22:22:503054// Tests that a request is cancelled while entering suspend mode. Uses mocks
3055// rather than a spawned test server because the connection used to talk to
3056// the test server is affected by entering suspend mode on Android.
3057TEST_F(URLRequestTest, CancelOnSuspend) {
3058 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363059 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503060
3061 URLRequestFailedJob::AddUrlHandler();
3062
3063 TestDelegate d;
3064 // Request that just hangs.
3065 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:363066 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:503067 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3068 r->Start();
3069
3070 power_monitor_source->Suspend();
3071 // Wait for the suspend notification to cause the request to fail.
3072 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503073 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503074 EXPECT_TRUE(d.request_failed());
3075 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3076
3077 URLRequestFilter::GetInstance()->ClearHandlers();
3078
3079 // Shouldn't be needed, but just in case.
3080 power_monitor_source->Resume();
3081}
3082
[email protected]5095cd72012-11-01 10:29:163083// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3084// value for the |fixed_date| argument given to the constructor.
3085class FixedDateNetworkDelegate : public TestNetworkDelegate {
3086 public:
3087 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3088 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203089 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163090
[email protected]cba24642014-08-15 20:49:593091 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203092 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593093 URLRequest* request,
3094 const CompletionCallback& callback,
3095 const HttpResponseHeaders* original_response_headers,
3096 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133097 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163098
3099 private:
3100 std::string fixed_date_;
3101
3102 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3103};
3104
3105int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593106 URLRequest* request,
3107 const CompletionCallback& callback,
3108 const HttpResponseHeaders* original_response_headers,
3109 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163110 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593111 HttpResponseHeaders* new_response_headers =
3112 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163113
3114 new_response_headers->RemoveHeader("Date");
3115 new_response_headers->AddHeader("Date: " + fixed_date_);
3116
3117 *override_response_headers = new_response_headers;
3118 return TestNetworkDelegate::OnHeadersReceived(request,
3119 callback,
3120 original_response_headers,
[email protected]5f714132014-03-26 10:41:163121 override_response_headers,
3122 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163123}
3124
3125// Test that cookie expiration times are adjusted for server/client clock
3126// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3127// headers by defaulting to GMT. (crbug.com/135131)
3128TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3129 LocalHttpTestServer test_server;
3130 ASSERT_TRUE(test_server.Start());
3131
3132 // Set up an expired cookie.
3133 {
3134 TestNetworkDelegate network_delegate;
3135 default_context_.set_network_delegate(&network_delegate);
3136 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363137 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193138 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553139 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363140 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193141 req->Start();
[email protected]255620da2013-08-19 13:14:293142 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163143 }
3144 // Verify that the cookie is not set.
3145 {
3146 TestNetworkDelegate network_delegate;
3147 default_context_.set_network_delegate(&network_delegate);
3148 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363149 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553150 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193151 req->Start();
[email protected]255620da2013-08-19 13:14:293152 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163153
3154 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3155 }
3156 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3157 {
3158 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3159 default_context_.set_network_delegate(&network_delegate);
3160 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363161 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193162 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553163 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363164 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193165 req->Start();
[email protected]255620da2013-08-19 13:14:293166 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163167 }
3168 // Verify that the cookie is set.
3169 {
3170 TestNetworkDelegate network_delegate;
3171 default_context_.set_network_delegate(&network_delegate);
3172 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363173 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553174 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193175 req->Start();
[email protected]255620da2013-08-19 13:14:293176 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163177
3178 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3179 }
3180}
3181
3182
[email protected]316c1e5e2012-09-12 15:17:443183// Check that it is impossible to change the referrer in the extra headers of
3184// an URLRequest.
3185TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3186 LocalHttpTestServer test_server;
3187 ASSERT_TRUE(test_server.Start());
3188
3189 // If extra headers contain referer and the request contains a referer,
3190 // only the latter shall be respected.
3191 {
3192 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363193 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553194 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193195 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443196
3197 HttpRequestHeaders headers;
3198 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193199 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443200
[email protected]f7022f32014-08-21 16:32:193201 req->Start();
[email protected]255620da2013-08-19 13:14:293202 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443203
3204 EXPECT_EQ("http://foo.com/", d.data_received());
3205 }
3206
3207 // If extra headers contain a referer but the request does not, no referer
3208 // shall be sent in the header.
3209 {
3210 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363211 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553212 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443213
3214 HttpRequestHeaders headers;
3215 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193216 req->SetExtraRequestHeaders(headers);
3217 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443218
[email protected]f7022f32014-08-21 16:32:193219 req->Start();
[email protected]255620da2013-08-19 13:14:293220 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443221
3222 EXPECT_EQ("None", d.data_received());
3223 }
3224}
3225
[email protected]b89290212009-08-14 22:37:353226class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113227 public:
mmenke9f2ec60c2015-06-01 20:59:473228 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113229
[email protected]b89290212009-08-14 22:37:353230 protected:
[email protected]21184962011-10-26 00:50:303231 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3232 // |request_method| is the method to use for the initial request.
3233 // |redirect_method| is the method that is expected to be used for the second
3234 // request, after redirection.
3235 // If |include_data| is true, data is uploaded with the request. The
3236 // response body is expected to match it exactly, if and only if
3237 // |request_method| == |redirect_method|.
3238 void HTTPRedirectMethodTest(const GURL& redirect_url,
3239 const std::string& request_method,
3240 const std::string& redirect_method,
3241 bool include_data) {
3242 static const char kData[] = "hello world";
3243 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363244 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363245 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193246 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303247 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073248 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303249 HttpRequestHeaders headers;
3250 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513251 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543252 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193253 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303254 }
[email protected]f7022f32014-08-21 16:32:193255 req->Start();
[email protected]255620da2013-08-19 13:14:293256 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193257 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503258 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303259 if (include_data) {
3260 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543261 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3262 HttpRequestHeaders::kContentLength));
3263 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3264 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303265 EXPECT_EQ(kData, d.data_received());
3266 } else {
svaldez5b3a8972015-10-09 23:23:543267 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3268 HttpRequestHeaders::kContentLength));
3269 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3270 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303271 EXPECT_NE(kData, d.data_received());
3272 }
3273 }
3274 if (HasFailure())
3275 LOG(WARNING) << "Request method was: " << request_method;
3276 }
3277
jww5fe460ff2015-03-28 00:22:513278 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3279 // |request_method| is the method to use for the initial request.
3280 // |redirect_method| is the method that is expected to be used for the second
3281 // request, after redirection.
3282 // |origin_value| is the expected value for the Origin header after
3283 // redirection. If empty, expects that there will be no Origin header.
3284 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3285 const std::string& request_method,
3286 const std::string& redirect_method,
3287 const std::string& origin_value) {
3288 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363289 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513290 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3291 req->set_method(request_method);
3292 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3293 redirect_url.GetOrigin().spec(), false);
3294 req->Start();
3295
3296 base::RunLoop().Run();
3297
3298 EXPECT_EQ(redirect_method, req->method());
3299 // Note that there is no check for request success here because, for
3300 // purposes of testing, the request very well may fail. For example, if the
3301 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3302 // origin, there is not an HTTPS server in this unit test framework, so the
3303 // request would fail. However, that's fine, as long as the request headers
3304 // are in order and pass the checks below.
3305 if (origin_value.empty()) {
3306 EXPECT_FALSE(
3307 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3308 } else {
3309 std::string origin_header;
3310 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3311 HttpRequestHeaders::kOrigin, &origin_header));
3312 EXPECT_EQ(origin_value, origin_header);
3313 }
3314 }
3315
[email protected]762d2db2010-01-11 19:03:013316 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013317 const int kMsgSize = 20000; // multiple of 10
3318 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483319 char* uploadBytes = new char[kMsgSize+1];
3320 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013321 char marker = 'a';
3322 for (int idx = 0; idx < kMsgSize/10; idx++) {
3323 memcpy(ptr, "----------", 10);
3324 ptr += 10;
3325 if (idx % 100 == 0) {
3326 ptr--;
3327 *ptr++ = marker;
3328 if (++marker > 'z')
3329 marker = 'a';
3330 }
3331 }
3332 uploadBytes[kMsgSize] = '\0';
3333
[email protected]762d2db2010-01-11 19:03:013334 for (int i = 0; i < kIterations; ++i) {
3335 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363336 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553337 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193338 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013339
mmenkecbc2b712014-10-09 20:29:073340 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013341
[email protected]f7022f32014-08-21 16:32:193342 r->Start();
3343 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013344
[email protected]255620da2013-08-19 13:14:293345 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013346
maksim.sisovb53724b52016-09-16 05:30:503347 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3348 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013349
3350 EXPECT_FALSE(d.received_data_before_response());
3351 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013352 }
3353 delete[] uploadBytes;
3354 }
3355
[email protected]ede03212012-09-07 12:52:263356 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343357 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363358 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553359 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363360 base::IntToString(num_cookies)),
3361 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343362
[email protected]f7022f32014-08-21 16:32:193363 r->Start();
3364 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343365
[email protected]255620da2013-08-19 13:14:293366 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343367
maksim.sisovb53724b52016-09-16 05:30:503368 if (d.request_status() != OK) {
3369 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3370 return false;
3371 }
[email protected]263163f2012-06-14 22:40:343372
maksim.sisovb53724b52016-09-16 05:30:503373 return true;
[email protected]263163f2012-06-14 22:40:343374 }
3375
tommycli59a63432015-11-06 00:10:553376 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503377
tommycli59a63432015-11-06 00:10:553378 private:
[email protected]1700c6a2012-02-22 18:07:073379 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353380};
3381
tommycli59a63432015-11-06 00:10:553382namespace {
3383
danakj8522a25b2016-04-16 00:17:363384std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553385 const test_server::HttpRequest& request) {
3386 if (request.headers.find("Host") == request.headers.end() ||
3387 request.headers.at("Host") != "www.redirect.com" ||
3388 request.method != test_server::METHOD_CONNECT) {
3389 return nullptr;
3390 }
3391
danakj8522a25b2016-04-16 00:17:363392 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553393 new test_server::BasicHttpResponse);
3394 http_response->set_code(HTTP_FOUND);
3395 http_response->AddCustomHeader("Location",
3396 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483397 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553398}
3399
3400} // namespace
3401
nharperb7441ef2016-01-25 23:54:143402class TestSSLConfigService : public SSLConfigService {
3403 public:
3404 TestSSLConfigService(bool ev_enabled,
3405 bool online_rev_checking,
3406 bool rev_checking_required_local_anchors,
3407 bool token_binding_enabled)
3408 : ev_enabled_(ev_enabled),
3409 online_rev_checking_(online_rev_checking),
3410 rev_checking_required_local_anchors_(
3411 rev_checking_required_local_anchors),
3412 token_binding_enabled_(token_binding_enabled),
davidben5a312152016-06-27 22:11:473413 min_version_(kDefaultSSLVersionMin) {}
nharperb7441ef2016-01-25 23:54:143414
3415 void set_min_version(uint16_t version) { min_version_ = version; }
3416
nharperb7441ef2016-01-25 23:54:143417 // SSLConfigService:
3418 void GetSSLConfig(SSLConfig* config) override {
3419 *config = SSLConfig();
3420 config->rev_checking_enabled = online_rev_checking_;
3421 config->verify_ev_cert = ev_enabled_;
3422 config->rev_checking_required_local_anchors =
3423 rev_checking_required_local_anchors_;
nharperb7441ef2016-01-25 23:54:143424 if (min_version_) {
3425 config->version_min = min_version_;
3426 }
3427 if (token_binding_enabled_) {
3428 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3429 }
3430 }
3431
3432 protected:
3433 ~TestSSLConfigService() override {}
3434
3435 private:
3436 const bool ev_enabled_;
3437 const bool online_rev_checking_;
3438 const bool rev_checking_required_local_anchors_;
3439 const bool token_binding_enabled_;
3440 uint16_t min_version_;
nharperb7441ef2016-01-25 23:54:143441};
3442
3443// TODO(svaldez): Update tests to use EmbeddedTestServer.
3444#if !defined(OS_IOS)
3445class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3446 public:
3447 void SetUp() override {
3448 default_context_.set_ssl_config_service(
3449 new TestSSLConfigService(false, false, false, true));
3450 channel_id_service_.reset(new ChannelIDService(
3451 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3452 default_context_.set_channel_id_service(channel_id_service_.get());
3453 URLRequestTestHTTP::SetUp();
3454 }
3455
3456 protected:
danakj8522a25b2016-04-16 00:17:363457 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143458};
3459
3460TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3461 SpawnedTestServer::SSLOptions ssl_options;
3462 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3463 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3464 ssl_options,
3465 base::FilePath(kTestFilePath));
3466 ASSERT_TRUE(https_test_server.Start());
3467
3468 TestDelegate d;
3469 {
danakj8522a25b2016-04-16 00:17:363470 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143471 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3472 r->Start();
3473 EXPECT_TRUE(r->is_pending());
3474
3475 base::RunLoop().Run();
3476
maksim.sisovb53724b52016-09-16 05:30:503477 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143478
3479 HttpRequestHeaders headers;
3480 std::string token_binding_header, token_binding_message;
3481 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3482 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3483 &token_binding_header));
3484 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353485 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143486 &token_binding_message));
nharperd6e65822016-03-30 23:05:483487 std::vector<TokenBinding> token_bindings;
3488 ASSERT_TRUE(
3489 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3490 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143491
3492 EXPECT_GT(d.bytes_received(), 0);
3493 std::string ekm = d.data_received();
3494
nharperd6e65822016-03-30 23:05:483495 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353496 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3497 token_bindings[0].signature,
3498 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143499 }
3500}
nharperd6e65822016-03-30 23:05:483501
3502TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3503 SpawnedTestServer::SSLOptions ssl_options;
3504 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3505 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3506 ssl_options,
3507 base::FilePath(kTestFilePath));
3508 ASSERT_TRUE(https_test_server.Start());
3509
3510 TestDelegate d;
3511 {
3512 GURL redirect_url =
3513 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363514 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483515 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3516 r->Start();
3517 EXPECT_TRUE(r->is_pending());
3518
3519 base::RunLoop().Run();
3520
maksim.sisovb53724b52016-09-16 05:30:503521 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483522
3523 HttpRequestHeaders headers;
3524 std::string token_binding_header, token_binding_message;
3525 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3526 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3527 &token_binding_header));
3528 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353529 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483530 &token_binding_message));
3531 std::vector<TokenBinding> token_bindings;
3532 ASSERT_TRUE(
3533 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3534 ASSERT_EQ(2ull, token_bindings.size());
3535
3536 EXPECT_GT(d.bytes_received(), 0);
3537 std::string ekm = d.data_received();
3538
3539 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353540 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3541 token_bindings[0].signature,
3542 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483543 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353544 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3545 token_bindings[1].signature,
3546 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483547 }
3548}
3549
3550// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3551// EmbeddedTestServer once crbug.com/599187 is resolved.
3552#if !defined(OS_ANDROID)
3553TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3554 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3555 SpawnedTestServer::kLocalhost,
3556 base::FilePath());
3557 ASSERT_TRUE(http_server.Start());
3558 SpawnedTestServer::SSLOptions ssl_options;
3559 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3560 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3561 ssl_options,
3562 base::FilePath(kTestFilePath));
3563 ASSERT_TRUE(https_test_server.Start());
3564
3565 TestDelegate d;
3566 {
3567 GURL redirect_url = http_server.GetURL(
3568 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363569 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483570 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3571 r->Start();
3572 EXPECT_TRUE(r->is_pending());
3573
3574 base::RunLoop().Run();
3575
maksim.sisovb53724b52016-09-16 05:30:503576 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483577
3578 HttpRequestHeaders headers;
3579 std::string token_binding_header, token_binding_message;
3580 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3581 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3582 &token_binding_header));
3583 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353584 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483585 &token_binding_message));
3586 std::vector<TokenBinding> token_bindings;
3587 ASSERT_TRUE(
3588 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3589 ASSERT_EQ(1ull, token_bindings.size());
3590
3591 EXPECT_GT(d.bytes_received(), 0);
3592 std::string ekm = d.data_received();
3593
3594 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353595 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3596 token_bindings[0].signature,
3597 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483598 }
3599}
3600
3601// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363602// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483603// support Token Binding, then we do not send a Sec-Token-Binding when following
3604// the redirect.
3605TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3606 SpawnedTestServer::SSLOptions ssl_options;
3607 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3608 ssl_options,
3609 base::FilePath(kTestFilePath));
3610 ASSERT_TRUE(https_test_server.Start());
3611 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3612 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3613 ssl_options,
3614 base::FilePath(kTestFilePath));
3615 ASSERT_TRUE(token_binding_test_server.Start());
3616
3617 TestDelegate d;
3618 {
3619 GURL redirect_url = token_binding_test_server.GetURL(
3620 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363621 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483622 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3623 r->Start();
3624 EXPECT_TRUE(r->is_pending());
3625
3626 base::RunLoop().Run();
3627
maksim.sisovb53724b52016-09-16 05:30:503628 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483629
3630 HttpRequestHeaders headers;
3631 std::string token_binding_header, token_binding_message;
3632 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3633 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3634 &token_binding_header));
3635 }
3636}
3637#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143638#endif // !defined(OS_IOS)
3639
3640// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113641// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553642// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113643// follow.
[email protected]f2f31b32013-01-16 23:24:093644TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553645 http_test_server()->RegisterRequestHandler(
3646 base::Bind(&HandleRedirectConnect));
3647 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113648
[email protected]ceefd7fd2012-11-29 00:36:243649 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043650 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553651 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503652
[email protected]d1ec59082009-02-11 02:48:153653 TestDelegate d;
3654 {
danakj8522a25b2016-04-16 00:17:363655 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363656 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193657 r->Start();
3658 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153659
[email protected]255620da2013-08-19 13:14:293660 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153661
[email protected]d8fc4722014-06-13 13:17:153662 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473663 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503664 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083665 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153666 // We should not have followed the redirect.
3667 EXPECT_EQ(0, d.received_redirect_count());
3668 }
3669}
3670
[email protected]8202d0c2011-02-23 08:31:143671// This is the same as the previous test, but checks that the network delegate
3672// registers the error.
[email protected]c044616e2013-02-20 02:01:263673TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553674 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143675
[email protected]ceefd7fd2012-11-29 00:36:243676 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043677 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553678 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503679
[email protected]8202d0c2011-02-23 08:31:143680 TestDelegate d;
3681 {
danakj8522a25b2016-04-16 00:17:363682 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363683 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193684 r->Start();
3685 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143686
[email protected]255620da2013-08-19 13:14:293687 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143688
[email protected]d8fc4722014-06-13 13:17:153689 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473690 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:143691 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:503692 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:143693 // We should not have followed the redirect.
3694 EXPECT_EQ(0, d.received_redirect_count());
3695
3696 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:013697 EXPECT_THAT(network_delegate.last_error(),
3698 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143699 }
3700}
3701
[email protected]dc5a5cf2012-09-26 02:49:303702// Tests that we can block and asynchronously return OK in various stages.
3703TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3704 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3705 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3706 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3707 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3708 };
3709 static const size_t blocking_stages_length = arraysize(blocking_stages);
3710
tommycli59a63432015-11-06 00:10:553711 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303712
3713 TestDelegate d;
3714 BlockingNetworkDelegate network_delegate(
3715 BlockingNetworkDelegate::USER_CALLBACK);
3716 network_delegate.set_block_on(
3717 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3718 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3719 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3720
3721 TestURLRequestContext context(true);
3722 context.set_network_delegate(&network_delegate);
3723 context.Init();
3724
3725 {
danakj8522a25b2016-04-16 00:17:363726 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553727 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303728
[email protected]f7022f32014-08-21 16:32:193729 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303730 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293731 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303732 EXPECT_EQ(blocking_stages[i],
3733 network_delegate.stage_blocked_for_callback());
3734 network_delegate.DoCallback(OK);
3735 }
[email protected]255620da2013-08-19 13:14:293736 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193737 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:503738 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:303739 EXPECT_EQ(1, network_delegate.created_requests());
3740 EXPECT_EQ(0, network_delegate.destroyed_requests());
3741 }
3742 EXPECT_EQ(1, network_delegate.destroyed_requests());
3743}
3744
[email protected]4c76d7c2011-04-15 19:14:123745// Tests that the network delegate can block and cancel a request.
3746TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553747 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123748
3749 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303750 BlockingNetworkDelegate network_delegate(
3751 BlockingNetworkDelegate::AUTO_CALLBACK);
3752 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3753 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123754
[email protected]d5a4dd62012-05-23 01:41:043755 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553756 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503757
[email protected]4c76d7c2011-04-15 19:14:123758 {
danakj8522a25b2016-04-16 00:17:363759 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553760 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123761
[email protected]f7022f32014-08-21 16:32:193762 r->Start();
[email protected]255620da2013-08-19 13:14:293763 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123764
[email protected]d8fc4722014-06-13 13:17:153765 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473766 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503767 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:123768 EXPECT_EQ(1, network_delegate.created_requests());
3769 EXPECT_EQ(0, network_delegate.destroyed_requests());
3770 }
3771 EXPECT_EQ(1, network_delegate.destroyed_requests());
3772}
3773
[email protected]b4438d32012-09-27 06:15:303774// Helper function for NetworkDelegateCancelRequestAsynchronously and
3775// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3776// delegate operating in |block_mode| and a request for |url|. It blocks the
3777// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3778void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3779 BlockingNetworkDelegate::Stage stage,
3780 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363781 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303782 BlockingNetworkDelegate network_delegate(block_mode);
3783 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3784 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363785
[email protected]b4438d32012-09-27 06:15:303786 TestURLRequestContext context(true);
3787 context.set_network_delegate(&network_delegate);
3788 context.Init();
[email protected]3cd384c602011-08-31 16:12:363789
3790 {
danakj8522a25b2016-04-16 00:17:363791 std::unique_ptr<URLRequest> r(
3792 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363793
[email protected]f7022f32014-08-21 16:32:193794 r->Start();
[email protected]255620da2013-08-19 13:14:293795 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363796
[email protected]d8fc4722014-06-13 13:17:153797 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473798 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
3799 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
3800 EXPECT_FALSE(r->proxy_server().is_valid());
3801 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
3802 EXPECT_TRUE(r->proxy_server().is_direct());
3803 } else {
3804 NOTREACHED();
3805 }
maksim.sisovb53724b52016-09-16 05:30:503806 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:363807 EXPECT_EQ(1, network_delegate.created_requests());
3808 EXPECT_EQ(0, network_delegate.destroyed_requests());
3809 }
3810 EXPECT_EQ(1, network_delegate.destroyed_requests());
3811}
3812
[email protected]b4438d32012-09-27 06:15:303813// The following 3 tests check that the network delegate can cancel a request
3814// synchronously in various stages of the request.
3815TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553816 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303817 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3818 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553819 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303820}
3821
3822TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553823 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303824 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3825 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553826 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303827}
3828
3829TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553830 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303831 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3832 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553833 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303834}
3835
3836// The following 3 tests check that the network delegate can cancel a request
3837// asynchronously in various stages of the request.
3838TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553839 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303840 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3841 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553842 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303843}
3844
3845TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553846 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303847 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3848 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553849 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303850}
3851
3852TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553853 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303854 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3855 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553856 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303857}
3858
[email protected]4c76d7c2011-04-15 19:14:123859// Tests that the network delegate can block and redirect a request to a new
3860// URL.
3861TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553862 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123863
3864 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303865 BlockingNetworkDelegate network_delegate(
3866 BlockingNetworkDelegate::AUTO_CALLBACK);
3867 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553868 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123869 network_delegate.set_redirect_url(redirect_url);
3870
[email protected]d5a4dd62012-05-23 01:41:043871 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553872 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503873
[email protected]4c76d7c2011-04-15 19:14:123874 {
tommycli59a63432015-11-06 00:10:553875 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363876 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363877 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123878
[email protected]6be6fa92014-08-06 23:44:563879 // Quit after hitting the redirect, so can check the headers.
3880 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193881 r->Start();
[email protected]255620da2013-08-19 13:14:293882 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123883
[email protected]6be6fa92014-08-06 23:44:563884 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193885 EXPECT_EQ(307, r->GetResponseCode());
3886 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563887 std::string location;
[email protected]f7022f32014-08-21 16:32:193888 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3889 &location));
[email protected]6be6fa92014-08-06 23:44:563890 EXPECT_EQ(redirect_url, GURL(location));
3891
3892 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193893 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563894 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503895 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473896 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3897 http_test_server()->host_port_pair()),
3898 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093899 // before_send_headers_with_proxy_count only increments for headers sent
3900 // through an untunneled proxy.
3901 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553902 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3903 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273904
maksim.sisovb53724b52016-09-16 05:30:503905 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193906 EXPECT_EQ(redirect_url, r->url());
3907 EXPECT_EQ(original_url, r->original_url());
3908 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123909 EXPECT_EQ(1, network_delegate.created_requests());
3910 EXPECT_EQ(0, network_delegate.destroyed_requests());
3911 }
3912 EXPECT_EQ(1, network_delegate.destroyed_requests());
3913}
3914
[email protected]b813ed72012-04-05 08:21:363915// Tests that the network delegate can block and redirect a request to a new
3916// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3917TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553918 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363919
3920 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303921 BlockingNetworkDelegate network_delegate(
3922 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553923 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363924 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363925
[email protected]d5a4dd62012-05-23 01:41:043926 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553927 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363928
3929 {
tommycli59a63432015-11-06 00:10:553930 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363931 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363932 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363933
[email protected]6be6fa92014-08-06 23:44:563934 // Quit after hitting the redirect, so can check the headers.
3935 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193936 r->Start();
[email protected]255620da2013-08-19 13:14:293937 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363938
[email protected]6be6fa92014-08-06 23:44:563939 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193940 EXPECT_EQ(307, r->GetResponseCode());
3941 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563942 std::string location;
[email protected]f7022f32014-08-21 16:32:193943 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3944 &location));
[email protected]6be6fa92014-08-06 23:44:563945 EXPECT_EQ(redirect_url, GURL(location));
3946
3947 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193948 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563949 base::RunLoop().Run();
3950
maksim.sisovb53724b52016-09-16 05:30:503951 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473952 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3953 http_test_server()->host_port_pair()),
3954 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093955 // before_send_headers_with_proxy_count only increments for headers sent
3956 // through an untunneled proxy.
3957 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553958 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3959 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:503960 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193961 EXPECT_EQ(redirect_url, r->url());
3962 EXPECT_EQ(original_url, r->original_url());
3963 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363964 EXPECT_EQ(1, network_delegate.created_requests());
3965 EXPECT_EQ(0, network_delegate.destroyed_requests());
3966 }
3967 EXPECT_EQ(1, network_delegate.destroyed_requests());
3968}
3969
[email protected]3c5ca8c2011-09-29 01:14:513970// Tests that redirects caused by the network delegate preserve POST data.
3971TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553972 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513973
3974 const char kData[] = "hello world";
3975
3976 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303977 BlockingNetworkDelegate network_delegate(
3978 BlockingNetworkDelegate::AUTO_CALLBACK);
3979 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553980 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513981 network_delegate.set_redirect_url(redirect_url);
3982
[email protected]ef2bf422012-05-11 03:27:093983 TestURLRequestContext context(true);
3984 context.set_network_delegate(&network_delegate);
3985 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513986
3987 {
tommycli59a63432015-11-06 00:10:553988 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363989 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363990 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193991 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073992 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513993 HttpRequestHeaders headers;
3994 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513995 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193996 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563997
3998 // Quit after hitting the redirect, so can check the headers.
3999 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:194000 r->Start();
[email protected]255620da2013-08-19 13:14:294001 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:514002
[email protected]6be6fa92014-08-06 23:44:564003 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:194004 EXPECT_EQ(307, r->GetResponseCode());
4005 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:564006 std::string location;
[email protected]f7022f32014-08-21 16:32:194007 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
4008 &location));
[email protected]6be6fa92014-08-06 23:44:564009 EXPECT_EQ(redirect_url, GURL(location));
4010
4011 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:194012 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:564013 base::RunLoop().Run();
4014
maksim.sisovb53724b52016-09-16 05:30:504015 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194016 EXPECT_EQ(redirect_url, r->url());
4017 EXPECT_EQ(original_url, r->original_url());
4018 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:514019 EXPECT_EQ(1, network_delegate.created_requests());
4020 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:194021 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:514022 EXPECT_EQ(kData, d.data_received());
4023 }
4024 EXPECT_EQ(1, network_delegate.destroyed_requests());
4025}
4026
[email protected]5f714132014-03-26 10:41:164027// Tests that the network delegate can block and redirect a request to a new
4028// URL during OnHeadersReceived.
4029TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:554030 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:164031
4032 TestDelegate d;
4033 BlockingNetworkDelegate network_delegate(
4034 BlockingNetworkDelegate::AUTO_CALLBACK);
4035 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:554036 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:164037 network_delegate.set_redirect_on_headers_received_url(redirect_url);
4038
4039 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554040 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:164041
4042 {
tommycli59a63432015-11-06 00:10:554043 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364044 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364045 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:164046
[email protected]f7022f32014-08-21 16:32:194047 r->Start();
[email protected]5f714132014-03-26 10:41:164048 base::RunLoop().Run();
4049
maksim.sisovb53724b52016-09-16 05:30:504050 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:474051 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
4052 http_test_server()->host_port_pair()),
4053 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:094054 // before_send_headers_with_proxy_count only increments for headers sent
4055 // through an untunneled proxy.
4056 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554057 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4058 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194059
maksim.sisovb53724b52016-09-16 05:30:504060 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194061 EXPECT_EQ(redirect_url, r->url());
4062 EXPECT_EQ(original_url, r->original_url());
4063 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164064 EXPECT_EQ(2, network_delegate.created_requests());
4065 EXPECT_EQ(0, network_delegate.destroyed_requests());
4066 }
4067 EXPECT_EQ(1, network_delegate.destroyed_requests());
4068}
4069
[email protected]c2911d72011-10-03 22:16:364070// Tests that the network delegate can synchronously complete OnAuthRequired
4071// by taking no action. This indicates that the NetworkDelegate does not want to
4072// handle the challenge, and is passing the buck along to the
4073// URLRequest::Delegate.
4074TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554075 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364076
4077 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304078 BlockingNetworkDelegate network_delegate(
4079 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364080
[email protected]ef2bf422012-05-11 03:27:094081 TestURLRequestContext context(true);
4082 context.set_network_delegate(&network_delegate);
4083 context.Init();
[email protected]c2911d72011-10-03 22:16:364084
[email protected]f3cf9802011-10-28 18:44:584085 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364086
4087 {
tommycli59a63432015-11-06 00:10:554088 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364089 std::unique_ptr<URLRequest> r(
4090 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194091 r->Start();
[email protected]79e1fd62013-06-20 06:50:044092
[email protected]255620da2013-08-19 13:14:294093 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044094
maksim.sisovb53724b52016-09-16 05:30:504095 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194096 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044097 EXPECT_TRUE(d.auth_required_called());
4098 EXPECT_EQ(1, network_delegate.created_requests());
4099 EXPECT_EQ(0, network_delegate.destroyed_requests());
4100 }
4101 EXPECT_EQ(1, network_delegate.destroyed_requests());
4102}
4103
4104TEST_F(URLRequestTestHTTP,
4105 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554106 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044107
4108 TestDelegate d;
4109 BlockingNetworkDelegate network_delegate(
4110 BlockingNetworkDelegate::SYNCHRONOUS);
4111
4112 TestURLRequestContext context(true);
4113 context.set_network_delegate(&network_delegate);
4114 context.Init();
4115
4116 d.set_credentials(AuthCredentials(kUser, kSecret));
4117
4118 {
tommycli59a63432015-11-06 00:10:554119 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364120 std::unique_ptr<URLRequest> r(
4121 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194122 r->Start();
[email protected]79e1fd62013-06-20 06:50:044123
4124 {
4125 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194126 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044127 EXPECT_FALSE(headers.HasHeader("Authorization"));
4128 }
4129
[email protected]255620da2013-08-19 13:14:294130 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364131
maksim.sisovb53724b52016-09-16 05:30:504132 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194133 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364134 EXPECT_TRUE(d.auth_required_called());
4135 EXPECT_EQ(1, network_delegate.created_requests());
4136 EXPECT_EQ(0, network_delegate.destroyed_requests());
4137 }
4138 EXPECT_EQ(1, network_delegate.destroyed_requests());
4139}
4140
4141// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404142// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364143TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554144 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364145
4146 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304147 BlockingNetworkDelegate network_delegate(
4148 BlockingNetworkDelegate::SYNCHRONOUS);
4149 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364150 network_delegate.set_auth_retval(
4151 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4152
[email protected]f3cf9802011-10-28 18:44:584153 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364154
[email protected]ef2bf422012-05-11 03:27:094155 TestURLRequestContext context(true);
4156 context.set_network_delegate(&network_delegate);
4157 context.Init();
[email protected]c2911d72011-10-03 22:16:364158
4159 {
tommycli59a63432015-11-06 00:10:554160 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364161 std::unique_ptr<URLRequest> r(
4162 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194163 r->Start();
[email protected]255620da2013-08-19 13:14:294164 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364165
maksim.sisovb53724b52016-09-16 05:30:504166 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194167 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364168 EXPECT_FALSE(d.auth_required_called());
4169 EXPECT_EQ(1, network_delegate.created_requests());
4170 EXPECT_EQ(0, network_delegate.destroyed_requests());
4171 }
4172 EXPECT_EQ(1, network_delegate.destroyed_requests());
4173}
4174
[email protected]79e1fd62013-06-20 06:50:044175// Same as above, but also tests that GetFullRequestHeaders returns the proper
4176// headers (for the first or second request) when called at the proper times.
4177TEST_F(URLRequestTestHTTP,
4178 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554179 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044180
4181 TestDelegate d;
4182 BlockingNetworkDelegate network_delegate(
4183 BlockingNetworkDelegate::SYNCHRONOUS);
4184 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4185 network_delegate.set_auth_retval(
4186 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4187
4188 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4189
4190 TestURLRequestContext context(true);
4191 context.set_network_delegate(&network_delegate);
4192 context.Init();
4193
4194 {
tommycli59a63432015-11-06 00:10:554195 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364196 std::unique_ptr<URLRequest> r(
4197 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194198 r->Start();
[email protected]255620da2013-08-19 13:14:294199 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044200
maksim.sisovb53724b52016-09-16 05:30:504201 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194202 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044203 EXPECT_FALSE(d.auth_required_called());
4204 EXPECT_EQ(1, network_delegate.created_requests());
4205 EXPECT_EQ(0, network_delegate.destroyed_requests());
4206
4207 {
4208 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194209 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044210 EXPECT_TRUE(headers.HasHeader("Authorization"));
4211 }
4212 }
4213 EXPECT_EQ(1, network_delegate.destroyed_requests());
4214}
4215
[email protected]c2911d72011-10-03 22:16:364216// Tests that the network delegate can synchronously complete OnAuthRequired
4217// by cancelling authentication.
4218TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554219 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364220
4221 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304222 BlockingNetworkDelegate network_delegate(
4223 BlockingNetworkDelegate::SYNCHRONOUS);
4224 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364225 network_delegate.set_auth_retval(
4226 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4227
[email protected]ef2bf422012-05-11 03:27:094228 TestURLRequestContext context(true);
4229 context.set_network_delegate(&network_delegate);
4230 context.Init();
[email protected]c2911d72011-10-03 22:16:364231
4232 {
tommycli59a63432015-11-06 00:10:554233 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364234 std::unique_ptr<URLRequest> r(
4235 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194236 r->Start();
[email protected]255620da2013-08-19 13:14:294237 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364238
maksim.sisovb53724b52016-09-16 05:30:504239 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194240 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364241 EXPECT_FALSE(d.auth_required_called());
4242 EXPECT_EQ(1, network_delegate.created_requests());
4243 EXPECT_EQ(0, network_delegate.destroyed_requests());
4244 }
4245 EXPECT_EQ(1, network_delegate.destroyed_requests());
4246}
4247
4248// Tests that the network delegate can asynchronously complete OnAuthRequired
4249// by taking no action. This indicates that the NetworkDelegate does not want
4250// to handle the challenge, and is passing the buck along to the
4251// URLRequest::Delegate.
4252TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554253 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364254
4255 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304256 BlockingNetworkDelegate network_delegate(
4257 BlockingNetworkDelegate::AUTO_CALLBACK);
4258 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364259
[email protected]ef2bf422012-05-11 03:27:094260 TestURLRequestContext context(true);
4261 context.set_network_delegate(&network_delegate);
4262 context.Init();
[email protected]c2911d72011-10-03 22:16:364263
[email protected]f3cf9802011-10-28 18:44:584264 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364265
4266 {
tommycli59a63432015-11-06 00:10:554267 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364268 std::unique_ptr<URLRequest> r(
4269 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194270 r->Start();
[email protected]255620da2013-08-19 13:14:294271 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364272
maksim.sisovb53724b52016-09-16 05:30:504273 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194274 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364275 EXPECT_TRUE(d.auth_required_called());
4276 EXPECT_EQ(1, network_delegate.created_requests());
4277 EXPECT_EQ(0, network_delegate.destroyed_requests());
4278 }
4279 EXPECT_EQ(1, network_delegate.destroyed_requests());
4280}
4281
4282// Tests that the network delegate can asynchronously complete OnAuthRequired
4283// by setting credentials.
4284TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554285 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364286
4287 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304288 BlockingNetworkDelegate network_delegate(
4289 BlockingNetworkDelegate::AUTO_CALLBACK);
4290 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364291 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364292 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4293
[email protected]f3cf9802011-10-28 18:44:584294 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364295 network_delegate.set_auth_credentials(auth_credentials);
4296
[email protected]ef2bf422012-05-11 03:27:094297 TestURLRequestContext context(true);
4298 context.set_network_delegate(&network_delegate);
4299 context.Init();
[email protected]c2911d72011-10-03 22:16:364300
4301 {
tommycli59a63432015-11-06 00:10:554302 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364303 std::unique_ptr<URLRequest> r(
4304 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194305 r->Start();
[email protected]255620da2013-08-19 13:14:294306 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364307
maksim.sisovb53724b52016-09-16 05:30:504308 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194309 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364310 EXPECT_FALSE(d.auth_required_called());
4311 EXPECT_EQ(1, network_delegate.created_requests());
4312 EXPECT_EQ(0, network_delegate.destroyed_requests());
4313 }
4314 EXPECT_EQ(1, network_delegate.destroyed_requests());
4315}
4316
4317// Tests that the network delegate can asynchronously complete OnAuthRequired
4318// by cancelling authentication.
4319TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554320 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364321
4322 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304323 BlockingNetworkDelegate network_delegate(
4324 BlockingNetworkDelegate::AUTO_CALLBACK);
4325 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364326 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364327 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4328
[email protected]ef2bf422012-05-11 03:27:094329 TestURLRequestContext context(true);
4330 context.set_network_delegate(&network_delegate);
4331 context.Init();
[email protected]c2911d72011-10-03 22:16:364332
4333 {
tommycli59a63432015-11-06 00:10:554334 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364335 std::unique_ptr<URLRequest> r(
4336 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194337 r->Start();
[email protected]255620da2013-08-19 13:14:294338 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364339
maksim.sisovb53724b52016-09-16 05:30:504340 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194341 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364342 EXPECT_FALSE(d.auth_required_called());
4343 EXPECT_EQ(1, network_delegate.created_requests());
4344 EXPECT_EQ(0, network_delegate.destroyed_requests());
4345 }
4346 EXPECT_EQ(1, network_delegate.destroyed_requests());
4347}
4348
[email protected]9045b8822012-01-13 20:35:354349// Tests that we can handle when a network request was canceled while we were
4350// waiting for the network delegate.
4351// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4352TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554353 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354354
4355 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304356 BlockingNetworkDelegate network_delegate(
4357 BlockingNetworkDelegate::USER_CALLBACK);
4358 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354359
[email protected]ef2bf422012-05-11 03:27:094360 TestURLRequestContext context(true);
4361 context.set_network_delegate(&network_delegate);
4362 context.Init();
[email protected]9045b8822012-01-13 20:35:354363
4364 {
danakj8522a25b2016-04-16 00:17:364365 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554366 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354367
[email protected]f7022f32014-08-21 16:32:194368 r->Start();
[email protected]255620da2013-08-19 13:14:294369 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304370 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4371 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354372 EXPECT_EQ(0, network_delegate.completed_requests());
4373 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194374 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354375 // Ensure that network delegate is notified.
4376 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504377 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354378 EXPECT_EQ(1, network_delegate.created_requests());
4379 EXPECT_EQ(0, network_delegate.destroyed_requests());
4380 }
4381 EXPECT_EQ(1, network_delegate.destroyed_requests());
4382}
4383
4384// Tests that we can handle when a network request was canceled while we were
4385// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004386// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4387// callback.
[email protected]9045b8822012-01-13 20:35:354388TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554389 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354390
4391 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304392 BlockingNetworkDelegate network_delegate(
4393 BlockingNetworkDelegate::USER_CALLBACK);
4394 network_delegate.set_block_on(
4395 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354396
[email protected]ef2bf422012-05-11 03:27:094397 TestURLRequestContext context(true);
4398 context.set_network_delegate(&network_delegate);
4399 context.Init();
[email protected]9045b8822012-01-13 20:35:354400
4401 {
danakj8522a25b2016-04-16 00:17:364402 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554403 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354404
[email protected]f7022f32014-08-21 16:32:194405 r->Start();
[email protected]255620da2013-08-19 13:14:294406 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304407 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4408 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354409 EXPECT_EQ(0, network_delegate.completed_requests());
4410 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194411 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354412 // Ensure that network delegate is notified.
4413 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504414 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354415 EXPECT_EQ(1, network_delegate.created_requests());
4416 EXPECT_EQ(0, network_delegate.destroyed_requests());
4417 }
4418 EXPECT_EQ(1, network_delegate.destroyed_requests());
4419}
4420
4421// Tests that we can handle when a network request was canceled while we were
4422// waiting for the network delegate.
4423// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4424TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554425 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354426
4427 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304428 BlockingNetworkDelegate network_delegate(
4429 BlockingNetworkDelegate::USER_CALLBACK);
4430 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354431
[email protected]ef2bf422012-05-11 03:27:094432 TestURLRequestContext context(true);
4433 context.set_network_delegate(&network_delegate);
4434 context.Init();
[email protected]9045b8822012-01-13 20:35:354435
4436 {
danakj8522a25b2016-04-16 00:17:364437 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554438 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354439
[email protected]f7022f32014-08-21 16:32:194440 r->Start();
[email protected]255620da2013-08-19 13:14:294441 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304442 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4443 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354444 EXPECT_EQ(0, network_delegate.completed_requests());
4445 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194446 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354447 // Ensure that network delegate is notified.
4448 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504449 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354450 EXPECT_EQ(1, network_delegate.created_requests());
4451 EXPECT_EQ(0, network_delegate.destroyed_requests());
4452 }
4453 EXPECT_EQ(1, network_delegate.destroyed_requests());
4454}
4455
4456// Tests that we can handle when a network request was canceled while we were
4457// waiting for the network delegate.
4458// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024459TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554460 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354461
4462 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304463 BlockingNetworkDelegate network_delegate(
4464 BlockingNetworkDelegate::USER_CALLBACK);
4465 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354466
[email protected]ef2bf422012-05-11 03:27:094467 TestURLRequestContext context(true);
4468 context.set_network_delegate(&network_delegate);
4469 context.Init();
[email protected]9045b8822012-01-13 20:35:354470
4471 {
danakj8522a25b2016-04-16 00:17:364472 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554473 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354474
[email protected]f7022f32014-08-21 16:32:194475 r->Start();
[email protected]255620da2013-08-19 13:14:294476 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304477 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4478 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354479 EXPECT_EQ(0, network_delegate.completed_requests());
4480 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194481 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354482 // Ensure that network delegate is notified.
4483 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504484 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354485 EXPECT_EQ(1, network_delegate.created_requests());
4486 EXPECT_EQ(0, network_delegate.destroyed_requests());
4487 }
4488 EXPECT_EQ(1, network_delegate.destroyed_requests());
4489}
4490
tommycli59a63432015-11-06 00:10:554491namespace {
4492
danakj8522a25b2016-04-16 00:17:364493std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554494 const test_server::HttpRequest& request) {
4495 if (request.headers.find("Host") == request.headers.end() ||
4496 request.headers.at("Host") != "www.server-auth.com" ||
4497 request.method != test_server::METHOD_CONNECT) {
4498 return nullptr;
4499 }
4500
danakj8522a25b2016-04-16 00:17:364501 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554502 new test_server::BasicHttpResponse);
4503 http_response->set_code(HTTP_UNAUTHORIZED);
4504 http_response->AddCustomHeader("WWW-Authenticate",
4505 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484506 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554507}
4508
4509} // namespace
4510
4511// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114512// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554513// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354514TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554515 http_test_server()->RegisterRequestHandler(
4516 base::Bind(&HandleServerAuthConnect));
4517 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114518
[email protected]ceefd7fd2012-11-29 00:36:244519 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044520 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554521 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504522
[email protected]dc651782009-02-14 01:45:084523 TestDelegate d;
4524 {
danakj8522a25b2016-04-16 00:17:364525 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364526 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084527
[email protected]f7022f32014-08-21 16:32:194528 r->Start();
4529 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084530
[email protected]255620da2013-08-19 13:14:294531 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084532
[email protected]d8fc4722014-06-13 13:17:154533 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474534 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504535 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084536 }
4537}
4538
[email protected]b89290212009-08-14 22:37:354539TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554540 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114541
initial.commit586acc5fe2008-07-26 22:42:524542 TestDelegate d;
4543 {
danakj8522a25b2016-04-16 00:17:364544 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554545 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524546
[email protected]f7022f32014-08-21 16:32:194547 r->Start();
4548 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524549
[email protected]255620da2013-08-19 13:14:294550 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524551
4552 EXPECT_EQ(1, d.response_started_count());
4553 EXPECT_FALSE(d.received_data_before_response());
4554 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554555 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194556 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554557 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194558 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164559
[email protected]9e743cd2010-03-16 07:03:534560 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524561 }
initial.commit586acc5fe2008-07-26 22:42:524562}
4563
[email protected]263163f2012-06-14 22:40:344564// This test has the server send a large number of cookies to the client.
4565// To ensure that no number of cookies causes a crash, a galloping binary
4566// search is used to estimate that maximum number of cookies that are accepted
4567// by the browser. Beyond the maximum number, the request will fail with
4568// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304569#if defined(OS_WIN)
4570// http://crbug.com/177916
4571#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4572#else
4573#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4574#endif // defined(OS_WIN)
4575TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554576 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344577
4578 int lower_bound = 0;
4579 int upper_bound = 1;
4580
4581 // Double the number of cookies until the response header limits are
4582 // exceeded.
4583 while (DoManyCookiesRequest(upper_bound)) {
4584 lower_bound = upper_bound;
4585 upper_bound *= 2;
4586 ASSERT_LT(upper_bound, 1000000);
4587 }
4588
pkasting6b68a162014-12-01 22:10:294589 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344590 if (tolerance < 2)
4591 tolerance = 2;
4592
4593 // Perform a binary search to find the highest possible number of cookies,
4594 // within the desired tolerance.
4595 while (upper_bound - lower_bound >= tolerance) {
4596 int num_cookies = (lower_bound + upper_bound) / 2;
4597
4598 if (DoManyCookiesRequest(num_cookies))
4599 lower_bound = num_cookies;
4600 else
4601 upper_bound = num_cookies;
4602 }
4603 // Success: the test did not crash.
4604}
4605
[email protected]b89290212009-08-14 22:37:354606TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554607 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114608
initial.commit586acc5fe2008-07-26 22:42:524609 TestDelegate d;
4610 {
danakj8522a25b2016-04-16 00:17:364611 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554612 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524613
[email protected]f7022f32014-08-21 16:32:194614 r->Start();
4615 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524616
[email protected]255620da2013-08-19 13:14:294617 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524618
4619 EXPECT_EQ(1, d.response_started_count());
4620 EXPECT_FALSE(d.received_data_before_response());
4621 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554622 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194623 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554624 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194625 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524626 }
[email protected]5d7b373e2009-09-02 07:19:034627}
4628
[email protected]79e1fd62013-06-20 06:50:044629TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554630 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044631
4632 TestDelegate d;
4633 {
tommycli59a63432015-11-06 00:10:554634 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364635 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364636 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044637
4638 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194639 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044640
[email protected]f7022f32014-08-21 16:32:194641 r->Start();
4642 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044643
[email protected]255620da2013-08-19 13:14:294644 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044645
4646 EXPECT_EQ(1, d.response_started_count());
4647 EXPECT_FALSE(d.received_data_before_response());
4648 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554649 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194650 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554651 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194652 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044653
4654 EXPECT_TRUE(d.have_full_request_headers());
4655 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4656 }
4657}
4658
[email protected]58e32bb2013-01-21 18:23:254659TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554660 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254661
4662 TestDelegate d;
4663 {
danakj8522a25b2016-04-16 00:17:364664 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554665 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254666
[email protected]f7022f32014-08-21 16:32:194667 r->Start();
4668 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254669
[email protected]255620da2013-08-19 13:14:294670 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254671
4672 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194673 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254674 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4675
4676 EXPECT_EQ(1, d.response_started_count());
4677 EXPECT_FALSE(d.received_data_before_response());
4678 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554679 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194680 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554681 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194682 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254683 }
4684}
4685
tommycli59a63432015-11-06 00:10:554686// TODO(svaldez): Update tests to use EmbeddedTestServer.
4687#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394688TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554689 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4690 SpawnedTestServer::kLocalhost,
4691 base::FilePath(kTestFilePath));
4692
4693 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394694
4695 // Parameter that specifies the Content-Length field in the response:
4696 // C - Compressed length.
4697 // U - Uncompressed length.
4698 // L - Large length (larger than both C & U).
4699 // M - Medium length (between C & U).
4700 // S - Small length (smaller than both C & U).
4701 const char test_parameters[] = "CULMS";
4702 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4703 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444704 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394705 // S has too little data, but we seem to accept it.
4706 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374707 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394708
xunjielifb4da222016-07-14 18:38:594709 base::FilePath file_path;
4710 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
4711 file_path = file_path.Append(kTestFilePath);
4712 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
4713 std::string expected_content;
4714 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
4715
4716 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:394717 TestDelegate d;
4718 {
tommycli59a63432015-11-06 00:10:554719 std::string test_file = base::StringPrintf(
4720 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394721
[email protected]ceefd7fd2012-11-29 00:36:244722 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094723 TestURLRequestContext context(true);
4724 context.set_network_delegate(&network_delegate);
4725 context.Init();
[email protected]87a09a92011-07-14 15:50:504726
danakj8522a25b2016-04-16 00:17:364727 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554728 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194729 r->Start();
4730 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394731
[email protected]255620da2013-08-19 13:14:294732 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394733
4734 EXPECT_EQ(1, d.response_started_count());
4735 EXPECT_FALSE(d.received_data_before_response());
4736 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:504737 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:394738 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:504739 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
4740 << "\"";
xunjielifb4da222016-07-14 18:38:594741 if (test_parameters[i] == 'S') {
4742 // When content length is smaller than both compressed length and
4743 // uncompressed length, HttpStreamParser might not read the full
4744 // response body.
4745 continue;
4746 }
4747 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:394748 } else {
maksim.sisovb53724b52016-09-16 05:30:504749 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:394750 << " Parameter = \"" << test_file << "\"";
4751 }
4752 }
4753 }
4754}
tommycli59a63432015-11-06 00:10:554755#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394756
[email protected]58e32bb2013-01-21 18:23:254757TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554758 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254759
tommycli59a63432015-11-06 00:10:554760 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454761 GURL original_url =
tommycli59a63432015-11-06 00:10:554762 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254763 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364764 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364765 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194766 req->Start();
[email protected]255620da2013-08-19 13:14:294767 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254768
4769 EXPECT_EQ(1, d.response_started_count());
4770 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194771 EXPECT_EQ(destination_url, req->url());
4772 EXPECT_EQ(original_url, req->original_url());
4773 ASSERT_EQ(2U, req->url_chain().size());
4774 EXPECT_EQ(original_url, req->url_chain()[0]);
4775 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254776
4777 LoadTimingInfo load_timing_info_before_redirect;
4778 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4779 &load_timing_info_before_redirect));
4780 TestLoadTimingNotReused(load_timing_info_before_redirect,
4781 CONNECT_TIMING_HAS_DNS_TIMES);
4782
4783 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194784 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254785 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4786
4787 // Check that a new socket was used on redirect, since the server does not
4788 // supposed keep-alive sockets, and that the times before the redirect are
4789 // before the ones recorded for the second request.
4790 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4791 load_timing_info.socket_log_id);
4792 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4793 load_timing_info.connect_timing.connect_start);
4794}
4795
[email protected]8f1ac082011-04-19 21:14:134796TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554797 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134798
tommycli59a63432015-11-06 00:10:554799 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454800 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554801 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4802 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4803 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134804 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364805 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364806 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194807 req->Start();
[email protected]255620da2013-08-19 13:14:294808 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134809
4810 EXPECT_EQ(1, d.response_started_count());
4811 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194812 EXPECT_EQ(destination_url, req->url());
4813 EXPECT_EQ(original_url, req->original_url());
4814 ASSERT_EQ(3U, req->url_chain().size());
4815 EXPECT_EQ(original_url, req->url_chain()[0]);
4816 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4817 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134818}
4819
[email protected]abe1c4a2013-10-25 19:28:514820// First and second pieces of information logged by delegates to URLRequests.
4821const char kFirstDelegateInfo[] = "Wonderful delegate";
4822const char kSecondDelegateInfo[] = "Exciting delegate";
4823
4824// Logs delegate information to a URLRequest. The first string is logged
4825// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4826// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4827// another asynchronous call is used to clear the delegate information
4828// before calling a callback. The object then deletes itself.
4829class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4830 public:
4831 typedef base::Callback<void()> Callback;
4832
4833 // Each time delegate information is added to the URLRequest, the resulting
4834 // load state is checked. The expected load state after each request is
4835 // passed in as an argument.
4836 static void Run(URLRequest* url_request,
4837 LoadState expected_first_load_state,
4838 LoadState expected_second_load_state,
4839 LoadState expected_third_load_state,
4840 const Callback& callback) {
4841 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4842 url_request,
4843 expected_first_load_state,
4844 expected_second_load_state,
4845 expected_third_load_state,
4846 callback);
4847 logger->Start();
4848 }
4849
4850 // Checks that the log entries, starting with log_position, contain the
4851 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4852 // recorded. Returns the index of entry after the expected number of
4853 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464854 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514855 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514856 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4857 if (log_position + 3 >= entries.size()) {
4858 ADD_FAILURE() << "Not enough log entries";
4859 return entries.size();
4860 }
4861 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:004862 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4863 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
rdsmith37a0dde2017-01-04 00:12:074864 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_blocked_by",
[email protected]abe1c4a2013-10-25 19:28:514865 &delegate_info));
4866 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4867
4868 ++log_position;
mikecirone8b85c432016-09-08 19:11:004869 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4870 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514871
4872 ++log_position;
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(kSecondDelegateInfo, 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 return log_position + 1;
4884 }
4885
4886 private:
4887 friend class base::RefCounted<AsyncDelegateLogger>;
4888
4889 AsyncDelegateLogger(URLRequest* url_request,
4890 LoadState expected_first_load_state,
4891 LoadState expected_second_load_state,
4892 LoadState expected_third_load_state,
4893 const Callback& callback)
4894 : url_request_(url_request),
4895 expected_first_load_state_(expected_first_load_state),
4896 expected_second_load_state_(expected_second_load_state),
4897 expected_third_load_state_(expected_third_load_state),
4898 callback_(callback) {
4899 }
4900
4901 ~AsyncDelegateLogger() {}
4902
4903 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534904 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514905 LoadStateWithParam load_state = url_request_->GetLoadState();
4906 EXPECT_EQ(expected_first_load_state_, load_state.state);
4907 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454908 base::ThreadTaskRunnerHandle::Get()->PostTask(
4909 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514910 }
4911
4912 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534913 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514914 LoadStateWithParam load_state = url_request_->GetLoadState();
4915 EXPECT_EQ(expected_second_load_state_, load_state.state);
4916 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4917 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4918 } else {
4919 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4920 }
skyostil4891b25b2015-06-11 11:43:454921 base::ThreadTaskRunnerHandle::Get()->PostTask(
4922 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514923 }
4924
4925 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534926 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514927 LoadStateWithParam load_state = url_request_->GetLoadState();
4928 EXPECT_EQ(expected_third_load_state_, load_state.state);
4929 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084930 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514931 callback_.Run();
4932 }
4933
4934 URLRequest* url_request_;
4935 const int expected_first_load_state_;
4936 const int expected_second_load_state_;
4937 const int expected_third_load_state_;
4938 const Callback callback_;
4939
4940 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4941};
4942
4943// NetworkDelegate that logs delegate information before a request is started,
4944// before headers are sent, when headers are read, and when auth information
4945// is requested. Uses AsyncDelegateLogger.
4946class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4947 public:
4948 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204949 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514950
4951 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204952 int OnBeforeURLRequest(URLRequest* request,
4953 const CompletionCallback& callback,
4954 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514955 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4956 return RunCallbackAsynchronously(request, callback);
4957 }
4958
ryansturm2343cb62016-06-15 01:09:004959 int OnBeforeStartTransaction(URLRequest* request,
4960 const CompletionCallback& callback,
4961 HttpRequestHeaders* headers) override {
4962 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514963 return RunCallbackAsynchronously(request, callback);
4964 }
4965
dchengb03027d2014-10-21 12:00:204966 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514967 URLRequest* request,
4968 const CompletionCallback& callback,
4969 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164970 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134971 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164972 TestNetworkDelegate::OnHeadersReceived(request,
4973 callback,
[email protected]abe1c4a2013-10-25 19:28:514974 original_response_headers,
[email protected]5f714132014-03-26 10:41:164975 override_response_headers,
4976 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514977 return RunCallbackAsynchronously(request, callback);
4978 }
4979
dchengb03027d2014-10-21 12:00:204980 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514981 URLRequest* request,
4982 const AuthChallengeInfo& auth_info,
4983 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134984 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514985 AsyncDelegateLogger::Run(
4986 request,
4987 LOAD_STATE_WAITING_FOR_DELEGATE,
4988 LOAD_STATE_WAITING_FOR_DELEGATE,
4989 LOAD_STATE_WAITING_FOR_DELEGATE,
4990 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4991 callback, credentials));
4992 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4993 }
4994
4995 private:
4996 static int RunCallbackAsynchronously(
4997 URLRequest* request,
4998 const CompletionCallback& callback) {
4999 AsyncDelegateLogger::Run(
5000 request,
5001 LOAD_STATE_WAITING_FOR_DELEGATE,
5002 LOAD_STATE_WAITING_FOR_DELEGATE,
5003 LOAD_STATE_WAITING_FOR_DELEGATE,
5004 base::Bind(callback, OK));
5005 return ERR_IO_PENDING;
5006 }
5007
5008 static void SetAuthAndResume(const AuthCallback& callback,
5009 AuthCredentials* credentials) {
5010 *credentials = AuthCredentials(kUser, kSecret);
5011 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
5012 }
5013
5014 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
5015};
5016
5017// URLRequest::Delegate that logs delegate information when the headers
5018// are received, when each read completes, and during redirects. Uses
5019// AsyncDelegateLogger. Can optionally cancel a request in any phase.
5020//
5021// Inherits from TestDelegate to reuse the TestDelegate code to handle
5022// advancing to the next step in most cases, as well as cancellation.
5023class AsyncLoggingUrlRequestDelegate : public TestDelegate {
5024 public:
5025 enum CancelStage {
5026 NO_CANCEL = 0,
5027 CANCEL_ON_RECEIVED_REDIRECT,
5028 CANCEL_ON_RESPONSE_STARTED,
5029 CANCEL_ON_READ_COMPLETED
5030 };
5031
5032 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
5033 : cancel_stage_(cancel_stage) {
5034 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
5035 set_cancel_in_received_redirect(true);
5036 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
5037 set_cancel_in_response_started(true);
5038 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
5039 set_cancel_in_received_data(true);
5040 }
dchengb03027d2014-10-21 12:00:205041 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:515042
5043 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:205044 void OnReceivedRedirect(URLRequest* request,
5045 const RedirectInfo& redirect_info,
5046 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:515047 *defer_redirect = true;
5048 AsyncDelegateLogger::Run(
5049 request,
5050 LOAD_STATE_WAITING_FOR_DELEGATE,
5051 LOAD_STATE_WAITING_FOR_DELEGATE,
5052 LOAD_STATE_WAITING_FOR_DELEGATE,
5053 base::Bind(
5054 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595055 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515056 }
5057
maksim.sisov0f4aa142016-09-05 05:55:285058 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515059 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285060 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5061 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5062 base::Bind(
5063 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5064 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515065 }
5066
dchengb03027d2014-10-21 12:00:205067 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515068 AsyncDelegateLogger::Run(
5069 request,
5070 LOAD_STATE_IDLE,
5071 LOAD_STATE_IDLE,
5072 LOAD_STATE_IDLE,
5073 base::Bind(
5074 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5075 base::Unretained(this), request, bytes_read));
5076 }
5077
5078 private:
5079 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595080 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515081 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595082 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515083 // FollowDeferredRedirect should not be called after cancellation.
5084 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5085 return;
5086 if (!defer_redirect)
5087 request->FollowDeferredRedirect();
5088 }
5089
maksim.sisov0f4aa142016-09-05 05:55:285090 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515091 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285092 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515093 }
5094
5095 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5096 // The parent class continues the request.
5097 TestDelegate::OnReadCompleted(request, bytes_read);
5098 }
5099
5100 const CancelStage cancel_stage_;
5101
5102 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5103};
5104
5105// Tests handling of delegate info before a request starts.
5106TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555107 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515108
5109 TestDelegate request_delegate;
5110 TestURLRequestContext context(true);
5111 context.set_network_delegate(NULL);
5112 context.set_net_log(&net_log_);
5113 context.Init();
5114
5115 {
danakj8522a25b2016-04-16 00:17:365116 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555117 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365118 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195119 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515120 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085121 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515122
5123 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195124 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515125 LOAD_STATE_WAITING_FOR_DELEGATE,
5126 LOAD_STATE_WAITING_FOR_DELEGATE,
5127 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195128 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515129
5130 base::RunLoop().Run();
5131
[email protected]f7022f32014-08-21 16:32:195132 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505133 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515134 }
5135
mmenke43758e62015-05-04 21:09:465136 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515137 net_log_.GetEntries(&entries);
5138 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005139 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515140
5141 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5142
5143 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005144 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5145 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515146}
5147
5148// Tests handling of delegate info from a network delegate.
5149TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555150 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515151
5152 TestDelegate request_delegate;
5153 AsyncLoggingNetworkDelegate network_delegate;
5154 TestURLRequestContext context(true);
5155 context.set_network_delegate(&network_delegate);
5156 context.set_net_log(&net_log_);
5157 context.Init();
5158
5159 {
danakj8522a25b2016-04-16 00:17:365160 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555161 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365162 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195163 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515164 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085165 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515166
[email protected]f7022f32014-08-21 16:32:195167 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515168 base::RunLoop().Run();
5169
[email protected]f7022f32014-08-21 16:32:195170 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505171 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515172 EXPECT_EQ(1, network_delegate.created_requests());
5173 EXPECT_EQ(0, network_delegate.destroyed_requests());
5174 }
5175 EXPECT_EQ(1, network_delegate.destroyed_requests());
5176
5177 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465178 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515179 net_log_.GetEntries(&entries);
5180 for (size_t i = 0; i < 3; ++i) {
5181 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005182 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5183 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515184
5185 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5186 log_position + 1);
5187
5188 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005189 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5190 entries[log_position].type);
5191 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515192 }
5193
mikecirone8b85c432016-09-08 19:11:005194 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5195 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515196}
5197
5198// Tests handling of delegate info from a network delegate in the case of an
5199// HTTP redirect.
5200TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555201 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515202
5203 TestDelegate request_delegate;
5204 AsyncLoggingNetworkDelegate network_delegate;
5205 TestURLRequestContext context(true);
5206 context.set_network_delegate(&network_delegate);
5207 context.set_net_log(&net_log_);
5208 context.Init();
5209
5210 {
danakj8522a25b2016-04-16 00:17:365211 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555212 http_test_server()->GetURL("/server-redirect?simple.html"),
5213 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195214 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515215 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085216 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515217
[email protected]f7022f32014-08-21 16:32:195218 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515219 base::RunLoop().Run();
5220
[email protected]f7022f32014-08-21 16:32:195221 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505222 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515223 EXPECT_EQ(2, network_delegate.created_requests());
5224 EXPECT_EQ(0, network_delegate.destroyed_requests());
5225 }
5226 EXPECT_EQ(1, network_delegate.destroyed_requests());
5227
5228 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465229 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515230 net_log_.GetEntries(&entries);
5231 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005232 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515233 for (size_t i = 0; i < 3; ++i) {
5234 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005235 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5236 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515237
5238 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5239 log_position + 1);
5240
5241 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005242 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5243 entries[log_position].type);
5244 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515245 }
5246
5247 // The URLRequest::Delegate then gets informed about the redirect.
5248 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005249 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5250 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515251
5252 // The NetworkDelegate logged information in the same three events as before.
5253 for (size_t i = 0; i < 3; ++i) {
5254 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005255 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5256 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515257
5258 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5259 log_position + 1);
5260
5261 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005262 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5263 entries[log_position].type);
5264 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515265 }
5266
mikecirone8b85c432016-09-08 19:11:005267 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5268 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515269}
5270
5271// Tests handling of delegate info from a network delegate in the case of HTTP
5272// AUTH.
5273TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555274 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515275
5276 TestDelegate request_delegate;
5277 AsyncLoggingNetworkDelegate network_delegate;
5278 TestURLRequestContext context(true);
5279 context.set_network_delegate(&network_delegate);
5280 context.set_net_log(&net_log_);
5281 context.Init();
5282
5283 {
danakj8522a25b2016-04-16 00:17:365284 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555285 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365286 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195287 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515288 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085289 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515290
[email protected]f7022f32014-08-21 16:32:195291 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515292 base::RunLoop().Run();
5293
[email protected]f7022f32014-08-21 16:32:195294 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505295 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515296 EXPECT_EQ(1, network_delegate.created_requests());
5297 EXPECT_EQ(0, network_delegate.destroyed_requests());
5298 }
5299 EXPECT_EQ(1, network_delegate.destroyed_requests());
5300
5301 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465302 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515303 net_log_.GetEntries(&entries);
5304 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005305 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5306 // in
5307 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515308 for (size_t i = 0; i < 6; ++i) {
5309 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005310 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5311 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515312
5313 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5314 log_position + 1);
5315
5316 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005317 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5318 entries[log_position].type);
5319 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515320 }
5321
mikecirone8b85c432016-09-08 19:11:005322 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5323 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515324}
5325
tommycli59a63432015-11-06 00:10:555326// TODO(svaldez): Update tests to use EmbeddedTestServer.
5327#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515328// Tests handling of delegate info from a URLRequest::Delegate.
5329TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555330 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5331 SpawnedTestServer::kLocalhost,
5332 base::FilePath(kTestFilePath));
5333
5334 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515335
5336 AsyncLoggingUrlRequestDelegate request_delegate(
5337 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5338 TestURLRequestContext context(true);
5339 context.set_network_delegate(NULL);
5340 context.set_net_log(&net_log_);
5341 context.Init();
5342
5343 {
5344 // A chunked response with delays between chunks is used to make sure that
5345 // attempts by the URLRequest delegate to log information while reading the
5346 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485347 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515348 // that it occurs.
danakj8522a25b2016-04-16 00:17:365349 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555350 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365351 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195352 LoadStateWithParam load_state = r->GetLoadState();
5353 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515354 base::RunLoop().Run();
5355
[email protected]f7022f32014-08-21 16:32:195356 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505357 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515358 }
5359
mmenke43758e62015-05-04 21:09:465360 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515361 net_log_.GetEntries(&entries);
5362
[email protected]1826a402014-01-08 15:40:485363 size_t log_position = 0;
5364
[email protected]abe1c4a2013-10-25 19:28:515365 // The delegate info should only have been logged on header complete. Other
5366 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005367 log_position = ExpectLogContainsSomewhereAfter(
5368 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5369 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515370
5371 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5372 log_position + 1);
5373
5374 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005375 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5376 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515377
mikecirone8b85c432016-09-08 19:11:005378 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5379 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515380 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005381 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515382}
tommycli59a63432015-11-06 00:10:555383#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515384
5385// Tests handling of delegate info from a URLRequest::Delegate in the case of
5386// an HTTP redirect.
5387TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555388 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515389
5390 AsyncLoggingUrlRequestDelegate request_delegate(
5391 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5392 TestURLRequestContext context(true);
5393 context.set_network_delegate(NULL);
5394 context.set_net_log(&net_log_);
5395 context.Init();
5396
5397 {
danakj8522a25b2016-04-16 00:17:365398 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555399 http_test_server()->GetURL("/server-redirect?simple.html"),
5400 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195401 LoadStateWithParam load_state = r->GetLoadState();
5402 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515403 base::RunLoop().Run();
5404
[email protected]f7022f32014-08-21 16:32:195405 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505406 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515407 }
5408
mmenke43758e62015-05-04 21:09:465409 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515410 net_log_.GetEntries(&entries);
5411
5412 // Delegate info should only have been logged in OnReceivedRedirect and
5413 // OnResponseStarted.
5414 size_t log_position = 0;
5415 for (int i = 0; i < 2; ++i) {
5416 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005417 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5418 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515419
5420 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5421 log_position + 1);
5422
5423 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005424 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5425 entries[log_position].type);
5426 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515427 }
5428
mikecirone8b85c432016-09-08 19:11:005429 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5430 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515431 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005432 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515433}
5434
5435// Tests handling of delegate info from a URLRequest::Delegate in the case of
5436// an HTTP redirect, with cancellation at various points.
5437TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555438 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515439
5440 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5441 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5442 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5443 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5444 };
5445
5446 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5447 ++test_case) {
5448 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5449 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515450 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515451 context.set_network_delegate(NULL);
5452 context.set_net_log(&net_log);
5453 context.Init();
5454
5455 {
danakj8522a25b2016-04-16 00:17:365456 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555457 http_test_server()->GetURL("/server-redirect?simple.html"),
5458 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195459 LoadStateWithParam load_state = r->GetLoadState();
5460 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515461 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505462 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515463 }
5464
mmenke43758e62015-05-04 21:09:465465 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515466 net_log.GetEntries(&entries);
5467
5468 // Delegate info is always logged in both OnReceivedRedirect and
5469 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5470 // OnResponseStarted delegate call is after cancellation, but logging is
5471 // still currently supported in that call.
5472 size_t log_position = 0;
5473 for (int i = 0; i < 2; ++i) {
5474 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005475 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5476 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515477
5478 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5479 log_position + 1);
5480
5481 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005482 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5483 entries[log_position].type);
5484 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515485 }
5486
mikecirone8b85c432016-09-08 19:11:005487 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5488 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515489 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005490 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515491 }
5492}
5493
[email protected]847c0fa92012-11-06 16:37:425494namespace {
5495
5496const char kExtraHeader[] = "Allow-Snafu";
5497const char kExtraValue[] = "fubar";
5498
5499class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205500 void OnReceivedRedirect(URLRequest* request,
5501 const RedirectInfo& redirect_info,
5502 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595503 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425504 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5505 }
5506};
5507
5508} // namespace
5509
5510TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555511 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425512
tommycli59a63432015-11-06 00:10:555513 GURL destination_url =
5514 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5515 GURL original_url =
5516 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425517 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365518 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365519 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195520 req->Start();
[email protected]255620da2013-08-19 13:14:295521 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425522
5523 std::string value;
[email protected]f7022f32014-08-21 16:32:195524 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425525 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5526 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195527 EXPECT_FALSE(req->is_pending());
5528 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425529 EXPECT_EQ(kExtraValue, d.data_received());
5530}
5531
[email protected]251a1b92012-11-13 11:01:095532namespace {
5533
5534const char kExtraHeaderToRemove[] = "To-Be-Removed";
5535
5536class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205537 void OnReceivedRedirect(URLRequest* request,
5538 const RedirectInfo& redirect_info,
5539 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595540 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095541 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5542 }
5543};
5544
5545} // namespace
5546
5547TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555548 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095549
tommycli59a63432015-11-06 00:10:555550 GURL destination_url = http_test_server()->GetURL(
5551 "/echoheader?" + std::string(kExtraHeaderToRemove));
5552 GURL original_url =
5553 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095554 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365555 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365556 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195557 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5558 req->Start();
[email protected]255620da2013-08-19 13:14:295559 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095560
5561 std::string value;
[email protected]f7022f32014-08-21 16:32:195562 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095563 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195564 EXPECT_FALSE(req->is_pending());
5565 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095566 EXPECT_EQ("None", d.data_received());
5567}
5568
mmenke94f1bd92016-12-07 21:13:055569TEST_F(URLRequestTestHTTP, CancelAfterStart) {
[email protected]316c1e5e2012-09-12 15:17:445570 TestDelegate d;
5571 {
danakj8522a25b2016-04-16 00:17:365572 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365573 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445574
[email protected]f7022f32014-08-21 16:32:195575 r->Start();
5576 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445577
[email protected]f7022f32014-08-21 16:32:195578 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445579
[email protected]255620da2013-08-19 13:14:295580 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445581
5582 // We expect to receive OnResponseStarted even though the request has been
5583 // cancelled.
5584 EXPECT_EQ(1, d.response_started_count());
5585 EXPECT_EQ(0, d.bytes_received());
5586 EXPECT_FALSE(d.received_data_before_response());
5587 }
5588}
5589
mmenke94f1bd92016-12-07 21:13:055590TEST_F(URLRequestTestHTTP, CancelInResponseStarted) {
tommycli59a63432015-11-06 00:10:555591 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445592
5593 TestDelegate d;
5594 {
danakj8522a25b2016-04-16 00:17:365595 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555596 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445597
5598 d.set_cancel_in_response_started(true);
5599
[email protected]f7022f32014-08-21 16:32:195600 r->Start();
5601 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445602
[email protected]255620da2013-08-19 13:14:295603 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445604
5605 EXPECT_EQ(1, d.response_started_count());
5606 EXPECT_EQ(0, d.bytes_received());
5607 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505608 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445609 }
5610}
5611
mmenke94f1bd92016-12-07 21:13:055612TEST_F(URLRequestTestHTTP, CancelOnDataReceived) {
tommycli59a63432015-11-06 00:10:555613 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445614
5615 TestDelegate d;
5616 {
danakj8522a25b2016-04-16 00:17:365617 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
mmenke94f1bd92016-12-07 21:13:055618 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
5619
5620 d.set_cancel_in_received_data(true);
5621
5622 r->Start();
5623 EXPECT_TRUE(r->is_pending());
5624
5625 base::RunLoop().Run();
5626
5627 EXPECT_EQ(1, d.response_started_count());
5628 EXPECT_NE(0, d.received_bytes_count());
5629 EXPECT_FALSE(d.received_data_before_response());
5630 EXPECT_EQ(ERR_ABORTED, d.request_status());
5631 }
5632}
5633
5634TEST_F(URLRequestTestHTTP, CancelDuringEofRead) {
5635 ASSERT_TRUE(http_test_server()->Start());
5636
5637 TestDelegate d;
5638 {
5639 // This returns an empty response (With headers).
5640 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555641 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445642
5643 d.set_cancel_in_received_data(true);
5644
[email protected]f7022f32014-08-21 16:32:195645 r->Start();
5646 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445647
[email protected]255620da2013-08-19 13:14:295648 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445649
5650 EXPECT_EQ(1, d.response_started_count());
mmenke94f1bd92016-12-07 21:13:055651 EXPECT_EQ(0, d.received_bytes_count());
[email protected]316c1e5e2012-09-12 15:17:445652 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505653 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445654 }
5655}
5656
mmenke94f1bd92016-12-07 21:13:055657TEST_F(URLRequestTestHTTP, CancelByDestroyingAfterStart) {
tommycli59a63432015-11-06 00:10:555658 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445659
5660 TestDelegate d;
5661 {
danakj8522a25b2016-04-16 00:17:365662 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555663 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445664
[email protected]f7022f32014-08-21 16:32:195665 r->Start();
5666 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445667
5668 // The request will be implicitly canceled when it is destroyed. The
5669 // test delegate must not post a quit message when this happens because
5670 // this test doesn't actually have a message loop. The quit message would
5671 // get put on this thread's message queue and the next test would exit
5672 // early, causing problems.
5673 d.set_quit_on_complete(false);
5674 }
5675 // expect things to just cleanup properly.
5676
kimwjdalsl2bb4ff02015-12-16 22:06:025677 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445678 // message loop
5679 EXPECT_FALSE(d.received_data_before_response());
5680 EXPECT_EQ(0, d.bytes_received());
5681}
5682
mmenke94f1bd92016-12-07 21:13:055683TEST_F(URLRequestTestHTTP, CancelWhileReadingFromCache) {
tommycli59a63432015-11-06 00:10:555684 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445685
5686 // populate cache
5687 {
5688 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365689 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555690 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195691 r->Start();
[email protected]255620da2013-08-19 13:14:295692 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505693 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445694 }
5695
5696 // cancel read from cache (see bug 990242)
5697 {
5698 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365699 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555700 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195701 r->Start();
5702 r->Cancel();
[email protected]255620da2013-08-19 13:14:295703 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445704
maksim.sisovb53724b52016-09-16 05:30:505705 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445706 EXPECT_EQ(1, d.response_started_count());
5707 EXPECT_EQ(0, d.bytes_received());
5708 EXPECT_FALSE(d.received_data_before_response());
5709 }
5710}
5711
5712TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555713 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445714 HTTPUploadDataOperationTest("POST");
5715}
5716
5717TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555718 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445719 HTTPUploadDataOperationTest("PUT");
5720}
5721
5722TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555723 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445724
5725 TestDelegate d;
5726 {
danakj8522a25b2016-04-16 00:17:365727 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555728 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195729 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445730
[email protected]f7022f32014-08-21 16:32:195731 r->Start();
5732 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445733
[email protected]255620da2013-08-19 13:14:295734 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445735
maksim.sisovb53724b52016-09-16 05:30:505736 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5737 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445738
5739 EXPECT_FALSE(d.received_data_before_response());
5740 EXPECT_TRUE(d.data_received().empty());
5741 }
5742}
5743
5744TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555745 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445746
5747 TestDelegate d;
5748 {
danakj8522a25b2016-04-16 00:17:365749 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555750 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195751 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445752
[email protected]6cdfd7f2013-02-08 20:40:155753 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445754 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025755 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445756
danakj8522a25b2016-04-16 00:17:365757 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445758
[email protected]6cdfd7f2013-02-08 20:40:155759 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445760 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475761 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445762 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
ricea2deef682016-09-09 08:04:075763 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:145764 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:075765 std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365766 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225767 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445768
[email protected]f7022f32014-08-21 16:32:195769 r->Start();
5770 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445771
[email protected]255620da2013-08-19 13:14:295772 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445773
avibf0746c2015-12-09 19:53:145774 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295775 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5776 ASSERT_LE(size64, std::numeric_limits<int>::max());
5777 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365778 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445779
[email protected]7600d0b2013-12-08 21:43:305780 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445781
maksim.sisovb53724b52016-09-16 05:30:505782 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5783 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445784
5785 EXPECT_FALSE(d.received_data_before_response());
5786
[email protected]329b68b2012-11-14 17:54:275787 EXPECT_EQ(size, d.bytes_received());
5788 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445789 }
5790}
5791
[email protected]999dd8c2013-11-12 06:45:545792TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555793 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545794
5795 TestDelegate d;
5796 {
danakj8522a25b2016-04-16 00:17:365797 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555798 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195799 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545800
danakj8522a25b2016-04-16 00:17:365801 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545802
ricea2deef682016-09-09 08:04:075803 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:455804 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545805 base::FilePath(FILE_PATH_LITERAL(
5806 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:075807 0, std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365808 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225809 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545810
[email protected]f7022f32014-08-21 16:32:195811 r->Start();
5812 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545813
5814 base::RunLoop().Run();
5815
[email protected]999dd8c2013-11-12 06:45:545816 EXPECT_TRUE(d.request_failed());
5817 EXPECT_FALSE(d.received_data_before_response());
5818 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:505819 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:545820 }
5821}
5822
mmenke56b0cbb912016-03-28 21:34:535823namespace {
5824
5825// Adds a standard set of data to an upload for chunked upload integration
5826// tests.
5827void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5828 writer->AppendData("a", 1, false);
5829 writer->AppendData("bcd", 3, false);
5830 writer->AppendData("this is a longer chunk than before.", 35, false);
5831 writer->AppendData("\r\n\r\n", 4, false);
5832 writer->AppendData("0", 1, false);
5833 writer->AppendData("2323", 4, true);
5834}
5835
5836// Checks that the upload data added in AddChunksToUpload() was echoed back from
5837// the server.
5838void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5839 // This should match the chunks sent by AddChunksToUpload().
5840 const std::string expected_data =
5841 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5842
maksim.sisovb53724b52016-09-16 05:30:505843 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
5844 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:535845
5846 EXPECT_FALSE(d->received_data_before_response());
5847
5848 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5849 EXPECT_EQ(expected_data, d->data_received());
5850}
5851
5852} // namespace
5853
[email protected]316c1e5e2012-09-12 15:17:445854TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555855 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445856
5857 TestDelegate d;
5858 {
danakj8522a25b2016-04-16 00:17:365859 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555860 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365861 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535862 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365863 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535864 upload_data_stream->CreateWriter();
5865 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195866 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535867 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195868 r->Start();
5869 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445870
[email protected]255620da2013-08-19 13:14:295871 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445872
[email protected]f7022f32014-08-21 16:32:195873 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445874 }
5875}
5876
[email protected]329b68b2012-11-14 17:54:275877TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555878 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275879
5880 TestDelegate d;
5881 {
danakj8522a25b2016-04-16 00:17:365882 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555883 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365884 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535885 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365886 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535887 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365888 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195889 r->set_method("POST");
5890 r->Start();
5891 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535892 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295893 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275894
[email protected]f7022f32014-08-21 16:32:195895 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275896 }
5897}
5898
[email protected]316c1e5e2012-09-12 15:17:445899TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555900 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445901
5902 TestDelegate d;
5903 {
danakj8522a25b2016-04-16 00:17:365904 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555905 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365906 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535907 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365908 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535909 upload_data_stream->CreateWriter();
5910 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195911 r->set_method("POST");
5912 r->Start();
5913 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445914
[email protected]255620da2013-08-19 13:14:295915 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535916 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295917 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445918
[email protected]f7022f32014-08-21 16:32:195919 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445920 }
5921}
5922
5923TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555924 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445925
5926 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365927 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555928 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195929 req->Start();
[email protected]255620da2013-08-19 13:14:295930 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445931
[email protected]f7022f32014-08-21 16:32:195932 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445933
5934 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195935 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445936
5937 std::string header;
5938 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5939 EXPECT_EQ("private", header);
5940
5941 header.clear();
5942 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5943 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5944
5945 // The response has two "X-Multiple-Entries" headers.
5946 // This verfies our output has them concatenated together.
5947 header.clear();
5948 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5949 EXPECT_EQ("a, b", header);
5950}
5951
tommycli59a63432015-11-06 00:10:555952// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5953// security state. (see http://crbug.com/550977).
5954#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465955TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555956 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5957 https_test_server.SetSSLConfig(
5958 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5959 https_test_server.ServeFilesFromSourceDirectory(
5960 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465961 ASSERT_TRUE(https_test_server.Start());
5962
tommycli59a63432015-11-06 00:10:555963 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465964 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365965 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555966 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195967 request->Start();
[email protected]255620da2013-08-19 13:14:295968 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465969
5970 TransportSecurityState* security_state =
5971 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405972 TransportSecurityState::STSState sts_state;
5973 TransportSecurityState::PKPState pkp_state;
5974 EXPECT_TRUE(
5975 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5976 EXPECT_FALSE(
5977 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5978 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5979 sts_state.upgrade_mode);
5980 EXPECT_TRUE(sts_state.include_subdomains);
5981 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035982#if defined(OS_ANDROID)
5983 // Android's CertVerifyProc does not (yet) handle pins.
5984#else
martijnc0d6b622015-06-30 19:14:405985 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035986#endif
[email protected]37fd55fb2013-06-29 13:13:275987}
5988
estarka5da76702015-04-09 04:00:165989TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555990 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5991 https_test_server.ServeFilesFromSourceDirectory(
5992 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165993 ASSERT_TRUE(https_test_server.Start());
5994 // Make sure this test fails if the test server is changed to not
5995 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555996 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5997 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165998
5999 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366000 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556001 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166002 request->Start();
6003 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:166004 TransportSecurityState* security_state =
6005 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406006 TransportSecurityState::STSState sts_state;
6007 EXPECT_FALSE(
6008 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:166009}
6010
estark06e0dac2015-08-07 21:56:016011namespace {
estark1614475f2016-03-10 03:46:476012const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:246013const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
6014const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:016015const char kHPKPReportUri[] = "https://hpkp-report.test";
6016} // namespace
6017
[email protected]37fd55fb2013-06-29 13:13:276018// Tests that enabling HPKP on a domain does not affect the HSTS
6019// validity/expiration.
dadrian2faf2062016-07-16 00:03:176020TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:016021 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556022 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6023 https_test_server.SetSSLConfig(
6024 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6025 https_test_server.ServeFilesFromSourceDirectory(
6026 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276027 ASSERT_TRUE(https_test_server.Start());
6028
tommycli59a63432015-11-06 00:10:556029 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166030
[email protected]37fd55fb2013-06-29 13:13:276031 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366032 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556033 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196034 request->Start();
[email protected]255620da2013-08-19 13:14:296035 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276036 TransportSecurityState* security_state =
6037 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406038 TransportSecurityState::STSState sts_state;
6039 TransportSecurityState::PKPState pkp_state;
6040 EXPECT_FALSE(
6041 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6042 EXPECT_TRUE(
6043 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6044 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6045 sts_state.upgrade_mode);
6046 EXPECT_FALSE(sts_state.include_subdomains);
6047 EXPECT_FALSE(pkp_state.include_subdomains);
6048 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016049 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406050 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466051}
6052
estark06e0dac2015-08-07 21:56:016053// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176054TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016055 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556056 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6057 https_test_server.SetSSLConfig(
6058 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6059 https_test_server.ServeFilesFromSourceDirectory(
6060 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016061 ASSERT_TRUE(https_test_server.Start());
6062
tommycli59a63432015-11-06 00:10:556063 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016064
6065 // Set up a pin for |test_server_hostname|.
6066 TransportSecurityState security_state;
6067 const base::Time current_time(base::Time::Now());
6068 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6069 HashValueVector hashes;
6070 HashValue hash1;
6071 HashValue hash2;
6072 // The values here don't matter, as long as they are different from
6073 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446074 ASSERT_TRUE(
6075 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6076 ASSERT_TRUE(
6077 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016078 hashes.push_back(hash1);
6079 hashes.push_back(hash2);
6080 security_state.AddHPKP(test_server_hostname, expiry,
6081 false, /* include subdomains */
6082 hashes, report_uri);
6083
6084 MockCertificateReportSender mock_report_sender;
6085 security_state.SetReportSender(&mock_report_sender);
6086
6087 // Set up a MockCertVerifier to trigger a violation of the previously
6088 // set pin.
6089 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6090 ASSERT_TRUE(cert);
6091
6092 MockCertVerifier cert_verifier;
6093 CertVerifyResult verify_result;
6094 verify_result.verified_cert = cert;
6095 verify_result.is_issued_by_known_root = true;
6096 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446097 ASSERT_TRUE(
6098 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016099 verify_result.public_key_hashes.push_back(hash3);
6100 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6101
6102 TestNetworkDelegate network_delegate;
6103 TestURLRequestContext context(true);
6104 context.set_transport_security_state(&security_state);
6105 context.set_network_delegate(&network_delegate);
6106 context.set_cert_verifier(&cert_verifier);
6107 context.Init();
6108
6109 // Now send a request to trigger the violation.
6110 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366111 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556112 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016113 violating_request->Start();
6114 base::RunLoop().Run();
6115
6116 // Check that a report was sent.
6117 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6118 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446119 EXPECT_EQ("application/json; charset=utf-8",
6120 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366121 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016122 base::JSONReader::Read(mock_report_sender.latest_report()));
6123 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286124 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016125 base::DictionaryValue* report_dict;
6126 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6127 std::string report_hostname;
6128 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6129 EXPECT_EQ(test_server_hostname, report_hostname);
6130}
6131
6132// Tests that reports get sent on requests with
6133// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176134TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016135 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556136 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6137 https_test_server.SetSSLConfig(
6138 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6139 https_test_server.ServeFilesFromSourceDirectory(
6140 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016141 ASSERT_TRUE(https_test_server.Start());
6142
tommycli59a63432015-11-06 00:10:556143 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016144
6145 TransportSecurityState security_state;
6146 MockCertificateReportSender mock_report_sender;
6147 security_state.SetReportSender(&mock_report_sender);
6148
6149 // Set up a MockCertVerifier to violate the pin in the Report-Only
6150 // header.
6151 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6152 ASSERT_TRUE(cert);
6153
6154 MockCertVerifier cert_verifier;
6155 CertVerifyResult verify_result;
6156 verify_result.verified_cert = cert;
6157 verify_result.is_issued_by_known_root = true;
6158 HashValue hash;
6159 // This value doesn't matter, as long as it is different from the pins
6160 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446161 ASSERT_TRUE(
6162 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016163 verify_result.public_key_hashes.push_back(hash);
6164 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6165
6166 TestNetworkDelegate network_delegate;
6167 TestURLRequestContext context(true);
6168 context.set_transport_security_state(&security_state);
6169 context.set_network_delegate(&network_delegate);
6170 context.set_cert_verifier(&cert_verifier);
6171 context.Init();
6172
6173 // Now send a request to trigger the violation.
6174 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366175 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556176 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016177 DEFAULT_PRIORITY, &d));
6178 violating_request->Start();
6179 base::RunLoop().Run();
6180
6181 // Check that a report was sent.
6182 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6183 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446184 EXPECT_EQ("application/json; charset=utf-8",
6185 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366186 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016187 base::JSONReader::Read(mock_report_sender.latest_report()));
6188 ASSERT_TRUE(value);
jdoerriedc72ee942016-12-07 15:43:286189 ASSERT_TRUE(value->IsType(base::Value::Type::DICTIONARY));
estark06e0dac2015-08-07 21:56:016190 base::DictionaryValue* report_dict;
6191 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6192 std::string report_hostname;
6193 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6194 EXPECT_EQ(test_server_hostname, report_hostname);
6195}
6196
6197// Tests that reports do not get sent on requests with
6198// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176199TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016200 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556201 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6202 https_test_server.SetSSLConfig(
6203 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6204 https_test_server.ServeFilesFromSourceDirectory(
6205 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016206 ASSERT_TRUE(https_test_server.Start());
6207
tommycli59a63432015-11-06 00:10:556208 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016209
6210 TransportSecurityState security_state;
6211 MockCertificateReportSender mock_report_sender;
6212 security_state.SetReportSender(&mock_report_sender);
6213
6214 TestNetworkDelegate network_delegate;
6215 MockCertVerifier mock_cert_verifier;
6216 TestURLRequestContext context(true);
6217 context.set_transport_security_state(&security_state);
6218 context.set_network_delegate(&network_delegate);
6219 context.set_cert_verifier(&mock_cert_verifier);
6220 mock_cert_verifier.set_default_result(OK);
6221 context.Init();
6222
6223 // Now send a request that does not trigger the violation.
6224 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366225 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556226 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016227 DEFAULT_PRIORITY, &d));
6228 request->Start();
6229 base::RunLoop().Run();
6230
6231 // Check that a report was not sent.
6232 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6233 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6234}
6235
estarka5da76702015-04-09 04:00:166236TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556237 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6238 https_test_server.ServeFilesFromSourceDirectory(
6239 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166240 ASSERT_TRUE(https_test_server.Start());
6241 // Make sure this test fails if the test server is changed to not
6242 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556243 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6244 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166245
6246 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366247 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556248 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166249 request->Start();
6250 base::RunLoop().Run();
6251
6252 TransportSecurityState* security_state =
6253 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406254 TransportSecurityState::PKPState pkp_state;
6255 EXPECT_FALSE(
6256 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166257}
6258
dadriandf302c42016-06-10 18:48:596259TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6260 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6261 https_test_server.SetSSLConfig(
6262 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6263 https_test_server.ServeFilesFromSourceDirectory(
6264 base::FilePath(kTestFilePath));
6265 ASSERT_TRUE(https_test_server.Start());
6266
6267 // Set up a MockCertVerifier to be a local root that violates the pin
6268 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6269 ASSERT_TRUE(cert);
6270
6271 MockCertVerifier cert_verifier;
6272 CertVerifyResult verify_result;
6273 verify_result.verified_cert = cert;
6274 verify_result.is_issued_by_known_root = false;
6275 HashValue hash;
6276 ASSERT_TRUE(
6277 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6278 verify_result.public_key_hashes.push_back(hash);
6279 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6280 cert_verifier.set_default_result(OK);
6281
6282 std::string test_server_hostname = https_test_server.GetURL("/").host();
6283
6284 // Set up HPKP
6285 base::Time current_time = base::Time::Now();
6286 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6287 HashValue pin;
6288 ASSERT_TRUE(
6289 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6290 HashValueVector hashes;
6291 hashes.push_back(pin);
6292 GURL report_uri(kHPKPReportUri);
6293 TransportSecurityState security_state;
6294 security_state.AddHPKP(test_server_hostname, expiry,
6295 false, /* include subdomains */
6296 hashes, report_uri);
6297
6298 TestNetworkDelegate network_delegate;
6299 TestURLRequestContext context(true);
6300 context.set_transport_security_state(&security_state);
6301 context.set_network_delegate(&network_delegate);
6302 context.set_cert_verifier(&cert_verifier);
6303 context.Init();
6304
6305 TestDelegate d;
6306 std::unique_ptr<URLRequest> request(context.CreateRequest(
6307 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6308 request->Start();
6309 base::RunLoop().Run();
6310
6311 TransportSecurityState::PKPState pkp_state;
6312 EXPECT_TRUE(
6313 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6314 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6315}
6316
[email protected]242d8562012-10-30 21:20:466317TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556318 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6319 https_test_server.SetSSLConfig(
6320 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6321 https_test_server.ServeFilesFromSourceDirectory(
6322 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466323 ASSERT_TRUE(https_test_server.Start());
6324
tommycli59a63432015-11-06 00:10:556325 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166326
[email protected]242d8562012-10-30 21:20:466327 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366328 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556329 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6330 &d));
[email protected]f7022f32014-08-21 16:32:196331 request->Start();
[email protected]255620da2013-08-19 13:14:296332 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466333
6334 // We should have set parameters from the first header, not the second.
6335 TransportSecurityState* security_state =
6336 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406337 TransportSecurityState::STSState sts_state;
6338 EXPECT_TRUE(
6339 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6340 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6341 sts_state.upgrade_mode);
6342 EXPECT_FALSE(sts_state.include_subdomains);
6343 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466344}
6345
[email protected]9f972ec2013-04-10 20:24:366346TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556347 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6348 https_test_server.SetSSLConfig(
6349 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6350 https_test_server.ServeFilesFromSourceDirectory(
6351 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366352 ASSERT_TRUE(https_test_server.Start());
6353
tommycli59a63432015-11-06 00:10:556354 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166355
[email protected]9f972ec2013-04-10 20:24:366356 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366357 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556358 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6359 &d));
[email protected]f7022f32014-08-21 16:32:196360 request->Start();
[email protected]255620da2013-08-19 13:14:296361 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366362
6363 // We should have set parameters from the first header, not the second.
6364 TransportSecurityState* security_state =
6365 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406366 TransportSecurityState::STSState sts_state;
6367 TransportSecurityState::PKPState pkp_state;
6368 EXPECT_TRUE(
6369 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6370 EXPECT_TRUE(
6371 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6372 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6373 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036374#if defined(OS_ANDROID)
6375 // Android's CertVerifyProc does not (yet) handle pins.
6376#else
martijnc0d6b622015-06-30 19:14:406377 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036378#endif
martijnc0d6b622015-06-30 19:14:406379 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366380
[email protected]a165f092013-06-12 16:10:056381 // Even though there is an HSTS header asserting includeSubdomains, it is
6382 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406383 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056384 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406385 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366386}
6387
[email protected]37fd55fb2013-06-29 13:13:276388// Tests that when multiple HPKP headers are present, asserting different
6389// policies, that only the first such policy is processed.
6390TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556391 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6392 https_test_server.SetSSLConfig(
6393 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6394 https_test_server.ServeFilesFromSourceDirectory(
6395 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276396 ASSERT_TRUE(https_test_server.Start());
6397
tommycli59a63432015-11-06 00:10:556398 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166399
[email protected]37fd55fb2013-06-29 13:13:276400 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366401 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556402 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366403 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196404 request->Start();
[email protected]255620da2013-08-19 13:14:296405 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276406
6407 TransportSecurityState* security_state =
6408 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406409 TransportSecurityState::STSState sts_state;
6410 TransportSecurityState::PKPState pkp_state;
6411 EXPECT_TRUE(
6412 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6413 EXPECT_TRUE(
6414 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6415 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6416 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036417#if defined(OS_ANDROID)
6418 // Android's CertVerifyProc does not (yet) handle pins.
6419#else
martijnc0d6b622015-06-30 19:14:406420 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036421#endif
martijnc0d6b622015-06-30 19:14:406422 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276423
martijnc0d6b622015-06-30 19:14:406424 EXPECT_TRUE(sts_state.include_subdomains);
6425 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276426}
6427
estark1614475f2016-03-10 03:46:476428// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6429// called.
6430class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6431 public:
6432 MockExpectCTReporter() : num_failures_(0) {}
6433 ~MockExpectCTReporter() override {}
6434
6435 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6436 const GURL& report_uri,
6437 const net::SSLInfo& ssl_info) override {
6438 num_failures_++;
6439 }
6440
6441 uint32_t num_failures() { return num_failures_; }
6442
6443 private:
6444 uint32_t num_failures_;
6445};
6446
estark1614475f2016-03-10 03:46:476447// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6448// for every certificate.
6449class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6450 public:
6451 MockCTPolicyEnforcer()
6452 : default_result_(
6453 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6454 ~MockCTPolicyEnforcer() override {}
6455
6456 ct::CertPolicyCompliance DoesConformToCertPolicy(
6457 X509Certificate* cert,
6458 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206459 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476460 return default_result_;
6461 }
6462
6463 void set_default_result(ct::CertPolicyCompliance default_result) {
6464 default_result_ = default_result;
6465 }
6466
6467 private:
6468 ct::CertPolicyCompliance default_result_;
6469};
6470
6471// Tests that Expect CT headers are processed correctly.
6472TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6473 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6474 https_test_server.SetSSLConfig(
6475 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6476 https_test_server.ServeFilesFromSourceDirectory(
6477 base::FilePath(kTestFilePath));
6478 ASSERT_TRUE(https_test_server.Start());
6479
6480 MockExpectCTReporter reporter;
6481 TransportSecurityState transport_security_state;
6482 transport_security_state.enable_static_expect_ct_ = true;
6483 transport_security_state.SetExpectCTReporter(&reporter);
6484
6485 // Set up a MockCertVerifier to accept the certificate that the server sends.
6486 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6487 ASSERT_TRUE(cert);
6488 MockCertVerifier cert_verifier;
6489 CertVerifyResult verify_result;
6490 verify_result.verified_cert = cert;
6491 verify_result.is_issued_by_known_root = true;
6492 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6493
rsleevi22cae1672016-12-28 01:53:366494 // Set up a DoNothingCTVerifier and MockCTPolicyEnforcer to trigger an Expect
6495 // CT violation.
6496 DoNothingCTVerifier ct_verifier;
estark1614475f2016-03-10 03:46:476497 MockCTPolicyEnforcer ct_policy_enforcer;
6498 ct_policy_enforcer.set_default_result(
6499 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6500
6501 TestNetworkDelegate network_delegate;
6502 // Use a MockHostResolver (which by default maps all hosts to
6503 // 127.0.0.1) so that the request can be sent to a site on the Expect
6504 // CT preload list.
6505 MockHostResolver host_resolver;
6506 TestURLRequestContext context(true);
6507 context.set_host_resolver(&host_resolver);
6508 context.set_transport_security_state(&transport_security_state);
6509 context.set_network_delegate(&network_delegate);
6510 context.set_cert_verifier(&cert_verifier);
6511 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206512 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476513 context.Init();
6514
6515 // Now send a request to trigger the violation.
6516 TestDelegate d;
6517 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6518 GURL::Replacements replace_host;
6519 replace_host.SetHostStr(kExpectCTStaticHostname);
6520 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366521 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476522 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6523 violating_request->Start();
6524 base::RunLoop().Run();
6525
6526 EXPECT_EQ(1u, reporter.num_failures());
6527}
6528
tommycli59a63432015-11-06 00:10:556529#endif // !defined(OS_IOS)
6530
[email protected]316c1e5e2012-09-12 15:17:446531TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556532 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446533
6534 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366535 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556536 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366537 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196538 req->Start();
[email protected]255620da2013-08-19 13:14:296539 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446540
6541 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196542 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446543 EXPECT_EQ("text/html", mime_type);
6544
6545 std::string charset;
[email protected]f7022f32014-08-21 16:32:196546 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446547 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196548 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446549}
6550
[email protected]02494ec2014-05-07 15:05:296551TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346552 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346553 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346554 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026555 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346556
6557 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506558 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346559}
6560
brettwa1228ebb2016-10-28 03:51:346561#if !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]02494ec2014-05-07 15:05:296562TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6563 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6564 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456565 FileProtocolHandler file_protocol_handler(
6566 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296567 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6568
6569 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506570 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296571}
6572
[email protected]588614c22013-08-16 00:09:026573TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556574 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446575
6576 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366577 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556578 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366579 &d));
[email protected]f7022f32014-08-21 16:32:196580 req->Start();
[email protected]255620da2013-08-19 13:14:296581 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446582
maksim.sisovb53724b52016-09-16 05:30:506583 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446584}
brettwa1228ebb2016-10-28 03:51:346585#endif // !BUILDFLAG(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446586
[email protected]588614c22013-08-16 00:09:026587TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556588 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026589
6590 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366591 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556592 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366593 &d));
[email protected]f7022f32014-08-21 16:32:196594 req->Start();
fdoray5eeb7642016-06-22 16:11:286595 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026596
maksim.sisovb53724b52016-09-16 05:30:506597 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]588614c22013-08-16 00:09:026598}
6599
[email protected]316c1e5e2012-09-12 15:17:446600TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556601 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446602
6603 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366604 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556605 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366606 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196607 req->Start();
[email protected]255620da2013-08-19 13:14:296608 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446609
maksim.sisovb53724b52016-09-16 05:30:506610 EXPECT_EQ(ERR_INVALID_URL, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446611}
6612
[email protected]e50efea2014-03-24 18:41:006613// Make sure redirects are cached, despite not reading their bodies.
6614TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556615 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006616 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556617 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006618
6619 {
6620 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366621 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366622 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196623 req->Start();
[email protected]e50efea2014-03-24 18:41:006624 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506625 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006626 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556627 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006628 }
6629
6630 {
6631 TestDelegate d;
6632 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366633 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366634 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196635 req->Start();
[email protected]e50efea2014-03-24 18:41:006636 base::RunLoop().Run();
6637
6638 EXPECT_EQ(1, d.received_redirect_count());
6639 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196640 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006641
[email protected]f7022f32014-08-21 16:32:196642 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006643 base::RunLoop().Run();
6644 EXPECT_EQ(1, d.received_redirect_count());
6645 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:506646 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:556647 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006648 }
6649}
6650
6651// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6652// when the headers are read, since the body won't have been read.
6653TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556654 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006655 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556656 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006657
6658 {
6659 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556660 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006661 default_network_delegate_.set_redirect_on_headers_received_url(
6662 redirect_to_url);
6663
6664 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366665 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366666 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196667 req->Start();
[email protected]e50efea2014-03-24 18:41:006668 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506669 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006670 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196671 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006672 }
6673
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();
6680
maksim.sisovb53724b52016-09-16 05:30:506681 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196682 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006683 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196684 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006685 }
6686}
6687
[email protected]5f714132014-03-26 10:41:166688// Tests that redirection to an unsafe URL is allowed when it has been marked as
6689// safe.
6690TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556691 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166692
6693 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6694 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6695 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6696
6697 TestDelegate d;
6698 {
danakj8522a25b2016-04-16 00:17:366699 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556700 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166701
[email protected]f7022f32014-08-21 16:32:196702 r->Start();
[email protected]5f714132014-03-26 10:41:166703 base::RunLoop().Run();
6704
maksim.sisovb53724b52016-09-16 05:30:506705 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196706 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:196707 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166708 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6709 }
6710}
6711
6712// Tests that a redirect to a different unsafe URL is blocked, even after adding
6713// some other URL to the whitelist.
6714TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556715 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166716
6717 GURL unsafe_url("data:text/html,something");
6718 GURL different_unsafe_url("data:text/html,something-else");
6719 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6720 default_network_delegate_.set_allowed_unsafe_redirect_url(
6721 different_unsafe_url);
6722
6723 TestDelegate d;
6724 {
danakj8522a25b2016-04-16 00:17:366725 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556726 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166727
[email protected]f7022f32014-08-21 16:32:196728 r->Start();
[email protected]5f714132014-03-26 10:41:166729 base::RunLoop().Run();
6730
maksim.sisovb53724b52016-09-16 05:30:506731 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]5f714132014-03-26 10:41:166732 }
6733}
6734
[email protected]5f714132014-03-26 10:41:166735// Redirects from an URL with fragment to an unsafe URL with fragment should
6736// be allowed, and the reference fragment of the target URL should be preserved.
6737TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556738 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166739
tommycli59a63432015-11-06 00:10:556740 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166741 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6742 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6743
6744 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6745 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6746
6747 TestDelegate d;
6748 {
danakj8522a25b2016-04-16 00:17:366749 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366750 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166751
[email protected]f7022f32014-08-21 16:32:196752 r->Start();
[email protected]5f714132014-03-26 10:41:166753 base::RunLoop().Run();
6754
[email protected]f7022f32014-08-21 16:32:196755 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506756 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196757 EXPECT_EQ(original_url, r->original_url());
6758 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166759 }
6760}
6761
6762// When a delegate has specified a safe redirect URL, but it does not match the
6763// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146764TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556765 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166766
tommycli59a63432015-11-06 00:10:556767 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166768 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556769 GURL redirect_url(http_test_server()->GetURL("/target"));
6770 GURL expected_redirect_url(
6771 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166772
6773 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6774 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6775
6776 TestDelegate d;
6777 {
danakj8522a25b2016-04-16 00:17:366778 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366779 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166780
[email protected]f7022f32014-08-21 16:32:196781 r->Start();
[email protected]5f714132014-03-26 10:41:166782 base::RunLoop().Run();
6783
[email protected]f7022f32014-08-21 16:32:196784 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506785 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196786 EXPECT_EQ(original_url, r->original_url());
6787 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166788 }
6789}
6790
[email protected]f878230e2014-04-03 15:36:146791// When a delegate has specified a safe redirect URL, assume that the redirect
6792// URL should not be changed. In particular, the reference fragment should not
6793// be modified.
6794TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556795 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146796
tommycli59a63432015-11-06 00:10:556797 GURL original_url(
6798 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146799 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6800
6801 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6802 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6803
6804 TestDelegate d;
6805 {
danakj8522a25b2016-04-16 00:17:366806 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366807 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146808
[email protected]f7022f32014-08-21 16:32:196809 r->Start();
[email protected]f878230e2014-04-03 15:36:146810 base::RunLoop().Run();
6811
[email protected]f7022f32014-08-21 16:32:196812 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506813 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196814 EXPECT_EQ(original_url, r->original_url());
6815 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146816 }
6817}
6818
6819// When a URLRequestRedirectJob is created, the redirection must be followed and
6820// the reference fragment of the target URL must not be modified.
6821TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556822 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146823
tommycli59a63432015-11-06 00:10:556824 GURL original_url(
6825 http_test_server()->GetURL("/original#should-not-be-appended"));
6826 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146827
6828 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366829 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366830 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146831
danakj8522a25b2016-04-16 00:17:366832 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196833 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426834 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6835 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146836
[email protected]f7022f32014-08-21 16:32:196837 r->Start();
[email protected]f878230e2014-04-03 15:36:146838 base::RunLoop().Run();
6839
maksim.sisovb53724b52016-09-16 05:30:506840 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196841 EXPECT_EQ(original_url, r->original_url());
6842 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146843}
6844
lizeb5120f6dc2016-02-19 09:29:446845TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6846 ASSERT_TRUE(http_test_server()->Start());
6847
6848 const std::string referrer("foobar://totally.legit.referrer");
6849 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366850 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446851 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6852 req->SetReferrer(referrer);
6853 req->Start();
6854 base::RunLoop().Run();
6855
6856 EXPECT_EQ(std::string("None"), d.data_received());
6857}
6858
[email protected]316c1e5e2012-09-12 15:17:446859TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556860 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446861
6862 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366863 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556864 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196865 req->SetReferrer("http://user:[email protected]/");
6866 req->Start();
[email protected]255620da2013-08-19 13:14:296867 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446868
6869 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6870}
6871
[email protected]99ecf6e2013-04-10 22:46:136872TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556873 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136874
6875 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366876 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556877 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196878 req->SetReferrer("http://foo.com/test#fragment");
6879 req->Start();
[email protected]255620da2013-08-19 13:14:296880 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136881
6882 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6883}
6884
6885TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556886 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136887
6888 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366889 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556890 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196891 req->SetReferrer("http://foo.com/test#fragment");
6892 req->SetReferrer("");
6893 req->Start();
[email protected]255620da2013-08-19 13:14:296894 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136895
6896 EXPECT_EQ(std::string("None"), d.data_received());
6897}
6898
[email protected]316c1e5e2012-09-12 15:17:446899TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556900 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446901
6902 TestDelegate d;
6903 {
6904 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366905 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556906 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6907 &d));
[email protected]f7022f32014-08-21 16:32:196908 req->Start();
[email protected]255620da2013-08-19 13:14:296909 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446910
6911 EXPECT_EQ(1, d.response_started_count());
6912 EXPECT_EQ(0, d.bytes_received());
6913 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506914 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446915 }
6916}
6917
6918TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556919 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446920
6921 TestDelegate d;
6922 {
6923 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556924 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366925 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366926 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046927
[email protected]f7022f32014-08-21 16:32:196928 req->Start();
[email protected]255620da2013-08-19 13:14:296929 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446930
6931 EXPECT_EQ(1, d.received_redirect_count());
6932
[email protected]f7022f32014-08-21 16:32:196933 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296934 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446935
6936 EXPECT_EQ(1, d.response_started_count());
6937 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506938 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446939
[email protected]6cdfd7f2013-02-08 20:40:156940 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446941 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476942 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446943 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6944
6945 std::string contents;
[email protected]82f84b92013-08-30 18:23:506946 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446947 EXPECT_EQ(contents, d.data_received());
6948 }
6949}
6950
[email protected]79e1fd62013-06-20 06:50:046951TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556952 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046953
6954 TestDelegate d;
6955 {
6956 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556957 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366958 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366959 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046960
6961 EXPECT_FALSE(d.have_full_request_headers());
6962
[email protected]f7022f32014-08-21 16:32:196963 req->Start();
[email protected]255620da2013-08-19 13:14:296964 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046965
6966 EXPECT_EQ(1, d.received_redirect_count());
6967 EXPECT_TRUE(d.have_full_request_headers());
6968 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6969 d.ClearFullRequestHeaders();
6970
[email protected]f7022f32014-08-21 16:32:196971 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296972 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046973
tommycli59a63432015-11-06 00:10:556974 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046975 EXPECT_EQ(1, d.response_started_count());
6976 EXPECT_TRUE(d.have_full_request_headers());
6977 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6978 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506979 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:046980
6981 base::FilePath path;
6982 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476983 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046984 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6985
6986 std::string contents;
[email protected]82f84b92013-08-30 18:23:506987 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046988 EXPECT_EQ(contents, d.data_received());
6989 }
6990}
6991
[email protected]316c1e5e2012-09-12 15:17:446992TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556993 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446994
6995 TestDelegate d;
6996 {
6997 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366998 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556999 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
7000 &d));
[email protected]f7022f32014-08-21 16:32:197001 req->Start();
[email protected]255620da2013-08-19 13:14:297002 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447003
7004 EXPECT_EQ(1, d.received_redirect_count());
7005
[email protected]f7022f32014-08-21 16:32:197006 req->Cancel();
[email protected]255620da2013-08-19 13:14:297007 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447008
7009 EXPECT_EQ(1, d.response_started_count());
7010 EXPECT_EQ(0, d.bytes_received());
7011 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:507012 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:447013 }
7014}
7015
7016TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557017 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447018
[email protected]3b23a222013-05-15 21:33:257019 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447020 {
7021 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367022 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557023 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7024 &d));
[email protected]316c1e5e2012-09-12 15:17:447025 HttpRequestHeaders headers;
7026 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197027 req->SetExtraRequestHeaders(headers);
7028 req->Start();
[email protected]255620da2013-08-19 13:14:297029 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257030
7031 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197032 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257033 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447034 }
7035
[email protected]3b23a222013-05-15 21:33:257036 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447037 {
7038 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367039 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557040 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7041 &d));
[email protected]316c1e5e2012-09-12 15:17:447042 HttpRequestHeaders headers;
7043 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197044 req->SetExtraRequestHeaders(headers);
7045 req->Start();
[email protected]255620da2013-08-19 13:14:297046 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447047
[email protected]f7022f32014-08-21 16:32:197048 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257049
7050 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197051 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257052 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447053 }
7054
[email protected]3b23a222013-05-15 21:33:257055 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447056 {
7057 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367058 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557059 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7060 &d));
[email protected]316c1e5e2012-09-12 15:17:447061 HttpRequestHeaders headers;
7062 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197063 req->SetExtraRequestHeaders(headers);
7064 req->Start();
[email protected]255620da2013-08-19 13:14:297065 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447066
[email protected]f7022f32014-08-21 16:32:197067 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257068
7069 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197070 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257071 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447072 }
7073}
7074
7075TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557076 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447077
7078 // populate the cache
7079 {
7080 TestDelegate d;
7081 d.set_credentials(AuthCredentials(kUser, kSecret));
7082
danakj8522a25b2016-04-16 00:17:367083 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557084 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197085 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447086
[email protected]255620da2013-08-19 13:14:297087 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447088
7089 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7090 }
7091
7092 // repeat request with end-to-end validation. since auth-basic results in a
7093 // cachable page, we expect this test to result in a 304. in which case, the
7094 // response should be fetched from the cache.
7095 {
7096 TestDelegate d;
7097 d.set_credentials(AuthCredentials(kUser, kSecret));
7098
danakj8522a25b2016-04-16 00:17:367099 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557100 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197101 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7102 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447103
[email protected]255620da2013-08-19 13:14:297104 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447105
7106 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7107
7108 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197109 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447110 }
7111}
7112
7113// Check that Set-Cookie headers in 401 responses are respected.
7114// http://crbug.com/6450
7115TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557116 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447117
7118 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557119 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447120
7121 // Request a page that will give a 401 containing a Set-Cookie header.
7122 // Verify that when the transaction is restarted, it includes the new cookie.
7123 {
[email protected]ceefd7fd2012-11-29 00:36:247124 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447125 TestURLRequestContext context(true);
7126 context.set_network_delegate(&network_delegate);
7127 context.Init();
7128
7129 TestDelegate d;
7130 d.set_credentials(AuthCredentials(kUser, kSecret));
7131
danakj8522a25b2016-04-16 00:17:367132 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367133 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197134 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447135
[email protected]255620da2013-08-19 13:14:297136 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447137
7138 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7139
7140 // Make sure we sent the cookie in the restarted transaction.
7141 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7142 != std::string::npos);
7143 }
7144
7145 // Same test as above, except this time the restart is initiated earlier
7146 // (without user intervention since identity is embedded in the URL).
7147 {
[email protected]ceefd7fd2012-11-29 00:36:247148 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447149 TestURLRequestContext context(true);
7150 context.set_network_delegate(&network_delegate);
7151 context.Init();
7152
7153 TestDelegate d;
7154
7155 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187156 replacements.SetUsernameStr("user2");
7157 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447158 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7159
danakj8522a25b2016-04-16 00:17:367160 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367161 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197162 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447163
[email protected]255620da2013-08-19 13:14:297164 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447165
7166 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7167
7168 // Make sure we sent the cookie in the restarted transaction.
7169 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7170 != std::string::npos);
7171 }
7172}
7173
[email protected]58e32bb2013-01-21 18:23:257174// Tests that load timing works as expected with auth and the cache.
7175TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557176 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257177
7178 // populate the cache
7179 {
7180 TestDelegate d;
7181 d.set_credentials(AuthCredentials(kUser, kSecret));
7182
danakj8522a25b2016-04-16 00:17:367183 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557184 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197185 r->Start();
[email protected]58e32bb2013-01-21 18:23:257186
[email protected]255620da2013-08-19 13:14:297187 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257188
7189 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7190
7191 LoadTimingInfo load_timing_info_before_auth;
7192 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7193 &load_timing_info_before_auth));
7194 TestLoadTimingNotReused(load_timing_info_before_auth,
7195 CONNECT_TIMING_HAS_DNS_TIMES);
7196
7197 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197198 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257199 // The test server does not support keep alive sockets, so the second
7200 // request with auth should use a new socket.
7201 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7202 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7203 load_timing_info.socket_log_id);
7204 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7205 load_timing_info.connect_timing.connect_start);
7206 }
7207
[email protected]3b23a222013-05-15 21:33:257208 // Repeat request with end-to-end validation. Since auth-basic results in a
7209 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257210 // response should be fetched from the cache.
7211 {
7212 TestDelegate d;
7213 d.set_credentials(AuthCredentials(kUser, kSecret));
7214
danakj8522a25b2016-04-16 00:17:367215 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557216 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197217 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7218 r->Start();
[email protected]58e32bb2013-01-21 18:23:257219
[email protected]255620da2013-08-19 13:14:297220 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257221
7222 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7223
7224 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197225 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257226
[email protected]3b23a222013-05-15 21:33:257227 // Since there was a request that went over the wire, the load timing
7228 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257229 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197230 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257231 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257232 }
7233}
7234
[email protected]316c1e5e2012-09-12 15:17:447235// In this test, we do a POST which the server will 302 redirect.
7236// The subsequent transaction should use GET, and should not send the
7237// Content-Type header.
7238// http://code.google.com/p/chromium/issues/detail?id=843
7239TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557240 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447241
7242 const char kData[] = "hello world";
7243
7244 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367245 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557246 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7247 &d));
[email protected]f7022f32014-08-21 16:32:197248 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077249 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447250
7251 // Set headers (some of which are specific to the POST).
7252 HttpRequestHeaders headers;
7253 headers.AddHeadersFromString(
7254 "Content-Type: multipart/form-data; "
7255 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7256 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7257 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7258 "Accept-Language: en-US,en\r\n"
7259 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7260 "Content-Length: 11\r\n"
7261 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197262 req->SetExtraRequestHeaders(headers);
7263 req->Start();
[email protected]255620da2013-08-19 13:14:297264 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447265
7266 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197267 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447268 EXPECT_EQ("text/html", mime_type);
7269
7270 const std::string& data = d.data_received();
7271
7272 // Check that the post-specific headers were stripped:
7273 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7274 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7275 EXPECT_FALSE(ContainsString(data, "Origin:"));
7276
7277 // These extra request headers should not have been stripped.
7278 EXPECT_TRUE(ContainsString(data, "Accept:"));
7279 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7280 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7281}
7282
jww5fe460ff2015-03-28 00:22:517283// The following tests check that we handle mutating the request for HTTP
7284// redirects as expected.
7285// See https://crbug.com/56373, https://crbug.com/102130, and
7286// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447287
7288TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557289 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447290
tommycli59a63432015-11-06 00:10:557291 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517292 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557293 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447294
7295 HTTPRedirectMethodTest(url, "POST", "GET", true);
7296 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7297 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517298
7299 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7300 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7301 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7302 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7303 std::string());
[email protected]316c1e5e2012-09-12 15:17:447304}
7305
7306TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557307 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447308
tommycli59a63432015-11-06 00:10:557309 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517310 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557311 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447312
7313 HTTPRedirectMethodTest(url, "POST", "GET", true);
7314 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7315 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517316
7317 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7318 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7319 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7320 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7321 std::string());
[email protected]316c1e5e2012-09-12 15:17:447322}
7323
7324TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557325 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447326
tommycli59a63432015-11-06 00:10:557327 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517328 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557329 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447330
7331 HTTPRedirectMethodTest(url, "POST", "GET", true);
7332 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7333 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517334
7335 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7336 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7337 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7338 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7339 std::string());
[email protected]316c1e5e2012-09-12 15:17:447340}
7341
7342TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557343 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447344
tommycli59a63432015-11-06 00:10:557345 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517346 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557347 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447348
7349 HTTPRedirectMethodTest(url, "POST", "POST", true);
7350 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7351 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517352
7353 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7354 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7355 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7356 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447357}
7358
[email protected]0a17aab32014-04-24 03:32:377359TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557360 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377361
tommycli59a63432015-11-06 00:10:557362 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517363 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557364 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377365
7366 HTTPRedirectMethodTest(url, "POST", "POST", true);
7367 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7368 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517369
7370 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7371 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7372 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7373 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377374}
7375
7376// Make sure that 308 responses without bodies are not treated as redirects.
7377// Certain legacy apis that pre-date the response code expect this behavior
7378// (Like Google Drive).
7379TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557380 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377381
7382 TestDelegate d;
tommycli59a63432015-11-06 00:10:557383 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377384
danakj8522a25b2016-04-16 00:17:367385 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367386 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377387
[email protected]f7022f32014-08-21 16:32:197388 request->Start();
[email protected]0a17aab32014-04-24 03:32:377389 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507390 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:377391 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197392 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377393 EXPECT_EQ("This is not a redirect.", d.data_received());
7394}
7395
[email protected]f878230e2014-04-03 15:36:147396TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557397 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147398
tommycli59a63432015-11-06 00:10:557399 GURL original_url(
7400 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7401 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147402
7403 TestDelegate d;
7404 {
danakj8522a25b2016-04-16 00:17:367405 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367406 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147407
[email protected]f7022f32014-08-21 16:32:197408 r->Start();
[email protected]f878230e2014-04-03 15:36:147409 base::RunLoop().Run();
7410
[email protected]f7022f32014-08-21 16:32:197411 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507412 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197413 EXPECT_EQ(original_url, r->original_url());
7414 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147415 }
7416}
7417
[email protected]cba24642014-08-15 20:49:597418TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557419 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597420
tommycli59a63432015-11-06 00:10:557421 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597422 GURL first_party_url("http://example.com");
7423
7424 TestDelegate d;
7425 {
danakj8522a25b2016-04-16 00:17:367426 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367427 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197428 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597429
[email protected]f7022f32014-08-21 16:32:197430 r->Start();
[email protected]cba24642014-08-15 20:49:597431 base::RunLoop().Run();
7432
[email protected]f7022f32014-08-21 16:32:197433 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507434 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197435 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597436 }
7437}
7438
7439TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557440 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597441
tommycli59a63432015-11-06 00:10:557442 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597443 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557444 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597445
7446 TestDelegate d;
7447 {
danakj8522a25b2016-04-16 00:17:367448 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367449 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197450 r->set_first_party_for_cookies(original_first_party_url);
7451 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597452 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7453
[email protected]f7022f32014-08-21 16:32:197454 r->Start();
[email protected]cba24642014-08-15 20:49:597455 base::RunLoop().Run();
7456
[email protected]f7022f32014-08-21 16:32:197457 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507458 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197459 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597460 }
7461}
7462
[email protected]316c1e5e2012-09-12 15:17:447463TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557464 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447465
7466 const char kData[] = "hello world";
7467
7468 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367469 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557470 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197471 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077472 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447473 HttpRequestHeaders headers;
7474 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517475 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197476 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447477
danakj8522a25b2016-04-16 00:17:367478 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557479 req.get(), &default_network_delegate_,
7480 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427481 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7482 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447483
[email protected]f7022f32014-08-21 16:32:197484 req->Start();
[email protected]255620da2013-08-19 13:14:297485 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197486 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447487}
7488
7489TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557490 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447491
7492 const char kData[] = "hello world";
7493
7494 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367495 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557496 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197497 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077498 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447499 HttpRequestHeaders headers;
7500 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517501 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197502 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447503
danakj8522a25b2016-04-16 00:17:367504 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557505 req.get(), &default_network_delegate_,
7506 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097507 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427508 "Very Good Reason"));
7509 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447510
[email protected]f7022f32014-08-21 16:32:197511 req->Start();
[email protected]255620da2013-08-19 13:14:297512 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197513 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447514 EXPECT_EQ(kData, d.data_received());
7515}
7516
7517// Check that default A-L header is sent.
7518TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557519 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447520
[email protected]8790210c2013-12-02 05:29:537521 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247522 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447523 TestURLRequestContext context(true);
7524 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437525 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447526 context.Init();
7527
7528 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367529 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557530 http_test_server()->GetURL("/echoheader?Accept-Language"),
7531 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197532 req->Start();
[email protected]255620da2013-08-19 13:14:297533 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447534 EXPECT_EQ("en", d.data_received());
7535}
7536
7537// Check that an empty A-L header is not sent. http://crbug.com/77365.
7538TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557539 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447540
[email protected]8790210c2013-12-02 05:29:537541 std::string empty_string; // Avoid most vexing parse on line below.
7542 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247543 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447544 TestURLRequestContext context(true);
7545 context.set_network_delegate(&network_delegate);
7546 context.Init();
7547 // We override the language after initialization because empty entries
7548 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437549 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447550
7551 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367552 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557553 http_test_server()->GetURL("/echoheader?Accept-Language"),
7554 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197555 req->Start();
[email protected]255620da2013-08-19 13:14:297556 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447557 EXPECT_EQ("None", d.data_received());
7558}
7559
7560// Check that if request overrides the A-L header, the default is not appended.
7561// See http://crbug.com/20894
7562TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557563 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447564
7565 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367566 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557567 http_test_server()->GetURL("/echoheader?Accept-Language"),
7568 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447569 HttpRequestHeaders headers;
7570 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197571 req->SetExtraRequestHeaders(headers);
7572 req->Start();
[email protected]255620da2013-08-19 13:14:297573 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447574 EXPECT_EQ(std::string("ru"), d.data_received());
7575}
7576
7577// Check that default A-E header is sent.
7578TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557579 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447580
7581 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367582 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557583 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7584 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447585 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197586 req->SetExtraRequestHeaders(headers);
7587 req->Start();
[email protected]255620da2013-08-19 13:14:297588 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447589 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7590}
7591
7592// Check that if request overrides the A-E header, the default is not appended.
7593// See http://crbug.com/47381
7594TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557595 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447596
7597 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367598 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557599 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7600 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447601 HttpRequestHeaders headers;
7602 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197603 req->SetExtraRequestHeaders(headers);
7604 req->Start();
[email protected]255620da2013-08-19 13:14:297605 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447606 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7607 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7608}
7609
[email protected]84f05432013-03-15 01:00:127610// Check that setting the A-C header sends the proper header.
7611TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557612 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447613
7614 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367615 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557616 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7617 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447618 HttpRequestHeaders headers;
7619 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197620 req->SetExtraRequestHeaders(headers);
7621 req->Start();
[email protected]255620da2013-08-19 13:14:297622 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447623 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7624}
7625
7626// Check that default User-Agent header is sent.
7627TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557628 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447629
7630 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367631 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557632 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7633 &d));
[email protected]f7022f32014-08-21 16:32:197634 req->Start();
[email protected]255620da2013-08-19 13:14:297635 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197636 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377637 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447638}
7639
7640// Check that if request overrides the User-Agent header,
7641// the default is not appended.
marqf14fff8d2015-12-02 15:52:297642// TODO(crbug.com/564656) This test is flaky on iOS.
7643#if defined(OS_IOS)
7644#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7645#else
7646#define MAYBE_OverrideUserAgent OverrideUserAgent
7647#endif
7648TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557649 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447650
7651 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367652 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557653 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7654 &d));
[email protected]316c1e5e2012-09-12 15:17:447655 HttpRequestHeaders headers;
7656 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197657 req->SetExtraRequestHeaders(headers);
7658 req->Start();
[email protected]255620da2013-08-19 13:14:297659 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357660 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447661}
7662
[email protected]ee4c30d2012-11-07 15:08:437663// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7664// User-Agent header to be sent but does not send the Accept-Language and
7665// Accept-Charset headers.
7666TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557667 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437668
[email protected]ceefd7fd2012-11-29 00:36:247669 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437670 TestURLRequestContext context(true);
7671 context.set_network_delegate(&network_delegate);
7672 context.Init();
7673 // We override the HttpUserAgentSettings after initialization because empty
7674 // entries get overridden by Init().
7675 context.set_http_user_agent_settings(NULL);
7676
7677 struct {
7678 const char* request;
7679 const char* expected_response;
tommycli59a63432015-11-06 00:10:557680 } tests[] = {{"/echoheader?Accept-Language", "None"},
7681 {"/echoheader?Accept-Charset", "None"},
7682 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437683
viettrungluue4a8b882014-10-16 06:17:387684 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437685 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367686 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557687 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197688 req->Start();
[email protected]255620da2013-08-19 13:14:297689 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437690 EXPECT_EQ(tests[i].expected_response, d.data_received())
7691 << " Request = \"" << tests[i].request << "\"";
7692 }
7693}
7694
[email protected]5033ab82013-03-22 20:17:467695// Make sure that URLRequest passes on its priority updates to
7696// newly-created jobs after the first one.
7697TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557698 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467699
7700 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367701 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557702 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197703 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467704
danakj8522a25b2016-04-16 00:17:367705 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557706 req.get(), &default_network_delegate_,
7707 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427708 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7709 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467710
[email protected]f7022f32014-08-21 16:32:197711 req->SetPriority(LOW);
7712 req->Start();
7713 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467714
mmenkeed0498b2015-12-08 23:20:427715 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367716 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427717 req.get(), &default_network_delegate_, &job_priority));
7718 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467719
7720 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297721 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427722 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467723}
7724
[email protected]80abdad2014-03-15 00:20:547725// Check that creating a network request while entering/exiting suspend mode
7726// fails as it should. This is the only case where an HttpTransactionFactory
7727// does not return an HttpTransaction.
7728TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7729 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367730 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177731 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547732 network_layer->OnSuspend();
7733
dchengc7eeda422015-12-26 03:56:487734 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427735 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547736
7737 TestURLRequestContext context(true);
7738 context.set_http_transaction_factory(&http_cache);
7739 context.Init();
7740
7741 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367742 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367743 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197744 req->Start();
[email protected]80abdad2014-03-15 00:20:547745 base::RunLoop().Run();
7746
7747 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:507748 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:547749}
7750
mmenke2281f3762015-11-02 20:38:177751namespace {
[email protected]80abdad2014-03-15 00:20:547752
mmenke2281f3762015-11-02 20:38:177753// HttpTransactionFactory that synchronously fails to create transactions.
7754class FailingHttpTransactionFactory : public HttpTransactionFactory {
7755 public:
7756 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7757 : network_session_(network_session) {}
7758
7759 ~FailingHttpTransactionFactory() override {}
7760
7761 // HttpTransactionFactory methods:
7762 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367763 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177764 return ERR_FAILED;
7765 }
7766
7767 HttpCache* GetCache() override { return nullptr; }
7768
7769 HttpNetworkSession* GetSession() override { return network_session_; }
7770
7771 private:
7772 HttpNetworkSession* network_session_;
7773
7774 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7775};
7776
7777} // namespace
7778
7779// Check that when a request that fails to create an HttpTransaction can be
7780// cancelled while the failure notification is pending, and doesn't send two
7781// failure notifications.
7782//
7783// This currently only happens when in suspend mode and there's no cache, but
7784// just use a special HttpTransactionFactory, to avoid depending on those
7785// behaviors.
7786TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7787 FailingHttpTransactionFactory http_transaction_factory(
7788 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547789 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177790 context.set_http_transaction_factory(&http_transaction_factory);
7791 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547792 context.Init();
7793
7794 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367795 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367796 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177797 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7798 // try to create an HttpNetworkTransaction synchronously on start).
7799 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197800 req->Start();
mmenke2281f3762015-11-02 20:38:177801 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547802 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177803 // Run pending error task, if there is one.
7804 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547805
7806 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177807 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507808 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:177809
7810 // NetworkDelegate should see the cancellation, but not the error.
7811 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7812 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547813}
7814
ttuttlec0c828492015-05-15 01:25:557815TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557816 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557817
7818 TestDelegate d;
tommycli59a63432015-11-06 00:10:557819 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367820 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557821 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7822
7823 req->Start();
7824 base::RunLoop().Run();
7825
7826 EXPECT_TRUE(req->response_info().network_accessed);
7827}
7828
7829TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557830 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557831
7832 // Populate the cache.
7833 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367834 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557835 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557836 req->Start();
7837 base::RunLoop().Run();
7838
maksim.sisovb53724b52016-09-16 05:30:507839 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557840 EXPECT_TRUE(req->response_info().network_accessed);
7841 EXPECT_FALSE(req->response_info().was_cached);
7842
tommycli59a63432015-11-06 00:10:557843 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557844 DEFAULT_PRIORITY, &d);
7845 req->Start();
7846 base::RunLoop().Run();
7847
maksim.sisovb53724b52016-09-16 05:30:507848 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557849 EXPECT_FALSE(req->response_info().network_accessed);
7850 EXPECT_TRUE(req->response_info().was_cached);
7851}
7852
7853TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557854 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557855
7856 TestDelegate d;
tommycli59a63432015-11-06 00:10:557857 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367858 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557859 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
jkarlina067deed2016-10-27 14:48:337860 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE | LOAD_SKIP_CACHE_VALIDATION);
ttuttlec0c828492015-05-15 01:25:557861
7862 req->Start();
7863 base::RunLoop().Run();
7864
7865 EXPECT_FALSE(req->response_info().network_accessed);
7866}
7867
rdsmithbf8c3c12016-11-18 18:16:247868// Test that a single job with a THROTTLED priority completes
rdsmith5eb6fbc2016-10-21 17:36:087869// correctly in the absence of contention.
7870TEST_F(URLRequestTestHTTP, ThrottledPriority) {
7871 ASSERT_TRUE(http_test_server()->Start());
7872
7873 TestDelegate d;
7874 GURL test_url(http_test_server()->GetURL("/"));
7875 std::unique_ptr<URLRequest> req(
7876 default_context_.CreateRequest(test_url, THROTTLED, &d));
7877 req->Start();
7878 base::RunLoop().Run();
7879
7880 EXPECT_TRUE(req->status().is_success());
7881}
7882
rdsmithbf8c3c12016-11-18 18:16:247883// A class to hold state for responding to USER_NOTIFY callbacks from
7884// BlockingNetworkDelegate. It also accepts a RunLoop that will be
7885// signaled via QuitWhenIdle() when any request is blocked.
7886//
7887class NotificationCallbackHandler {
7888 public:
7889 // Default constructed object doesn't block anything.
7890 NotificationCallbackHandler() : run_loop_(nullptr) {}
7891
7892 void AddURLRequestToBlockList(const URLRequest* request) {
7893 requests_to_block_.insert(request);
7894 }
7895
7896 Error ShouldBlockRequest(const CompletionCallback& callback,
7897 const URLRequest* request) {
7898 if (requests_to_block_.find(request) == requests_to_block_.end()) {
7899 return OK;
7900 }
7901
7902 DCHECK(blocked_callbacks_.find(request) == blocked_callbacks_.end());
7903 blocked_callbacks_[request] = callback;
7904 if (run_loop_ && blocked_callbacks_.size() == requests_to_block_.size())
7905 run_loop_->QuitWhenIdle();
7906 return ERR_IO_PENDING;
7907 }
7908
7909 // Erases object's memory of blocked callbacks as a side effect.
7910 void GetBlockedCallbacks(
7911 std::map<const URLRequest*, CompletionCallback>* blocked_callbacks) {
7912 blocked_callbacks_.swap(*blocked_callbacks);
7913 }
7914
7915 // Set a RunLoop that, if non-null, will be signaled if any request
7916 // is blocked. It is the callers responsibility to make sure the
7917 // passed object lives past the destruction of this class or
7918 // next call to SetRunLoop().
7919 void SetRunLoop(base::RunLoop* run_loop) { run_loop_ = run_loop; }
7920
7921 private:
7922 std::set<const URLRequest*> requests_to_block_;
7923 std::map<const URLRequest*, CompletionCallback> blocked_callbacks_;
7924
7925 base::RunLoop* run_loop_;
7926
7927 DISALLOW_COPY_AND_ASSIGN(NotificationCallbackHandler);
7928};
7929
7930TEST_F(URLRequestTestHTTP, MultiThrottledPriority) {
7931 ASSERT_TRUE(http_test_server()->Start());
7932
7933 base::RunLoop run_until_request_blocked;
7934
7935 NotificationCallbackHandler notification_handler;
7936 notification_handler.SetRunLoop(&run_until_request_blocked);
7937 BlockingNetworkDelegate network_delegate(
7938 BlockingNetworkDelegate::USER_NOTIFY);
7939 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
7940 network_delegate.set_notification_callback(
7941 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
7942 // Both objects are owned by this function, and
7943 // |*network_delegate| will be destroyed first, so
7944 // it's safe to pass it an unretained pointer.
7945 base::Unretained(&notification_handler)));
7946
7947 TestURLRequestContext context(true);
7948 context.set_network_delegate(&network_delegate);
7949 context.Init();
7950
7951 // Use different test URLs to make sure all three requests turn into
7952 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
7953 // the requests may be waited on separately.
7954 TestDelegate d1;
7955 std::unique_ptr<URLRequest> req1(context.CreateRequest(
7956 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
7957 notification_handler.AddURLRequestToBlockList(req1.get());
7958
7959 TestDelegate d2;
7960 std::unique_ptr<URLRequest> req2(context.CreateRequest(
7961 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
7962 notification_handler.AddURLRequestToBlockList(req2.get());
7963
7964 TestDelegate d3;
7965 std::unique_ptr<URLRequest> req3(context.CreateRequest(
7966 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
7967 req1->Start();
7968 req2->Start();
7969 req3->Start();
7970 run_until_request_blocked.Run();
7971 notification_handler.SetRunLoop(nullptr);
7972
7973 // The first two requests should be blocked based on the notification
7974 // callback, and their status should have blocked the third request
7975 // through throttling.
7976 EXPECT_TRUE(req1->status().is_io_pending());
7977 EXPECT_TRUE(req2->status().is_io_pending());
7978 EXPECT_TRUE(req3->status().is_io_pending());
7979
7980 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
7981 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
7982 ASSERT_EQ(2u, blocked_callbacks.size());
7983 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
7984 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
7985
7986 // Unblocking one of the requests blocked on the notification callback
7987 // should let it complete, which should then let the third request
7988 // complete. Unblock the second request, then wait for the third
7989 // request to complete.
7990 // TODO(rdsmith): Find something to wait on other than the third
7991 // requests completion; if there's a bug in throttling, that will
7992 // result in this test hanging rather than failing quickly.
7993 d1.set_quit_on_complete(false);
7994 d2.set_quit_on_complete(false);
7995 d3.set_quit_on_complete(true);
7996 blocked_callbacks[req2.get()].Run(OK);
7997 base::RunLoop().Run();
7998
7999 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8000 EXPECT_EQ(0u, blocked_callbacks.size());
8001 EXPECT_TRUE(req1->status().is_io_pending());
8002 // req3 is only unblocked after req2 completes, so req2's
8003 // success is guaranteed at this point in the function.
8004 EXPECT_EQ(URLRequestStatus::SUCCESS, req2->status().status());
8005 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8006}
8007
8008// Confirm that failing a request unblocks following requests.
8009TEST_F(URLRequestTestHTTP, ThrottledFailure) {
8010 ASSERT_TRUE(http_test_server()->Start());
8011
8012 base::RunLoop run_until_request_blocked;
8013
8014 NotificationCallbackHandler notification_handler;
8015 notification_handler.SetRunLoop(&run_until_request_blocked);
8016 BlockingNetworkDelegate network_delegate(
8017 BlockingNetworkDelegate::USER_NOTIFY);
8018 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8019 network_delegate.set_notification_callback(
8020 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8021 // Both objects are owned by this function, and
8022 // |*network_delegate| will be destroyed first, so
8023 // it's safe to pass it an unretained pointer.
8024 base::Unretained(&notification_handler)));
8025
8026 TestURLRequestContext context(true);
8027 context.set_network_delegate(&network_delegate);
8028 context.Init();
8029
8030 // Use different test URLs to make sure all three requests turn into
8031 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8032 // the requests may be waited on separately.
8033 TestDelegate d1;
8034 std::unique_ptr<URLRequest> req1(context.CreateRequest(
8035 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
8036 notification_handler.AddURLRequestToBlockList(req1.get());
8037
8038 TestDelegate d2;
8039 std::unique_ptr<URLRequest> req2(context.CreateRequest(
8040 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
8041 notification_handler.AddURLRequestToBlockList(req2.get());
8042
8043 TestDelegate d3;
8044 std::unique_ptr<URLRequest> req3(context.CreateRequest(
8045 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
8046 req1->Start();
8047 req2->Start();
8048 req3->Start();
8049 run_until_request_blocked.Run();
8050 notification_handler.SetRunLoop(nullptr);
8051
8052 // The first two requests should be blocked based on the notification
8053 // callback, and their status should have blocked the third request
8054 // through throttling.
8055 EXPECT_TRUE(req1->status().is_io_pending());
8056 EXPECT_TRUE(req2->status().is_io_pending());
8057 EXPECT_TRUE(req3->status().is_io_pending());
8058
8059 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8060 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8061 ASSERT_EQ(2u, blocked_callbacks.size());
8062 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8063 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8064
8065 // Confirm canceling one of the outstanding requests allows the
8066 // blocked request to complete.
8067
8068 // TODO(rdsmith): Find something to wait on other than the third
8069 // requests completion; if there's a bug in throttling, that will
8070 // result in this test hanging rather than failing quickly.
8071 d1.set_quit_on_complete(false);
8072 d2.set_quit_on_complete(false);
8073 d3.set_quit_on_complete(true);
8074 req2->Cancel();
8075 base::RunLoop().Run();
8076
8077 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8078 EXPECT_EQ(0u, blocked_callbacks.size());
8079 EXPECT_TRUE(req1->status().is_io_pending());
8080 EXPECT_EQ(URLRequestStatus::CANCELED, req2->status().status());
8081 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8082}
8083
8084TEST_F(URLRequestTestHTTP, ThrottledRepriUnblock) {
8085 ASSERT_TRUE(http_test_server()->Start());
8086
8087 base::RunLoop run_until_request_blocked;
8088
8089 NotificationCallbackHandler notification_handler;
8090 notification_handler.SetRunLoop(&run_until_request_blocked);
8091 BlockingNetworkDelegate network_delegate(
8092 BlockingNetworkDelegate::USER_NOTIFY);
8093 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
8094 network_delegate.set_notification_callback(
8095 base::Bind(&NotificationCallbackHandler::ShouldBlockRequest,
8096 // Both objects are owned by this function, and
8097 // |*network_delegate| will be destroyed first, so
8098 // it's safe to pass it an unretained pointer.
8099 base::Unretained(&notification_handler)));
8100
8101 TestURLRequestContext context(true);
8102 context.set_network_delegate(&network_delegate);
8103 context.Init();
8104
8105 // Use different test URLs to make sure all three requests turn into
8106 // HttpNetworkTransacations. Use different URLRequest::Delegates so that
8107 // the requests may be waited on separately.
8108 TestDelegate d1;
8109 std::unique_ptr<URLRequest> req1(context.CreateRequest(
8110 http_test_server()->GetURL("/echoall/l"), THROTTLED, &d1));
8111 notification_handler.AddURLRequestToBlockList(req1.get());
8112
8113 TestDelegate d2;
8114 std::unique_ptr<URLRequest> req2(context.CreateRequest(
8115 http_test_server()->GetURL("/echoall/2"), THROTTLED, &d2));
8116 notification_handler.AddURLRequestToBlockList(req2.get());
8117
8118 TestDelegate d3;
8119 std::unique_ptr<URLRequest> req3(context.CreateRequest(
8120 http_test_server()->GetURL("/echoall/3"), THROTTLED, &d3));
8121 req1->Start();
8122 req2->Start();
8123 req3->Start();
8124 run_until_request_blocked.Run();
8125 notification_handler.SetRunLoop(nullptr);
8126
8127 // The first two requests should be blocked based on the notification
8128 // callback, and their status should have blocked the third request
8129 // through throttling.
8130 EXPECT_TRUE(req1->status().is_io_pending());
8131 EXPECT_TRUE(req2->status().is_io_pending());
8132 EXPECT_TRUE(req3->status().is_io_pending());
8133
8134 std::map<const URLRequest*, CompletionCallback> blocked_callbacks;
8135 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8136 ASSERT_EQ(2u, blocked_callbacks.size());
8137 ASSERT_TRUE(blocked_callbacks.find(req1.get()) != blocked_callbacks.end());
8138 ASSERT_TRUE(blocked_callbacks.find(req2.get()) != blocked_callbacks.end());
8139
8140 // Confirm raising the priority of the third request allows it to complete.
8141
8142 // TODO(rdsmith): Find something to wait on other than the third
8143 // requests completion; if there's a bug in throttling, that will
8144 // result in this test hanging rather than failing quickly.
8145 d1.set_quit_on_complete(false);
8146 d2.set_quit_on_complete(false);
8147 d3.set_quit_on_complete(true);
8148 req3->SetPriority(IDLE);
8149 base::RunLoop().Run();
8150
8151 notification_handler.GetBlockedCallbacks(&blocked_callbacks);
8152 EXPECT_EQ(0u, blocked_callbacks.size());
8153 EXPECT_TRUE(req1->status().is_io_pending());
8154 EXPECT_TRUE(req2->status().is_io_pending());
8155 EXPECT_EQ(URLRequestStatus::SUCCESS, req3->status().status());
8156}
8157
ricea3a1c71f2016-06-17 10:05:268158TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
8159 ASSERT_TRUE(http_test_server()->Start());
8160
8161 TestDelegate d;
8162 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8163 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
8164 req->Start();
8165 base::RunLoop().Run();
8166
8167 EXPECT_EQ(5, req->GetRawBodyBytes());
8168}
8169
8170TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
8171 ASSERT_TRUE(http_test_server()->Start());
8172
8173 TestDelegate d;
8174 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8175 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
8176 req->Start();
8177 base::RunLoop().Run();
8178
8179 EXPECT_EQ(30, req->GetRawBodyBytes());
8180}
8181
jamd3f5a3c2016-10-27 18:52:028182// Check that if NetworkDelegate::OnBeforeStartTransaction returns an error,
8183// the delegate isn't called back synchronously.
8184TEST_F(URLRequestTestHTTP, TesBeforeStartTransactionFails) {
8185 ASSERT_TRUE(http_test_server()->Start());
8186 default_network_delegate_.set_before_start_transaction_fails();
8187
8188 TestDelegate d;
8189 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
8190 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
8191 req->Start();
8192 DCHECK(!d.response_completed());
8193 base::RunLoop().Run();
8194 DCHECK(d.response_completed());
8195 EXPECT_EQ(ERR_FAILED, d.request_status());
8196}
8197
bengr1bf8e942014-11-07 01:36:508198class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
8199 public:
8200 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
8201 // ideally remove the dependency on URLRequestTestJob, and maybe move these
8202 // tests into the factory tests.
8203 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
8204 }
8205
8206 void SetUpFactory() override {
8207 interceptor_ = new MockURLRequestInterceptor();
8208 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:368209 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:508210 }
8211
8212 MockURLRequestInterceptor* interceptor() const {
8213 return interceptor_;
8214 }
8215
8216 private:
8217 MockURLRequestInterceptor* interceptor_;
8218};
8219
8220TEST_F(URLRequestInterceptorTestHTTP,
8221 NetworkDelegateNotificationOnRedirectIntercept) {
8222 interceptor()->set_intercept_redirect(true);
8223 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8224 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8225
tommycli59a63432015-11-06 00:10:558226 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508227
8228 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368229 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558230 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508231 req->Start();
8232 base::RunLoop().Run();
8233
8234 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8235 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:508236 int status = d.request_status();
8237 EXPECT_EQ(OK, status);
8238 if (status == OK)
bengr1bf8e942014-11-07 01:36:508239 EXPECT_EQ(200, req->response_headers()->response_code());
8240
8241 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8242 EXPECT_EQ(1, d.response_started_count());
8243 EXPECT_EQ(0, d.received_redirect_count());
8244
8245 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008246 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508247 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8248}
8249
8250TEST_F(URLRequestInterceptorTestHTTP,
8251 NetworkDelegateNotificationOnErrorIntercept) {
8252 // Intercept that error and respond with an OK response.
8253 interceptor()->set_intercept_final_response(true);
8254 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8255 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8256 default_network_delegate()->set_can_be_intercepted_on_error(true);
8257
tommycli59a63432015-11-06 00:10:558258 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508259
8260 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368261 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558262 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:368263 &d));
bengr1bf8e942014-11-07 01:36:508264 req->set_method("GET");
8265 req->Start();
8266 base::RunLoop().Run();
8267
8268 EXPECT_TRUE(interceptor()->did_intercept_final());
8269
8270 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508271 int status = d.request_status();
8272 EXPECT_EQ(OK, status);
8273 if (status == OK)
bengr1bf8e942014-11-07 01:36:508274 EXPECT_EQ(200, req->response_headers()->response_code());
8275 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8276 EXPECT_EQ(1, d.response_started_count());
8277 EXPECT_EQ(0, d.received_redirect_count());
8278
8279 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008280 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508281 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
8282}
8283
8284TEST_F(URLRequestInterceptorTestHTTP,
8285 NetworkDelegateNotificationOnResponseIntercept) {
8286 // Intercept that error and respond with an OK response.
8287 interceptor()->set_intercept_final_response(true);
8288
8289 // Intercept with a real URLRequestHttpJob.
8290 interceptor()->set_use_url_request_http_job(true);
8291
tommycli59a63432015-11-06 00:10:558292 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508293
8294 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368295 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558296 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508297 req->set_method("GET");
8298 req->Start();
8299 base::RunLoop().Run();
8300
8301 EXPECT_TRUE(interceptor()->did_intercept_final());
8302
8303 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:508304 int status = d.request_status();
8305 EXPECT_EQ(OK, status);
8306 if (status == OK)
bengr1bf8e942014-11-07 01:36:508307 EXPECT_EQ(200, req->response_headers()->response_code());
8308 EXPECT_EQ("hello", d.data_received());
8309 EXPECT_EQ(1, d.response_started_count());
8310 EXPECT_EQ(0, d.received_redirect_count());
8311
8312 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008313 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508314 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
8315}
8316
mkwst0c5eab872014-11-21 14:18:548317class URLRequestTestReferrerPolicy : public URLRequestTest {
8318 public:
8319 URLRequestTestReferrerPolicy() {}
8320
tommycli59a63432015-11-06 00:10:558321 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
8322 origin_server_.reset(new EmbeddedTestServer(type));
8323 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
8324 origin_server_->AddDefaultHandlers(
8325 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8326 } else {
8327 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8328 }
mkwst0c5eab872014-11-21 14:18:548329 ASSERT_TRUE(origin_server_->Start());
8330 }
8331
tommycli59a63432015-11-06 00:10:558332 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8333 net::EmbeddedTestServer::Type dest_type) {
8334 origin_server_.reset(new EmbeddedTestServer(origin_type));
8335 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8336 origin_server_->AddDefaultHandlers(
8337 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8338 } else {
8339 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8340 }
mkwst0c5eab872014-11-21 14:18:548341 ASSERT_TRUE(origin_server_->Start());
8342
tommycli59a63432015-11-06 00:10:558343 destination_server_.reset(new EmbeddedTestServer(dest_type));
8344 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8345 destination_server_->AddDefaultHandlers(
8346 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8347 } else {
8348 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8349 }
mkwst0c5eab872014-11-21 14:18:548350 ASSERT_TRUE(destination_server_->Start());
8351 }
8352
8353 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8354 const GURL& referrer,
8355 const GURL& expected) {
8356 // Create and execute the request: we'll only have a |destination_server_|
8357 // if the origins are meant to be distinct. Otherwise, we'll use the
8358 // |origin_server_| for both endpoints.
8359 GURL destination_url =
tommycli59a63432015-11-06 00:10:558360 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8361 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548362 GURL origin_url =
tommycli59a63432015-11-06 00:10:558363 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548364
8365 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368366 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368367 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548368 req->set_referrer_policy(policy);
8369 req->SetReferrer(referrer.spec());
8370 req->Start();
8371 base::RunLoop().Run();
8372
8373 EXPECT_EQ(1, d.response_started_count());
8374 EXPECT_EQ(1, d.received_redirect_count());
8375 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:508376 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:548377 EXPECT_EQ(200, req->response_headers()->response_code());
8378
8379 EXPECT_EQ(expected.spec(), req->referrer());
8380 if (expected.is_empty())
8381 EXPECT_EQ("None", d.data_received());
8382 else
8383 EXPECT_EQ(expected.spec(), d.data_received());
8384 }
8385
tommycli59a63432015-11-06 00:10:558386 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548387
8388 private:
danakj8522a25b2016-04-16 00:17:368389 std::unique_ptr<EmbeddedTestServer> origin_server_;
8390 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548391};
8392
8393TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558394 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548395
8396 VerifyReferrerAfterRedirect(
8397 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558398 origin_server()->GetURL("/path/to/file.html"),
8399 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548400
8401 VerifyReferrerAfterRedirect(
8402 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558403 origin_server()->GetURL("/path/to/file.html"),
8404 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548405
8406 VerifyReferrerAfterRedirect(
8407 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558408 origin_server()->GetURL("/path/to/file.html"),
8409 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548410
8411 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558412 origin_server()->GetURL("/path/to/file.html"),
8413 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548414}
8415
tommycli59a63432015-11-06 00:10:558416TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8417 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8418 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548419
8420 VerifyReferrerAfterRedirect(
8421 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558422 origin_server()->GetURL("/path/to/file.html"),
8423 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548424
8425 VerifyReferrerAfterRedirect(
8426 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558427 origin_server()->GetURL("/path/to/file.html"),
8428 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548429
8430 VerifyReferrerAfterRedirect(
8431 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558432 origin_server()->GetURL("/path/to/file.html"),
8433 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548434
8435 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558436 origin_server()->GetURL("/path/to/file.html"),
8437 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548438}
8439
8440TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558441 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548442
8443 VerifyReferrerAfterRedirect(
8444 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558445 origin_server()->GetURL("/path/to/file.html"),
8446 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548447
8448 VerifyReferrerAfterRedirect(
8449 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558450 origin_server()->GetURL("/path/to/file.html"),
8451 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548452
8453 VerifyReferrerAfterRedirect(
8454 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558455 origin_server()->GetURL("/path/to/file.html"),
8456 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548457
8458 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558459 origin_server()->GetURL("/path/to/file.html"),
8460 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548461}
8462
tommycli59a63432015-11-06 00:10:558463TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8464 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8465 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548466
8467 VerifyReferrerAfterRedirect(
8468 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558469 origin_server()->GetURL("/path/to/file.html"),
8470 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548471
8472 VerifyReferrerAfterRedirect(
8473 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558474 origin_server()->GetURL("/path/to/file.html"),
8475 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548476
8477 VerifyReferrerAfterRedirect(
8478 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558479 origin_server()->GetURL("/path/to/file.html"),
8480 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548481
8482 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558483 origin_server()->GetURL("/path/to/file.html"),
8484 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548485}
8486
tommycli59a63432015-11-06 00:10:558487TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8488 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8489 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548490
8491 VerifyReferrerAfterRedirect(
8492 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558493 origin_server()->GetURL("/path/to/file.html"),
8494 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548495
8496 VerifyReferrerAfterRedirect(
8497 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558498 origin_server()->GetURL("/path/to/file.html"),
8499 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548500
8501 VerifyReferrerAfterRedirect(
8502 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558503 origin_server()->GetURL("/path/to/file.html"),
8504 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548505
8506 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558507 origin_server()->GetURL("/path/to/file.html"),
8508 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548509}
8510
tommycli59a63432015-11-06 00:10:558511TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8512 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8513 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548514
8515 VerifyReferrerAfterRedirect(
8516 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558517 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548518
8519 VerifyReferrerAfterRedirect(
8520 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558521 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548522
8523 VerifyReferrerAfterRedirect(
8524 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558525 origin_server()->GetURL("/path/to/file.html"),
8526 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548527
8528 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
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
[email protected]73e0bba2009-02-19 22:57:098533class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508534 public:
[email protected]ef2bf422012-05-11 03:27:098535 HTTPSRequestTest() : default_context_(true) {
8536 default_context_.set_network_delegate(&default_network_delegate_);
8537 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508538 }
dcheng67be2b1f2014-10-27 21:47:298539 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508540
8541 protected:
[email protected]ceefd7fd2012-11-29 00:36:248542 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098543 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468544};
8545
[email protected]c044616e2013-02-20 02:01:268546TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558547 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8548 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228549 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118550 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468551
[email protected]ea224582008-12-07 20:25:468552 TestDelegate d;
8553 {
danakj8522a25b2016-04-16 00:17:368554 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558555 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198556 r->Start();
8557 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468558
[email protected]255620da2013-08-19 13:14:298559 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468560
8561 EXPECT_EQ(1, d.response_started_count());
8562 EXPECT_FALSE(d.received_data_before_response());
8563 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198564 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198565 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198566 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198567 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198568 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468569 }
[email protected]ea224582008-12-07 20:25:468570}
8571
[email protected]5774ada2010-07-15 06:30:548572TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558573 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8574 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8575 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228576 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118577 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338578
8579 bool err_allowed = true;
8580 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8581 TestDelegate d;
8582 {
8583 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368584 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558585 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338586
[email protected]f7022f32014-08-21 16:32:198587 r->Start();
8588 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338589
[email protected]255620da2013-08-19 13:14:298590 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338591
8592 EXPECT_EQ(1, d.response_started_count());
8593 EXPECT_FALSE(d.received_data_before_response());
8594 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178595 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338596 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198597 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178598 } else {
[email protected]bacff652009-03-31 17:50:338599 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178600 }
[email protected]bacff652009-03-31 17:50:338601 }
8602 }
8603}
8604
[email protected]5774ada2010-07-15 06:30:548605TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558606 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8607 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8608 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228609 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118610 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338611
8612 // Iterate from false to true, just so that we do the opposite of the
8613 // previous test in order to increase test coverage.
8614 bool err_allowed = false;
8615 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8616 TestDelegate d;
8617 {
8618 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368619 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558620 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338621
[email protected]f7022f32014-08-21 16:32:198622 r->Start();
8623 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338624
[email protected]255620da2013-08-19 13:14:298625 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338626
8627 EXPECT_EQ(1, d.response_started_count());
8628 EXPECT_FALSE(d.received_data_before_response());
8629 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178630 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338631 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198632 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178633 } else {
[email protected]bacff652009-03-31 17:50:338634 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178635 }
[email protected]bacff652009-03-31 17:50:338636 }
8637 }
8638}
[email protected]73e0bba2009-02-19 22:57:098639
tommycli59a63432015-11-06 00:10:558640// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8641// security state. (see http://crbug.com/550977).
8642#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448643// This tests that a load of www.google.com with a certificate error sets
8644// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8645// the interstitial to be fatal.
8646TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558647 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8648 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8649 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448650 ASSERT_TRUE(test_server.Start());
8651
8652 // We require that the URL be www.google.com in order to pick up the
8653 // preloaded HSTS entries in the TransportSecurityState. This means that we
8654 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248655 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448656
8657 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248658 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448659 TestURLRequestContext context(true);
8660 context.set_network_delegate(&network_delegate);
8661 context.set_host_resolver(&host_resolver);
8662 TransportSecurityState transport_security_state;
8663 context.set_transport_security_state(&transport_security_state);
8664 context.Init();
8665
8666 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368667 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198668 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368669 test_server.host_port_pair().port())),
8670 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448671
[email protected]f7022f32014-08-21 16:32:198672 r->Start();
8673 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448674
[email protected]255620da2013-08-19 13:14:298675 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448676
8677 EXPECT_EQ(1, d.response_started_count());
8678 EXPECT_FALSE(d.received_data_before_response());
8679 EXPECT_TRUE(d.have_certificate_errors());
8680 EXPECT_TRUE(d.certificate_errors_are_fatal());
8681}
8682
8683// This tests that cached HTTPS page loads do not cause any updates to the
8684// TransportSecurityState.
8685TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8686 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8687 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558688 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8689 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8690 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448691 ASSERT_TRUE(test_server.Start());
8692
[email protected]9e6968d2014-05-07 21:46:268693 // We require that the URL be www.google.com in order to pick up the static
8694 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8695 // that we have to use a MockHostResolver in order to direct www.google.com to
8696 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448697
8698 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248699 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448700 TestURLRequestContext context(true);
8701 context.set_network_delegate(&network_delegate);
8702 context.set_host_resolver(&host_resolver);
8703 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268704
martijnc0d6b622015-06-30 19:14:408705 TransportSecurityState::STSState static_sts_state;
8706 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268707 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408708 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448709 context.set_transport_security_state(&transport_security_state);
8710 context.Init();
8711
martijnc0d6b622015-06-30 19:14:408712 TransportSecurityState::STSState dynamic_sts_state;
8713 TransportSecurityState::PKPState dynamic_pkp_state;
8714 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8715 &dynamic_sts_state));
8716 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8717 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268718
[email protected]316c1e5e2012-09-12 15:17:448719 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368720 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198721 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368722 test_server.host_port_pair().port())),
8723 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448724
[email protected]f7022f32014-08-21 16:32:198725 r->Start();
8726 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448727
[email protected]255620da2013-08-19 13:14:298728 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448729
8730 EXPECT_EQ(1, d.response_started_count());
8731 EXPECT_FALSE(d.received_data_before_response());
8732 EXPECT_TRUE(d.have_certificate_errors());
8733 EXPECT_TRUE(d.certificate_errors_are_fatal());
8734
[email protected]9e6968d2014-05-07 21:46:268735 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408736 TransportSecurityState::STSState new_static_sts_state;
8737 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268738 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408739 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8740 TransportSecurityState::STSState new_dynamic_sts_state;
8741 TransportSecurityState::PKPState new_dynamic_pkp_state;
8742 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8743 "www.google.com", &new_dynamic_sts_state));
8744 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8745 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268746
martijnc0d6b622015-06-30 19:14:408747 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8748 EXPECT_EQ(new_static_sts_state.include_subdomains,
8749 static_sts_state.include_subdomains);
8750 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8751 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488752 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8753 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8754 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448755}
8756
[email protected]8ccc69f2012-11-28 19:52:148757// Make sure HSTS preserves a POST request's method and body.
8758TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8759 static const char kData[] = "hello world";
8760
tommycli59a63432015-11-06 00:10:558761 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8762 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228763 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148764 ASSERT_TRUE(test_server.Start());
8765
8766
8767 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8768 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558769 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228770 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148771 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148772
8773 // Force https for www.somewhere.com.
8774 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208775 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8776 bool include_subdomains = false;
8777 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8778 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148779
8780 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8781
8782 TestURLRequestContext context(true);
8783 context.set_host_resolver(&host_resolver);
8784 context.set_transport_security_state(&transport_security_state);
8785 context.set_network_delegate(&network_delegate);
8786 context.Init();
8787
8788 TestDelegate d;
8789 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8790 // cause a certificate error. Ignore the error.
8791 d.set_allow_certificate_errors(true);
8792
danakj8522a25b2016-04-16 00:17:368793 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198794 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368795 test_server.host_port_pair().port())),
8796 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198797 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078798 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148799
[email protected]f7022f32014-08-21 16:32:198800 req->Start();
[email protected]255620da2013-08-19 13:14:298801 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148802
[email protected]f7022f32014-08-21 16:32:198803 EXPECT_EQ("https", req->url().scheme());
8804 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148805 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408806
8807 LoadTimingInfo load_timing_info;
8808 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8809 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8810 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148811}
8812
rob4e0be1f2014-09-11 23:40:228813// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8814TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8815 static const char kOriginHeaderValue[] = "http://www.example.com";
8816
tommycli59a63432015-11-06 00:10:558817 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8818 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228819 ASSERT_TRUE(test_server.Start());
8820
8821 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8822 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558823 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8824 // default.
rob4e0be1f2014-09-11 23:40:228825 MockHostResolver host_resolver;
8826
8827 TransportSecurityState transport_security_state;
8828 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8829 bool include_subdomains = false;
8830 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8831
8832 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8833
8834 MockCertVerifier cert_verifier;
8835 cert_verifier.set_default_result(OK);
8836
8837 TestURLRequestContext context(true);
8838 context.set_host_resolver(&host_resolver);
8839 context.set_transport_security_state(&transport_security_state);
8840 context.set_network_delegate(&network_delegate);
8841 context.set_cert_verifier(&cert_verifier);
8842 context.Init();
8843
8844 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8845 test_server.host_port_pair().port()));
8846 url::Replacements<char> replacements;
8847 const char kNewScheme[] = "https";
8848 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8849 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8850
8851 TestDelegate d;
8852 // Quit on redirect to allow response header inspection upon redirect.
8853 d.set_quit_on_redirect(true);
8854
danakj8522a25b2016-04-16 00:17:368855 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368856 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228857 // Set Origin header to simulate a cross-origin request.
8858 HttpRequestHeaders request_headers;
8859 request_headers.SetHeader("Origin", kOriginHeaderValue);
8860 req->SetExtraRequestHeaders(request_headers);
8861
8862 req->Start();
8863 base::RunLoop().Run();
8864
8865 EXPECT_EQ(1, d.received_redirect_count());
8866
8867 const HttpResponseHeaders* headers = req->response_headers();
8868 std::string redirect_location;
8869 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8870 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8871
8872 std::string received_cors_header;
8873 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8874 &received_cors_header));
8875 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8876}
8877
davidbenb4c25b62016-06-24 02:39:278878// Test that DHE-only servers fail with the expected dedicated error code.
8879TEST_F(HTTPSRequestTest, DHE) {
8880 SpawnedTestServer::SSLOptions ssl_options;
8881 ssl_options.key_exchanges =
8882 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
8883 SpawnedTestServer test_server(
8884 SpawnedTestServer::TYPE_HTTPS, ssl_options,
8885 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8886 ASSERT_TRUE(test_server.Start());
8887
8888 TestDelegate d;
8889 {
8890 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8891 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
8892
8893 r->Start();
8894 EXPECT_TRUE(r->is_pending());
8895
8896 base::RunLoop().Run();
8897
8898 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508899 EXPECT_EQ(ERR_SSL_OBSOLETE_CIPHER, d.request_status());
davidbenb4c25b62016-06-24 02:39:278900 }
8901}
8902
[email protected]316c1e5e2012-09-12 15:17:448903namespace {
8904
8905class SSLClientAuthTestDelegate : public TestDelegate {
8906 public:
8907 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8908 }
dchengb03027d2014-10-21 12:00:208909 void OnCertificateRequested(URLRequest* request,
8910 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448911 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178912 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448913 }
8914 int on_certificate_requested_count() {
8915 return on_certificate_requested_count_;
8916 }
8917 private:
8918 int on_certificate_requested_count_;
8919};
8920
8921} // namespace
8922
8923// TODO(davidben): Test the rest of the code. Specifically,
8924// - Filtering which certificates to select.
8925// - Sending a certificate back.
8926// - Getting a certificate request in an SSL renegotiation sending the
8927// HTTP request.
8928TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558929 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8930 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128931 ssl_config.client_cert_type =
8932 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558933 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8934 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228935 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448936 ASSERT_TRUE(test_server.Start());
8937
8938 SSLClientAuthTestDelegate d;
8939 {
danakj8522a25b2016-04-16 00:17:368940 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558941 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448942
[email protected]f7022f32014-08-21 16:32:198943 r->Start();
8944 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448945
[email protected]255620da2013-08-19 13:14:298946 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448947
8948 EXPECT_EQ(1, d.on_certificate_requested_count());
8949 EXPECT_FALSE(d.received_data_before_response());
8950 EXPECT_EQ(0, d.bytes_received());
8951
8952 // Send no certificate.
8953 // TODO(davidben): Get temporary client cert import (with keys) working on
8954 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548955 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448956
[email protected]255620da2013-08-19 13:14:298957 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448958
8959 EXPECT_EQ(1, d.response_started_count());
8960 EXPECT_FALSE(d.received_data_before_response());
8961 EXPECT_NE(0, d.bytes_received());
8962 }
8963}
8964
8965TEST_F(HTTPSRequestTest, ResumeTest) {
8966 // Test that we attempt a session resume when making two connections to the
8967 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228968 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448969 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228970 SpawnedTestServer test_server(
8971 SpawnedTestServer::TYPE_HTTPS,
8972 ssl_options,
8973 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448974 ASSERT_TRUE(test_server.Start());
8975
8976 SSLClientSocket::ClearSessionCache();
8977
8978 {
8979 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368980 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368981 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448982
[email protected]f7022f32014-08-21 16:32:198983 r->Start();
8984 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448985
[email protected]255620da2013-08-19 13:14:298986 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448987
8988 EXPECT_EQ(1, d.response_started_count());
8989 }
8990
8991 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8992 CloseAllConnections();
8993
8994 {
8995 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368996 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368997 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448998
[email protected]f7022f32014-08-21 16:32:198999 r->Start();
9000 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449001
[email protected]255620da2013-08-19 13:14:299002 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449003
9004 // The response will look like;
9005 // insert abc
9006 // lookup abc
9007 // insert xyz
9008 //
9009 // With a newline at the end which makes the split think that there are
9010 // four lines.
9011
9012 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:299013 std::vector<std::string> lines = base::SplitString(
9014 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449015 ASSERT_EQ(4u, lines.size()) << d.data_received();
9016
9017 std::string session_id;
9018
9019 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299020 std::vector<std::string> parts = base::SplitString(
9021 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:449022 ASSERT_EQ(2u, parts.size());
9023 if (i == 0) {
9024 EXPECT_EQ("insert", parts[0]);
9025 session_id = parts[1];
9026 } else {
9027 EXPECT_EQ("lookup", parts[0]);
9028 EXPECT_EQ(session_id, parts[1]);
9029 }
9030 }
9031 }
9032}
9033
Adam Langley32352ad2014-10-14 22:31:009034// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
9035// the result of fetching "ssl-session-cache" from the test server, indicates
9036// that exactly two different sessions were inserted, with no lookups etc.
9037static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:299038 std::vector<std::string> lines = base::SplitString(
9039 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009040 ASSERT_EQ(3u, lines.size()) << session_info;
9041
9042 std::string session_id;
9043 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:299044 std::vector<std::string> parts = base::SplitString(
9045 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:009046 ASSERT_EQ(2u, parts.size());
9047 EXPECT_EQ("insert", parts[0]);
9048 if (i == 0) {
9049 session_id = parts[1];
9050 } else {
9051 EXPECT_NE(session_id, parts[1]);
9052 }
9053 }
9054}
9055
[email protected]316c1e5e2012-09-12 15:17:449056TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
9057 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
9058 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:229059 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:449060 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:229061 SpawnedTestServer test_server(
9062 SpawnedTestServer::TYPE_HTTPS,
9063 ssl_options,
9064 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:449065 ASSERT_TRUE(test_server.Start());
9066
9067 SSLClientSocket::ClearSessionCache();
9068
9069 {
9070 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369071 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369072 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449073
[email protected]f7022f32014-08-21 16:32:199074 r->Start();
9075 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449076
[email protected]255620da2013-08-19 13:14:299077 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449078
9079 EXPECT_EQ(1, d.response_started_count());
9080 }
9081
9082 // Now create a new HttpCache with a different ssl_session_cache_shard value.
9083 HttpNetworkSession::Params params;
9084 params.host_resolver = default_context_.host_resolver();
9085 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:119086 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:209087 params.cert_transparency_verifier =
9088 default_context_.cert_transparency_verifier();
9089 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:449090 params.proxy_service = default_context_.proxy_service();
9091 params.ssl_config_service = default_context_.ssl_config_service();
9092 params.http_auth_handler_factory =
9093 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:449094 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:449095
mmenkee65e7af2015-10-13 17:16:429096 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:369097 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:429098 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:449099
9100 default_context_.set_http_transaction_factory(cache.get());
9101
9102 {
9103 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369104 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369105 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:449106
[email protected]f7022f32014-08-21 16:32:199107 r->Start();
9108 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:449109
[email protected]255620da2013-08-19 13:14:299110 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:449111
9112 // The response will look like;
9113 // insert abc
9114 // insert xyz
9115 //
9116 // With a newline at the end which makes the split think that there are
9117 // three lines.
9118
9119 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009120 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:449121 }
9122}
9123
[email protected]48d2b7c52014-06-27 01:16:559124class HTTPSFallbackTest : public testing::Test {
9125 public:
Adam Langley32352ad2014-10-14 22:31:009126 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:299127 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:559128
9129 protected:
9130 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
9131 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:009132 context_.Init();
9133 delegate_.set_allow_certificate_errors(true);
9134
[email protected]48d2b7c52014-06-27 01:16:559135 SpawnedTestServer test_server(
9136 SpawnedTestServer::TYPE_HTTPS,
9137 ssl_options,
9138 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9139 ASSERT_TRUE(test_server.Start());
9140
tommycli59a63432015-11-06 00:10:559141 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
9142 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:559143 request_->Start();
9144
9145 base::RunLoop().Run();
9146 }
9147
[email protected]48d2b7c52014-06-27 01:16:559148 void ExpectFailure(int error) {
9149 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:509150 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:559151 }
9152
9153 private:
9154 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:479155 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369156 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:559157};
9158
davidbenb127ca82015-06-15 19:05:429159// Tests the TLS 1.0 fallback doesn't happen.
9160TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:559161 SpawnedTestServer::SSLOptions ssl_options(
9162 SpawnedTestServer::SSLOptions::CERT_OK);
9163 ssl_options.tls_intolerant =
9164 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
9165
9166 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:559167 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:429168}
9169
davidben5a312152016-06-27 22:11:479170// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:559171TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:429172 SpawnedTestServer::SSLOptions ssl_options(
9173 SpawnedTestServer::SSLOptions::CERT_OK);
9174 ssl_options.tls_intolerant =
9175 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
9176
9177 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:559178 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
9179}
9180
[email protected]a8fed1742013-12-27 02:14:249181class HTTPSSessionTest : public testing::Test {
9182 public:
9183 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:599184 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249185
9186 default_context_.set_network_delegate(&default_network_delegate_);
9187 default_context_.set_cert_verifier(&cert_verifier_);
9188 default_context_.Init();
9189 }
dcheng67be2b1f2014-10-27 21:47:299190 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:249191
9192 protected:
9193 MockCertVerifier cert_verifier_;
9194 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
9195 TestURLRequestContext default_context_;
9196};
9197
9198// Tests that session resumption is not attempted if an invalid certificate
9199// is presented.
9200TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
9201 SpawnedTestServer::SSLOptions ssl_options;
9202 ssl_options.record_resume = true;
9203 SpawnedTestServer test_server(
9204 SpawnedTestServer::TYPE_HTTPS,
9205 ssl_options,
9206 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9207 ASSERT_TRUE(test_server.Start());
9208
9209 SSLClientSocket::ClearSessionCache();
9210
9211 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:599212 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:249213 {
9214 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369215 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369216 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249217
[email protected]f7022f32014-08-21 16:32:199218 r->Start();
9219 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249220
9221 base::RunLoop().Run();
9222
9223 EXPECT_EQ(1, d.response_started_count());
9224 }
9225
9226 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9227 CloseAllConnections();
9228
9229 // Now change the certificate to be acceptable (so that the response is
9230 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:599231 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249232 {
9233 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369234 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369235 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249236
[email protected]f7022f32014-08-21 16:32:199237 r->Start();
9238 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249239
9240 base::RunLoop().Run();
9241
9242 // The response will look like;
9243 // insert abc
9244 // insert xyz
9245 //
9246 // With a newline at the end which makes the split think that there are
9247 // three lines.
9248 //
9249 // If a session was presented (eg: a bug), then the response would look
9250 // like;
9251 // insert abc
9252 // lookup abc
9253 // insert xyz
9254
9255 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009256 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:249257 }
9258}
9259
[email protected]dffe8242012-03-20 15:14:279260// This the fingerprint of the "Testing CA" certificate used by the testserver.
9261// See net/data/ssl/certificates/ocsp-test-root.pem.
mattm3b4376f12016-10-03 21:07:159262static const SHA1HashValue kOCSPTestCertFingerprint = {{
mattm0b12a6f2016-11-29 19:57:169263 0x80, 0x37, 0xe7, 0xee, 0x12, 0x19, 0xeb, 0x10, 0x79, 0x36,
9264 0x00, 0x48, 0x57, 0x5a, 0xa6, 0x1e, 0x2b, 0x24, 0x1a, 0xd7,
mattm3b4376f12016-10-03 21:07:159265}};
[email protected]dffe8242012-03-20 15:14:279266
[email protected]51523f52013-07-31 21:57:289267// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
9268// testserver.
mattm0b12a6f2016-11-29 19:57:169269static const SHA256HashValue kOCSPTestCertSPKI = {{
9270 0x05, 0xa8, 0xf6, 0xfd, 0x8e, 0x10, 0xfe, 0x92, 0x2f, 0x22, 0x75,
9271 0x46, 0x40, 0xf4, 0xc4, 0x57, 0x06, 0x0d, 0x95, 0xfd, 0x60, 0x31,
9272 0x3b, 0xf3, 0xfc, 0x12, 0x47, 0xe7, 0x66, 0x1a, 0x82, 0xa3,
9273}};
[email protected]51523f52013-07-31 21:57:289274
[email protected]dffe8242012-03-20 15:14:279275// This is the policy OID contained in the certificates that testserver
9276// generates.
9277static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
9278
9279class HTTPSOCSPTest : public HTTPSRequestTest {
9280 public:
9281 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:099282 : context_(true),
[email protected]b6f2de32012-08-17 04:35:089283 ev_test_policy_(
9284 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
9285 kOCSPTestCertFingerprint,
9286 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:029287 }
9288
dcheng67be2b1f2014-10-27 21:47:299289 void SetUp() override {
rsleevid6de8302016-06-21 01:33:209290 context_.SetCTPolicyEnforcer(
9291 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
9292 SetupContext();
[email protected]ef2bf422012-05-11 03:27:099293 context_.Init();
[email protected]dffe8242012-03-20 15:14:279294
[email protected]cba24642014-08-15 20:49:599295 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:209296 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:429297 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:509298 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:279299
svaldez2135be52016-04-20 16:34:539300#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:099301 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:279302 EnsureNSSHttpIOInit();
9303#endif
9304 }
9305
dadrian612337a2016-07-20 22:36:589306 void DoConnectionWithDelegate(
9307 const SpawnedTestServer::SSLOptions& ssl_options,
9308 TestDelegate* delegate,
9309 SSLInfo* out_ssl_info) {
9310 // Always overwrite |out_ssl_info|.
9311 out_ssl_info->Reset();
9312
[email protected]ce7d0cbc2013-05-03 18:57:229313 SpawnedTestServer test_server(
9314 SpawnedTestServer::TYPE_HTTPS,
9315 ssl_options,
9316 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:279317 ASSERT_TRUE(test_server.Start());
9318
dadrian612337a2016-07-20 22:36:589319 delegate->set_allow_certificate_errors(true);
9320 std::unique_ptr<URLRequest> r(context_.CreateRequest(
9321 test_server.GetURL("/"), DEFAULT_PRIORITY, delegate));
[email protected]f7022f32014-08-21 16:32:199322 r->Start();
[email protected]dffe8242012-03-20 15:14:279323
[email protected]255620da2013-08-19 13:14:299324 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:589325 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:279326
dadrian612337a2016-07-20 22:36:589327 *out_ssl_info = r->ssl_info();
9328 }
9329
9330 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
9331 CertStatus* out_cert_status) {
9332 // Always overwrite |out_cert_status|.
9333 *out_cert_status = 0;
9334
9335 TestDelegate d;
9336 SSLInfo ssl_info;
9337 ASSERT_NO_FATAL_FAILURE(
9338 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
9339
9340 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:279341 }
9342
dcheng67be2b1f2014-10-27 21:47:299343 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:539344#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:279345 ShutdownNSSHttpIO();
9346#endif
9347 }
9348
[email protected]a13234c2012-03-20 21:45:029349 protected:
rsleevid6de8302016-06-21 01:33:209350 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9351 public:
9352 AllowAnyCertCTPolicyEnforcer() = default;
9353 ~AllowAnyCertCTPolicyEnforcer() override = default;
9354
9355 ct::CertPolicyCompliance DoesConformToCertPolicy(
9356 X509Certificate* cert,
9357 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209358 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209359 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9360 }
9361
9362 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9363 X509Certificate* cert,
9364 const ct::EVCertsWhitelist* ev_whitelist,
9365 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209366 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209367 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9368 }
9369 };
[email protected]a13234c2012-03-20 21:45:029370 // SetupContext configures the URLRequestContext that will be used for making
9371 // connetions to testserver. This can be overridden in test subclasses for
9372 // different behaviour.
rsleevid6de8302016-06-21 01:33:209373 virtual void SetupContext() {
9374 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149375 true /* check for EV */, true /* online revocation checking */,
9376 false /* require rev. checking for local
9377 anchors */,
9378 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029379 }
9380
danakj8522a25b2016-04-16 00:17:369381 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099382 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369383 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279384};
9385
[email protected]a13234c2012-03-20 21:45:029386static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:209387#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:029388 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9389 // have that ability on other platforms.
9390 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9391#else
9392 return 0;
9393#endif
9394}
9395
[email protected]3a86a712013-07-30 07:16:209396// SystemSupportsHardFailRevocationChecking returns true iff the current
9397// operating system supports revocation checking and can distinguish between
9398// situations where a given certificate lacks any revocation information (eg:
9399// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9400// revocation information cannot be obtained (eg: the CRL was unreachable).
9401// If it does not, then tests which rely on 'hard fail' behaviour should be
9402// skipped.
9403static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539404#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209405 return true;
9406#else
9407 return false;
9408#endif
9409}
9410
[email protected]a13234c2012-03-20 21:45:029411// SystemUsesChromiumEVMetadata returns true iff the current operating system
9412// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9413// several tests are effected because our testing EV certificate won't be
9414// recognised as EV.
9415static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329416#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579417 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9418 return false;
mattm1a282f52016-11-10 21:49:429419#elif defined(OS_ANDROID)
9420 // On Android, we use the system to tell us whether a certificate is EV or not
9421 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019422 return false;
9423#else
9424 return true;
9425#endif
9426}
9427
mattmaf868e72016-09-23 23:25:209428// Returns the expected CertStatus for tests that expect an online revocation
9429// check failure as a result of checking a test EV cert, which will not
9430// actually trigger an online revocation check on some platforms.
9431static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
9432 if (SystemUsesChromiumEVMetadata()) {
9433 return ExpectedCertStatusForFailedOnlineRevocationCheck();
9434 } else {
9435 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
9436 // be enabled, and thus there will not be a revocation check to fail.
9437 return 0u;
9438 }
9439}
9440
[email protected]b6f2de32012-08-17 04:35:089441static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339442#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029443 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9444 return false;
9445#else
9446 return true;
9447#endif
9448}
9449
davidbend1fb2f12014-11-08 02:51:009450static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339451#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039452 return true;
mathpc992e602015-10-21 20:34:039453#else
9454 return false;
9455#endif
davidbend1fb2f12014-11-08 02:51:009456}
9457
[email protected]dffe8242012-03-20 15:14:279458TEST_F(HTTPSOCSPTest, Valid) {
9459 if (!SystemSupportsOCSP()) {
9460 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9461 return;
9462 }
9463
[email protected]ce7d0cbc2013-05-03 18:57:229464 SpawnedTestServer::SSLOptions ssl_options(
9465 SpawnedTestServer::SSLOptions::CERT_AUTO);
9466 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279467
[email protected]924e9f92012-12-16 22:00:539468 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129469 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279470
9471 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9472
[email protected]a13234c2012-03-20 21:45:029473 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9474 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279475
9476 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9477}
9478
9479TEST_F(HTTPSOCSPTest, Revoked) {
9480 if (!SystemSupportsOCSP()) {
9481 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9482 return;
9483 }
9484
[email protected]ce7d0cbc2013-05-03 18:57:229485 SpawnedTestServer::SSLOptions ssl_options(
9486 SpawnedTestServer::SSLOptions::CERT_AUTO);
9487 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279488
9489 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129490 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279491
[email protected]dffe8242012-03-20 15:14:279492 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279493 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9494 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9495}
9496
9497TEST_F(HTTPSOCSPTest, Invalid) {
9498 if (!SystemSupportsOCSP()) {
9499 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9500 return;
9501 }
9502
[email protected]ce7d0cbc2013-05-03 18:57:229503 SpawnedTestServer::SSLOptions ssl_options(
9504 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589505 ssl_options.ocsp_status =
9506 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:279507
[email protected]924e9f92012-12-16 22:00:539508 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129509 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279510
[email protected]a13234c2012-03-20 21:45:029511 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279512 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279513
9514 // Without a positive OCSP response, we shouldn't show the EV status.
9515 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9516 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9517}
[email protected]a13234c2012-03-20 21:45:029518
davidbend1fb2f12014-11-08 02:51:009519TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039520 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009521 LOG(WARNING)
9522 << "Skipping test because system doesn't support OCSP stapling";
9523 return;
9524 }
9525
9526 SpawnedTestServer::SSLOptions ssl_options(
9527 SpawnedTestServer::SSLOptions::CERT_AUTO);
9528 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9529 ssl_options.staple_ocsp_response = true;
9530 ssl_options.ocsp_server_unavailable = true;
9531
9532 CertStatus cert_status;
9533 DoConnection(ssl_options, &cert_status);
9534
9535 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9536
9537 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9538 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9539
9540 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9541}
9542
davidben6c3191b2014-11-21 22:38:049543// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489544#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049545#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9546#else
9547#define MAYBE_RevokedStapled RevokedStapled
9548#endif
9549TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039550 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009551 LOG(WARNING)
9552 << "Skipping test because system doesn't support OCSP stapling";
9553 return;
9554 }
9555
9556 SpawnedTestServer::SSLOptions ssl_options(
9557 SpawnedTestServer::SSLOptions::CERT_AUTO);
9558 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9559 ssl_options.staple_ocsp_response = true;
9560 ssl_options.ocsp_server_unavailable = true;
9561
9562 CertStatus cert_status;
9563 DoConnection(ssl_options, &cert_status);
9564
9565 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9566 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9567 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9568}
9569
dadriand476e652016-07-26 21:33:249570TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
9571 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9572 https_test_server.SetSSLConfig(
9573 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9574 https_test_server.ServeFilesFromSourceDirectory(
9575 base::FilePath(kTestFilePath));
9576 ASSERT_TRUE(https_test_server.Start());
9577
9578 // Set up a MockCertVerifier to accept the certificate that the server sends,
9579 // but not provide any OCSP information.
9580 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9581 ASSERT_TRUE(cert);
9582 MockCertVerifier cert_verifier;
9583 CertVerifyResult verify_result;
9584 verify_result.verified_cert = cert;
9585 verify_result.is_issued_by_known_root = true;
9586 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9587 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9588
9589 // Catch the Expect-Staple report.
9590 TransportSecurityState transport_security_state;
9591 MockCertificateReportSender mock_report_sender;
9592 transport_security_state.SetReportSender(&mock_report_sender);
9593
9594 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9595 // that the request can be sent to a site on the Expect-Staple preload list.
9596 MockHostResolver host_resolver;
9597 TestNetworkDelegate network_delegate;
9598 TestURLRequestContext context(true);
9599 context.set_host_resolver(&host_resolver);
9600 context.set_transport_security_state(&transport_security_state);
9601 context.set_network_delegate(&network_delegate);
9602 context.set_cert_verifier(&cert_verifier);
9603 context.Init();
9604
9605 // Now send a request to trigger the violation.
9606 TestDelegate d;
9607 GURL url = https_test_server.GetURL("/");
9608 GURL::Replacements replace_host;
9609 replace_host.SetHostStr(kExpectStapleStaticHostname);
9610 url = url.ReplaceComponents(replace_host);
9611 std::unique_ptr<URLRequest> violating_request(
9612 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9613 violating_request->Start();
9614 base::RunLoop().Run();
9615
9616 // Confirm a report was sent.
9617 EXPECT_FALSE(mock_report_sender.latest_report().empty());
9618 EXPECT_EQ(GURL(kExpectStapleReportURI),
9619 mock_report_sender.latest_report_uri());
9620}
9621
estark13e0b312016-12-22 23:52:329622// Tests that Expect-Staple reports are not sent for connections on which there
9623// is a certificate error.
9624TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnMissingWithCertError) {
9625 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9626 https_test_server.SetSSLConfig(
9627 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9628 https_test_server.ServeFilesFromSourceDirectory(
9629 base::FilePath(kTestFilePath));
9630 ASSERT_TRUE(https_test_server.Start());
9631
9632 // Set up a MockCertVerifier to report an error for the certificate
9633 // and indicate that there was no stapled OCSP response.
9634 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9635 ASSERT_TRUE(cert);
9636 MockCertVerifier cert_verifier;
9637 CertVerifyResult verify_result;
9638 verify_result.cert_status = CERT_STATUS_DATE_INVALID;
9639 verify_result.verified_cert = cert;
9640 verify_result.is_issued_by_known_root = true;
9641 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9642 cert_verifier.AddResultForCert(cert.get(), verify_result,
9643 ERR_CERT_DATE_INVALID);
9644
9645 // Set up a mock report sender so that the test can check that an
9646 // Expect-Staple report is not sent.
9647 TransportSecurityState transport_security_state;
9648 MockCertificateReportSender mock_report_sender;
9649 transport_security_state.SetReportSender(&mock_report_sender);
9650
9651 TestNetworkDelegate network_delegate;
9652 TestURLRequestContext context(true);
9653
9654 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
9655 MockHostResolver host_resolver;
9656 context.set_host_resolver(&host_resolver);
9657
9658 context.set_transport_security_state(&transport_security_state);
9659 context.set_network_delegate(&network_delegate);
9660 context.set_cert_verifier(&cert_verifier);
9661 context.Init();
9662
9663 // Make a connection to |kExpectStapleStaticHostname|. Because the
9664 // |verify_result| used with the |cert_verifier| will indicate a certificate
9665 // error, an Expect-Staple report should not be sent.
9666 TestDelegate d;
9667 GURL url = https_test_server.GetURL("/");
9668 GURL::Replacements replace_host;
9669 replace_host.SetHostStr(kExpectStapleStaticHostname);
9670 url = url.ReplaceComponents(replace_host);
9671 std::unique_ptr<URLRequest> violating_request(
9672 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9673 violating_request->Start();
9674 base::RunLoop().Run();
9675
9676 // Confirm a report was not sent.
9677 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9678 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9679}
9680
dadriand476e652016-07-26 21:33:249681TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
9682 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9683 https_test_server.SetSSLConfig(
9684 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9685 https_test_server.ServeFilesFromSourceDirectory(
9686 base::FilePath(kTestFilePath));
9687 ASSERT_TRUE(https_test_server.Start());
9688
9689 // Set up a MockCertVerifier to accept the certificate that the server sends,
9690 // and provide GOOD revocation status.
9691 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9692 ASSERT_TRUE(cert);
9693 MockCertVerifier cert_verifier;
9694 CertVerifyResult verify_result;
9695 verify_result.verified_cert = cert;
9696 verify_result.is_issued_by_known_root = true;
9697 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
9698 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
9699 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9700
9701 // Catch the Expect-Staple report.
9702 TransportSecurityState transport_security_state;
9703 MockCertificateReportSender mock_report_sender;
9704 transport_security_state.SetReportSender(&mock_report_sender);
9705
9706 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9707 // that the request can be sent to a site on the Expect-Staple preload list.
9708 MockHostResolver host_resolver;
9709 TestNetworkDelegate network_delegate;
9710 TestURLRequestContext context(true);
9711 context.set_host_resolver(&host_resolver);
9712 context.set_transport_security_state(&transport_security_state);
9713 context.set_network_delegate(&network_delegate);
9714 context.set_cert_verifier(&cert_verifier);
9715 context.Init();
9716
9717 // This request should not not trigger an Expect-Staple violation.
9718 TestDelegate d;
9719 GURL url = https_test_server.GetURL("/");
9720 GURL::Replacements replace_host;
9721 replace_host.SetHostStr(kExpectStapleStaticHostname);
9722 url = url.ReplaceComponents(replace_host);
9723 std::unique_ptr<URLRequest> ok_request(
9724 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9725 ok_request->Start();
9726 base::RunLoop().Run();
9727
9728 // Check that no report was sent.
9729 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9730 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9731}
9732
estark13e0b312016-12-22 23:52:329733// Tests that an Expect-Staple report is not sent when OCSP details are not
9734// checked on the connection.
9735TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnNotChecked) {
9736 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9737 https_test_server.SetSSLConfig(
9738 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9739 https_test_server.ServeFilesFromSourceDirectory(
9740 base::FilePath(kTestFilePath));
9741 ASSERT_TRUE(https_test_server.Start());
9742
9743 // Set up a MockCertVerifier to accept the certificate that the server sends,
9744 // and set |ocsp_result| to indicate that OCSP stapling details were not
9745 // checked on the connection.
9746 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9747 ASSERT_TRUE(cert);
9748 MockCertVerifier cert_verifier;
9749 CertVerifyResult verify_result;
9750 verify_result.verified_cert = cert;
9751 verify_result.is_issued_by_known_root = true;
9752 verify_result.ocsp_result.response_status = OCSPVerifyResult::NOT_CHECKED;
9753 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9754
9755 // Set up a mock report sender so that the test can check that an
9756 // Expect-Staple report is not sent.
9757 TransportSecurityState transport_security_state;
9758 MockCertificateReportSender mock_report_sender;
9759 transport_security_state.SetReportSender(&mock_report_sender);
9760
9761 TestNetworkDelegate network_delegate;
9762 TestURLRequestContext context(true);
9763
9764 // Force |kExpectStapleStaticHostname| to resolve to |https_test_server|.
9765 MockHostResolver host_resolver;
9766 context.set_host_resolver(&host_resolver);
9767
9768 context.set_transport_security_state(&transport_security_state);
9769 context.set_network_delegate(&network_delegate);
9770 context.set_cert_verifier(&cert_verifier);
9771 context.Init();
9772
9773 // Make a connection to |kExpectStapleStaticHostname|. Because the
9774 // |verify_result| used with the |cert_verifier| will indicate that OCSP
9775 // stapling details were not checked on the connection, an Expect-Staple
9776 // report should not be sent.
9777 TestDelegate d;
9778 GURL url = https_test_server.GetURL("/");
9779 GURL::Replacements replace_host;
9780 replace_host.SetHostStr(kExpectStapleStaticHostname);
9781 url = url.ReplaceComponents(replace_host);
9782 std::unique_ptr<URLRequest> ok_request(
9783 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9784 ok_request->Start();
9785 base::RunLoop().Run();
9786
9787 // Check that no report was sent.
9788 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9789 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9790}
9791
dadrian612337a2016-07-20 22:36:589792static const struct OCSPVerifyTestData {
9793 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
9794 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
9795 OCSPVerifyResult::ResponseStatus response_status;
9796 bool has_revocation_status;
9797 OCSPRevocationStatus cert_status;
9798} kOCSPVerifyData[] = {
9799
9800 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9801 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9802 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9803 OCSPVerifyResult::PROVIDED,
9804 true,
9805 OCSPRevocationStatus::GOOD},
9806
9807 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9808 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9809 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9810 OCSPVerifyResult::INVALID_DATE,
9811 false,
9812 OCSPRevocationStatus::UNKNOWN},
9813
9814 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9815 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9816 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9817 OCSPVerifyResult::INVALID_DATE,
9818 false,
9819 OCSPRevocationStatus::UNKNOWN},
9820
9821 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9822 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9823 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9824 OCSPVerifyResult::INVALID_DATE,
9825 false,
9826 OCSPRevocationStatus::UNKNOWN},
9827
9828 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9829 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9830 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9831 OCSPVerifyResult::INVALID_DATE,
9832 false,
9833 OCSPRevocationStatus::UNKNOWN},
9834
9835 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
9836 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9837 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9838 OCSPVerifyResult::ERROR_RESPONSE,
9839 false,
9840 OCSPRevocationStatus::UNKNOWN},
9841
9842 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
9843 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9844 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9845 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
9846 false,
9847 OCSPRevocationStatus::UNKNOWN},
9848
9849 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
9850 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9851 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9852 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
9853 false,
9854 OCSPRevocationStatus::UNKNOWN},
9855
9856 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9857 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9858 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9859 OCSPVerifyResult::INVALID_DATE,
9860 false,
9861 OCSPRevocationStatus::UNKNOWN},
9862
9863 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9864 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9865 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9866 OCSPVerifyResult::PROVIDED,
9867 true,
9868 OCSPRevocationStatus::UNKNOWN},
9869
9870 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9871 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9872 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9873 OCSPVerifyResult::INVALID_DATE,
9874 false,
9875 OCSPRevocationStatus::UNKNOWN},
9876
9877 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9878 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9879 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9880 OCSPVerifyResult::INVALID_DATE,
9881 false,
9882 OCSPRevocationStatus::UNKNOWN},
9883
9884 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9885 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9886 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
9887 OCSPVerifyResult::BAD_PRODUCED_AT,
9888 false,
9889 OCSPRevocationStatus::UNKNOWN},
9890
9891 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9892 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9893 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9894 OCSPVerifyResult::BAD_PRODUCED_AT,
9895 false,
9896 OCSPRevocationStatus::UNKNOWN},
9897
9898 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9899 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9900 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9901 OCSPVerifyResult::BAD_PRODUCED_AT,
9902 false,
9903 OCSPRevocationStatus::UNKNOWN},
9904
9905 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9906 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9907 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9908 OCSPVerifyResult::PROVIDED,
9909 true,
9910 OCSPRevocationStatus::REVOKED},
9911
9912 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9913 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9914 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9915 OCSPVerifyResult::INVALID_DATE,
9916 false,
9917 OCSPRevocationStatus::UNKNOWN},
9918
9919 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9920 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9921 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9922 OCSPVerifyResult::INVALID_DATE,
9923 false,
9924 OCSPRevocationStatus::UNKNOWN},
9925
9926 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9927 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9928 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9929 OCSPVerifyResult::PROVIDED,
9930 true,
9931 OCSPRevocationStatus::GOOD},
9932
9933 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9934 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9935 {SpawnedTestServer::SSLOptions::OCSP_OK,
9936 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9937 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9938 OCSPVerifyResult::PROVIDED,
9939 true,
9940 OCSPRevocationStatus::GOOD},
9941
9942 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9943 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9944 {SpawnedTestServer::SSLOptions::OCSP_OK,
9945 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9946 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9947 OCSPVerifyResult::PROVIDED,
9948 true,
9949 OCSPRevocationStatus::GOOD},
9950
9951 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9952 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9953 {SpawnedTestServer::SSLOptions::OCSP_OK,
9954 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9955 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9956 OCSPVerifyResult::PROVIDED,
9957 true,
9958 OCSPRevocationStatus::GOOD},
9959
9960 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9961 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9962 {SpawnedTestServer::SSLOptions::OCSP_OK,
9963 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9964 {SpawnedTestServer::SSLOptions::OCSP_OK,
9965 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9966 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9967 OCSPVerifyResult::INVALID_DATE,
9968 false,
9969 OCSPRevocationStatus::UNKNOWN},
9970
9971 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9972 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9973 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9974 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9975 {SpawnedTestServer::SSLOptions::OCSP_OK,
9976 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9977 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9978 OCSPVerifyResult::PROVIDED,
9979 true,
9980 OCSPRevocationStatus::REVOKED},
9981
9982 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9983 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9984 {SpawnedTestServer::SSLOptions::OCSP_OK,
9985 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9986 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9987 OCSPVerifyResult::PROVIDED,
9988 true,
9989 OCSPRevocationStatus::UNKNOWN},
9990
9991 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9992 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9993 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9994 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9995 {SpawnedTestServer::SSLOptions::OCSP_OK,
9996 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9997 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9998 OCSPVerifyResult::PROVIDED,
9999 true,
10000 OCSPRevocationStatus::UNKNOWN},
10001
10002 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10003 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
10004 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10005 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10006 false,
10007 OCSPRevocationStatus::UNKNOWN},
10008
10009 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
10010 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
10011 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
10012 OCSPVerifyResult::NO_MATCHING_RESPONSE,
10013 false,
10014 OCSPRevocationStatus::UNKNOWN},
10015
10016};
10017
10018class HTTPSOCSPVerifyTest
10019 : public HTTPSOCSPTest,
10020 public testing::WithParamInterface<OCSPVerifyTestData> {};
10021
10022TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
10023 SpawnedTestServer::SSLOptions ssl_options(
10024 SpawnedTestServer::SSLOptions::CERT_AUTO);
10025 OCSPVerifyTestData test = GetParam();
10026
10027 ssl_options.ocsp_responses = test.ocsp_responses;
10028 ssl_options.ocsp_produced = test.ocsp_produced;
10029 ssl_options.staple_ocsp_response = true;
10030
10031 SSLInfo ssl_info;
10032 OCSPErrorTestDelegate delegate;
10033 ASSERT_NO_FATAL_FAILURE(
10034 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
10035
10036 // The SSLInfo must be extracted from |delegate| on error, due to how
10037 // URLRequest caches certificate errors.
10038 if (delegate.have_certificate_errors()) {
10039 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
10040 ssl_info = delegate.ssl_info();
10041 }
10042
10043 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
10044
10045 if (test.has_revocation_status)
10046 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
10047}
10048
10049INSTANTIATE_TEST_CASE_P(OCSPVerify,
10050 HTTPSOCSPVerifyTest,
10051 testing::ValuesIn(kOCSPVerifyData));
10052
mattm0b12a6f2016-11-29 19:57:1610053static bool SystemSupportsAIA() {
10054#if defined(OS_ANDROID)
10055 return false;
10056#else
10057 return true;
10058#endif
10059}
10060
10061class HTTPSAIATest : public HTTPSOCSPTest {
10062 public:
10063 void SetupContext() override {
10064 context_.set_ssl_config_service(new TestSSLConfigService(
10065 false /* check for EV */, false /* online revocation checking */,
10066 false /* require rev. checking for local anchors */,
10067 false /* token binding enabled */));
10068 }
10069};
10070
10071TEST_F(HTTPSAIATest, AIAFetching) {
10072 SpawnedTestServer::SSLOptions ssl_options(
10073 SpawnedTestServer::SSLOptions::CERT_AUTO_AIA_INTERMEDIATE);
10074 SpawnedTestServer test_server(
10075 SpawnedTestServer::TYPE_HTTPS, ssl_options,
10076 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
10077 ASSERT_TRUE(test_server.Start());
10078
10079 TestDelegate d;
10080 d.set_allow_certificate_errors(true);
10081 std::unique_ptr<URLRequest> r(context_.CreateRequest(
10082 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
10083
10084 r->Start();
10085 EXPECT_TRUE(r->is_pending());
10086
10087 base::RunLoop().Run();
10088
10089 EXPECT_EQ(1, d.response_started_count());
10090
10091 CertStatus cert_status = r->ssl_info().cert_status;
10092 if (SystemSupportsAIA()) {
10093 EXPECT_EQ(OK, d.request_status());
10094 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10095 ASSERT_TRUE(r->ssl_info().cert);
10096 EXPECT_EQ(2u, r->ssl_info().cert->GetIntermediateCertificates().size());
10097 } else {
10098 EXPECT_EQ(CERT_STATUS_AUTHORITY_INVALID,
10099 cert_status & CERT_STATUS_ALL_ERRORS);
10100 }
10101 ASSERT_TRUE(r->ssl_info().unverified_cert);
10102 EXPECT_EQ(
10103 0u, r->ssl_info().unverified_cert->GetIntermediateCertificates().size());
10104}
10105
[email protected]3a86a712013-07-30 07:16:2010106class HTTPSHardFailTest : public HTTPSOCSPTest {
10107 protected:
rsleevid6de8302016-06-21 01:33:2010108 void SetupContext() override {
10109 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410110 false /* check for EV */, false /* online revocation checking */,
10111 true /* require rev. checking for local
10112 anchors */,
10113 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:2010114 }
10115};
10116
[email protected]3a86a712013-07-30 07:16:2010117TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
10118 if (!SystemSupportsOCSP()) {
10119 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10120 return;
10121 }
10122
10123 if (!SystemSupportsHardFailRevocationChecking()) {
10124 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
10125 << "revocation checking";
10126 return;
10127 }
10128
10129 SpawnedTestServer::SSLOptions ssl_options(
10130 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810131 ssl_options.ocsp_status =
10132 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:2010133
10134 CertStatus cert_status;
10135 DoConnection(ssl_options, &cert_status);
10136
10137 EXPECT_EQ(CERT_STATUS_REVOKED,
10138 cert_status & CERT_STATUS_REVOKED);
10139
10140 // Without a positive OCSP response, we shouldn't show the EV status.
10141 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10142}
10143
[email protected]a13234c2012-03-20 21:45:0210144class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
10145 protected:
rsleevid6de8302016-06-21 01:33:2010146 void SetupContext() override {
10147 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410148 true /* check for EV */, false /* online revocation checking */,
10149 false /* require rev. checking for local
10150 anchors */,
10151 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210152 }
10153};
10154
10155TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
10156 if (!SystemSupportsOCSP()) {
10157 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10158 return;
10159 }
10160
[email protected]ce7d0cbc2013-05-03 18:57:2210161 SpawnedTestServer::SSLOptions ssl_options(
10162 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810163 ssl_options.ocsp_status =
10164 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210165 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10166
[email protected]924e9f92012-12-16 22:00:5310167 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210168 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210169
mattmaf868e72016-09-23 23:25:2010170 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210171 cert_status & CERT_STATUS_ALL_ERRORS);
10172
10173 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810174 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10175 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210176}
10177
[email protected]be0fff62013-08-29 23:37:4810178TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
10179 if (!SystemSupportsOCSP()) {
10180 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10181 return;
10182 }
10183
10184 SpawnedTestServer::SSLOptions ssl_options(
10185 SpawnedTestServer::SSLOptions::CERT_AUTO);
10186 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
10187 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10188
10189 CertStatus cert_status;
10190 DoConnection(ssl_options, &cert_status);
10191
mattm1a282f52016-11-10 21:49:4210192// Currently only works for Windows and OS X. When using NSS, it's not
10193// possible to determine whether the check failed because of actual
10194// revocation or because there was an OCSP failure.
10195#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]be0fff62013-08-29 23:37:4810196 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10197#else
10198 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10199#endif
10200
10201 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10202 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10203 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10204}
10205
[email protected]a13234c2012-03-20 21:45:0210206TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
10207 if (!SystemSupportsOCSP()) {
10208 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10209 return;
10210 }
10211
[email protected]ce7d0cbc2013-05-03 18:57:2210212 SpawnedTestServer::SSLOptions ssl_options(
10213 SpawnedTestServer::SSLOptions::CERT_AUTO);
10214 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:0210215 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
10216
10217 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210218 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210219
10220 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10221
10222 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10223 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:0810224 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10225 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210226}
10227
10228TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
10229 if (!SystemSupportsOCSP()) {
10230 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10231 return;
10232 }
10233
[email protected]ce7d0cbc2013-05-03 18:57:2210234 SpawnedTestServer::SSLOptions ssl_options(
10235 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810236 ssl_options.ocsp_status =
10237 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210238 SSLConfigService::SetCRLSet(
10239 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10240
10241 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210242 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210243
mattmaf868e72016-09-23 23:25:2010244 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:0210245 cert_status & CERT_STATUS_ALL_ERRORS);
10246
10247 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:0810248 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10249 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210250}
10251
[email protected]51523f52013-07-31 21:57:2810252TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
10253 if (!SystemSupportsOCSP()) {
10254 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10255 return;
10256 }
10257
10258 SpawnedTestServer::SSLOptions ssl_options(
10259 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810260 ssl_options.ocsp_status =
10261 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:2810262 SSLConfigService::SetCRLSet(
10263 scoped_refptr<CRLSet>(CRLSet::ForTesting(
10264 false, &kOCSPTestCertSPKI, "")));
10265
10266 CertStatus cert_status;
10267 DoConnection(ssl_options, &cert_status);
10268
10269 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
10270 // revocation check for EV.
10271 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10272 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
10273 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
10274 EXPECT_FALSE(
10275 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10276}
10277
10278TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
10279 if (!SystemSupportsOCSP()) {
10280 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10281 return;
10282 }
10283
[email protected]ce7d0cbc2013-05-03 18:57:2210284 SpawnedTestServer::SSLOptions ssl_options(
10285 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810286 ssl_options.ocsp_status =
10287 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210288 SSLConfigService::SetCRLSet(
10289 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
10290
[email protected]51523f52013-07-31 21:57:2810291 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:1210292 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210293
[email protected]51523f52013-07-31 21:57:2810294 // Even with a fresh CRLSet, we should still do online revocation checks when
10295 // the certificate chain isn't covered by the CRLSet, which it isn't in this
10296 // test.
mattmaf868e72016-09-23 23:25:2010297 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:2810298 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:0210299
[email protected]51523f52013-07-31 21:57:2810300 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:0210301 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:2810302 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:0210303}
10304
[email protected]b6f2de32012-08-17 04:35:0810305TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
10306 // Test that when EV verification is requested, but online revocation
10307 // checking is disabled, and the leaf certificate is not in fact EV, that
10308 // no revocation checking actually happens.
10309 if (!SystemSupportsOCSP()) {
10310 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
10311 return;
10312 }
10313
10314 // Unmark the certificate's OID as EV, which should disable revocation
10315 // checking (as per the user preference)
10316 ev_test_policy_.reset();
10317
[email protected]ce7d0cbc2013-05-03 18:57:2210318 SpawnedTestServer::SSLOptions ssl_options(
10319 SpawnedTestServer::SSLOptions::CERT_AUTO);
10320 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:0810321 SSLConfigService::SetCRLSet(
10322 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10323
10324 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210325 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:0810326
10327 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10328
10329 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10330 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10331}
10332
[email protected]a13234c2012-03-20 21:45:0210333class HTTPSCRLSetTest : public HTTPSOCSPTest {
10334 protected:
rsleevid6de8302016-06-21 01:33:2010335 void SetupContext() override {
10336 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:1410337 false /* check for EV */, false /* online revocation checking */,
10338 false /* require rev. checking for local
10339 anchors */,
10340 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:0210341 }
10342};
10343
10344TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:2210345 SpawnedTestServer::SSLOptions ssl_options(
10346 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:5810347 ssl_options.ocsp_status =
10348 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:0210349 SSLConfigService::SetCRLSet(
10350 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
10351
[email protected]924e9f92012-12-16 22:00:5310352 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:1210353 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:0210354
10355 // If we're not trying EV verification then, even if the CRLSet has expired,
10356 // we don't fall back to online revocation checks.
10357 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
10358 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10359 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
10360}
[email protected]51523f52013-07-31 21:57:2810361
10362TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:3010363#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:2810364 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
10365 return;
10366#endif
10367
10368 SpawnedTestServer::SSLOptions ssl_options(
10369 SpawnedTestServer::SSLOptions::CERT_AUTO);
10370 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
10371 ssl_options.cert_serial = 10;
10372 SSLConfigService::SetCRLSet(
10373 scoped_refptr<CRLSet>(CRLSet::ForTesting(
10374 false, &kOCSPTestCertSPKI, "\x0a")));
10375
10376 CertStatus cert_status = 0;
10377 DoConnection(ssl_options, &cert_status);
10378
10379 // If the certificate is recorded as revoked in the CRLSet, that should be
10380 // reflected without online revocation checking.
10381 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
10382 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
10383 EXPECT_FALSE(
10384 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
10385}
[email protected]316c1e5e2012-09-12 15:17:4410386#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:2710387
brettwa1228ebb2016-10-28 03:51:3410388#if !BUILDFLAG(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
mmenke9f2ec60c2015-06-01 20:59:4710389// These tests aren't passing on Android. Either the RemoteTestServer isn't
10390// starting up successfully, or it can't access the test files.
10391// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:3110392class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:1110393 public:
[email protected]d9fca99a2012-02-24 16:16:2010394 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:0510395 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:5510396 SpawnedTestServer::kLocalhost,
10397 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:4710398 // Can't use |default_context_|'s HostResolver to set up the
10399 // FTPTransactionFactory because it hasn't been created yet.
10400 default_context_.set_host_resolver(&host_resolver_);
10401 }
10402
10403 // URLRequestTest interface:
10404 void SetUpFactory() override {
10405 // Add FTP support to the default URLRequestContext.
10406 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:0510407 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:4710408 }
10409
10410 std::string GetTestFileContents() {
10411 base::FilePath path;
10412 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
10413 path = path.Append(kTestFilePath);
10414 path = path.AppendASCII(kFtpTestFile);
10415 std::string contents;
10416 EXPECT_TRUE(base::ReadFileToString(path, &contents));
10417 return contents;
[email protected]95409e12010-08-17 20:07:1110418 }
10419
[email protected]b89ca032009-08-31 21:41:3110420 protected:
mmenkecd4c7532016-10-19 18:36:0510421 // Note that this is destroyed before the FtpProtocolHandler that references
10422 // it, which is owned by the parent class. Since no requests are made during
10423 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:4710424 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:4710425
tommycli59a63432015-11-06 00:10:5510426 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:3110427};
10428
[email protected]d2a133182012-08-05 16:44:0810429// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:0910430TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:0810431 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:0810432
10433 TestDelegate d;
10434 {
danakj8522a25b2016-04-16 00:17:3610435 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:3610436 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910437 r->Start();
10438 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:0810439
[email protected]255620da2013-08-19 13:14:2910440 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:0810441
[email protected]f7022f32014-08-21 16:32:1910442 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:5010443 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:0810444 }
10445}
10446
mmenke9f2ec60c2015-06-01 20:59:4710447TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:5510448 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110449
[email protected]a25e90e2009-09-09 17:05:3710450 TestDelegate d;
10451 {
danakj8522a25b2016-04-16 00:17:3610452 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510453 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910454 r->Start();
10455 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3710456
[email protected]255620da2013-08-19 13:14:2910457 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:3710458
[email protected]f7022f32014-08-21 16:32:1910459 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:3710460 EXPECT_EQ(1, d.response_started_count());
10461 EXPECT_FALSE(d.received_data_before_response());
10462 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:5510463 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910464 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510465 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910466 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:3710467 }
10468}
10469
mmenke9f2ec60c2015-06-01 20:59:4710470TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:5510471 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110472
[email protected]dd265012009-01-08 20:45:2710473 TestDelegate d;
10474 {
danakj8522a25b2016-04-16 00:17:3610475 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510476 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910477 r->Start();
10478 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710479
[email protected]255620da2013-08-19 13:14:2910480 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710481
[email protected]f7022f32014-08-21 16:32:1910482 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710483 EXPECT_EQ(1, d.response_started_count());
10484 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710485 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5510486 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910487 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510488 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910489 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:2710490 }
10491}
10492
mmenke9f2ec60c2015-06-01 20:59:4710493TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:5510494 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110495
[email protected]dd265012009-01-08 20:45:2710496 TestDelegate d;
10497 {
danakj8522a25b2016-04-16 00:17:3610498 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510499 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10500 "chrome"),
10501 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910502 r->Start();
10503 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710504
[email protected]255620da2013-08-19 13:14:2910505 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710506
[email protected]f7022f32014-08-21 16:32:1910507 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:4710508 EXPECT_EQ(1, d.response_started_count());
10509 EXPECT_FALSE(d.received_data_before_response());
10510 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:5510511 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910512 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510513 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910514 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2510515
10516 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1910517 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2510518 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2710519 }
10520}
10521
mmenke9f2ec60c2015-06-01 20:59:4710522TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5510523 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110524
[email protected]dd265012009-01-08 20:45:2710525 TestDelegate d;
10526 {
danakj8522a25b2016-04-16 00:17:3610527 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510528 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10529 "wrong_password"),
davidben151423e2015-03-23 18:48:3610530 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910531 r->Start();
10532 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710533
[email protected]255620da2013-08-19 13:14:2910534 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710535
[email protected]f7022f32014-08-21 16:32:1910536 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710537 EXPECT_EQ(1, d.response_started_count());
10538 EXPECT_FALSE(d.received_data_before_response());
10539 EXPECT_EQ(d.bytes_received(), 0);
10540 }
10541}
10542
mmenke9f2ec60c2015-06-01 20:59:4710543TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5510544 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110545
[email protected]8b8a197d2009-08-26 15:57:5810546 TestDelegate d;
10547 // Set correct login credentials. The delegate will be asked for them when
10548 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810549 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810550 {
danakj8522a25b2016-04-16 00:17:3610551 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510552 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10553 "wrong_password"),
davidben151423e2015-03-23 18:48:3610554 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910555 r->Start();
10556 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810557
[email protected]255620da2013-08-19 13:14:2910558 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810559
[email protected]f7022f32014-08-21 16:32:1910560 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810561 EXPECT_EQ(1, d.response_started_count());
10562 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710563 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810564 }
10565}
10566
mmenke9f2ec60c2015-06-01 20:59:4710567TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5510568 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110569
[email protected]dd265012009-01-08 20:45:2710570 TestDelegate d;
10571 {
danakj8522a25b2016-04-16 00:17:3610572 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510573 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10574 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710575 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910576 r->Start();
10577 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710578
[email protected]255620da2013-08-19 13:14:2910579 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710580
[email protected]f7022f32014-08-21 16:32:1910581 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710582 EXPECT_EQ(1, d.response_started_count());
10583 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710584 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2710585 }
10586}
[email protected]8b8a197d2009-08-26 15:57:5810587
mmenke9f2ec60c2015-06-01 20:59:4710588TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5510589 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110590
[email protected]8b8a197d2009-08-26 15:57:5810591 TestDelegate d;
10592 // Set correct login credentials. The delegate will be asked for them when
10593 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810594 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810595 {
danakj8522a25b2016-04-16 00:17:3610596 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510597 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10598 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710599 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910600 r->Start();
10601 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810602
[email protected]255620da2013-08-19 13:14:2910603 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810604
[email protected]f7022f32014-08-21 16:32:1910605 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810606 EXPECT_EQ(1, d.response_started_count());
10607 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710608 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810609 }
10610}
[email protected]60a3df52009-09-22 16:13:2410611
mmenke9f2ec60c2015-06-01 20:59:4710612TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510613 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110614
danakj8522a25b2016-04-16 00:17:3610615 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410616 {
10617 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610618 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510619 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10620 "chrome"),
10621 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910622 r->Start();
10623 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410624
[email protected]255620da2013-08-19 13:14:2910625 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410626
[email protected]f7022f32014-08-21 16:32:1910627 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410628 EXPECT_EQ(1, d->response_started_count());
10629 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710630 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410631 }
10632
10633 d.reset(new TestDelegate);
10634 {
10635 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610636 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510637 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910638 r->Start();
10639 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410640
[email protected]255620da2013-08-19 13:14:2910641 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410642
[email protected]f7022f32014-08-21 16:32:1910643 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410644 EXPECT_EQ(1, d->response_started_count());
10645 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710646 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410647 }
10648}
10649
mmenke9f2ec60c2015-06-01 20:59:4710650TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510651 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110652
danakj8522a25b2016-04-16 00:17:3610653 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410654 // Set correct login credentials. The delegate will be asked for them when
10655 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810656 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410657 {
danakj8522a25b2016-04-16 00:17:3610658 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510659 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10660 "wrong_password"),
davidben151423e2015-03-23 18:48:3610661 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910662 r->Start();
10663 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410664
[email protected]255620da2013-08-19 13:14:2910665 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410666
[email protected]f7022f32014-08-21 16:32:1910667 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410668 EXPECT_EQ(1, d->response_started_count());
10669 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710670 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410671 }
10672
10673 // Use a new delegate without explicit credentials. The cached ones should be
10674 // used.
10675 d.reset(new TestDelegate);
10676 {
10677 // Don't pass wrong credentials in the URL, they would override valid cached
10678 // ones.
danakj8522a25b2016-04-16 00:17:3610679 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510680 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910681 r->Start();
10682 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410683
[email protected]255620da2013-08-19 13:14:2910684 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410685
[email protected]f7022f32014-08-21 16:32:1910686 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410687 EXPECT_EQ(1, d->response_started_count());
10688 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710689 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410690 }
10691}
ricea3a1c71f2016-06-17 10:05:2610692
10693TEST_F(URLRequestTestFTP, RawBodyBytes) {
10694 ASSERT_TRUE(ftp_test_server_.Start());
10695
10696 TestDelegate d;
10697 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10698 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10699 req->Start();
10700 base::RunLoop().Run();
10701
10702 EXPECT_EQ(6, req->GetRawBodyBytes());
10703}
10704
brettwa1228ebb2016-10-28 03:51:3410705#endif // !BUILDFLAG(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110706
ttuttlec0c828492015-05-15 01:25:5510707TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10708 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610709 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510710 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10711
10712 EXPECT_FALSE(req->response_info().network_accessed);
10713
10714 req->Start();
10715 base::RunLoop().Run();
10716
10717 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10718 EXPECT_FALSE(req->response_info().network_accessed);
10719}
10720
10721TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10722 MockHostResolver host_resolver;
10723 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10724 TestURLRequestContext context(true);
10725 context.set_network_delegate(&network_delegate);
10726 context.set_host_resolver(&host_resolver);
10727 host_resolver.rules()->AddSimulatedFailure("*");
10728 context.Init();
10729
10730 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610731 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510732 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10733
10734 EXPECT_FALSE(req->response_info().network_accessed);
10735
10736 req->Start();
10737 base::RunLoop().Run();
10738 EXPECT_TRUE(req->response_info().network_accessed);
10739}
10740
mmenkeed0498b2015-12-08 23:20:4210741// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210742// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210743TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210744 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610745 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210746 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10747
danakj8522a25b2016-04-16 00:17:3610748 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210749 req.get(), &default_network_delegate_,
10750 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210751 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10752 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210753
10754 req->Start();
10755 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210756 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5010757 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2210758 EXPECT_EQ(0, d.received_redirect_count());
10759}
10760
[email protected]7461a402011-03-24 23:19:5110761} // namespace net