blob: 325f745c98870852365dc6c27796c9d95eea4d86 [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"
63#include "net/cert/ct_verifier.h"
64#include "net/cert/ct_verify_result.h"
[email protected]6e7845ae2013-03-29 21:48:1165#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2466#include "net/cert/mock_cert_verifier.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"
eroman87c53d62015-04-02 06:51:0780#include "net/log/net_log.h"
mikecirone8b85c432016-09-08 19:11:0081#include "net/log/net_log_event_type.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"
tbansalca83c002016-04-28 20:56:2885#include "net/nqe/external_estimate_provider.h"
[email protected]63de95b2008-12-10 04:11:2786#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1987#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1488#include "net/ssl/channel_id_service.h"
89#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:5790#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:5591#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:1492#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:1193#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3694#include "net/test/embedded_test_server/embedded_test_server.h"
95#include "net/test/embedded_test_server/http_request.h"
96#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:0197#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:2198#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:4399#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:50100#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:34101#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43102#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52103#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50104#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14105#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50106#include "net/url_request/url_request_intercepting_job_factory.h"
107#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49108#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51109#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47110#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44111#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01112#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52113#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15114#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52115
[email protected]02494ec2014-05-07 15:05:29116#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55117#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29118#include "net/url_request/file_protocol_handler.h"
119#include "net/url_request/url_request_file_dir_job.h"
120#endif
121
mmenke9f2ec60c2015-06-01 20:59:47122#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
123#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29124#include "net/url_request/ftp_protocol_handler.h"
125#endif
126
[email protected]dffe8242012-03-20 15:14:27127#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48128#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56129#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27130#endif
131
robpercival214763f2016-07-01 23:27:01132using net::test::IsError;
133using net::test::IsOk;
134
[email protected]ad65a3e2013-12-25 18:18:01135using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33136using base::Time;
halton.huoe4e45742014-12-08 07:55:46137using std::string;
[email protected]e1acf6f2008-10-27 20:43:33138
[email protected]7461a402011-03-24 23:19:51139namespace net {
140
initial.commit586acc5fe2008-07-26 22:42:52141namespace {
142
[email protected]42cba2fb2013-03-29 19:58:57143const base::string16 kChrome(ASCIIToUTF16("chrome"));
144const base::string16 kSecret(ASCIIToUTF16("secret"));
145const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44146
mmenke9f2ec60c2015-06-01 20:59:47147const base::FilePath::CharType kTestFilePath[] =
148 FILE_PATH_LITERAL("net/data/url_request_unittest");
149
150#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
151// Test file used in most FTP tests.
152const char kFtpTestFile[] = "BullRunSpeech.txt";
153#endif
154
[email protected]2bba3252013-04-08 19:50:59155// Tests load timing information in the case a fresh connection was used, with
156// no proxy.
[email protected]cba24642014-08-15 20:49:59157void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25158 int connect_timing_flags) {
159 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59160 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25161
162 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
163 EXPECT_FALSE(load_timing_info.request_start.is_null());
164
165 EXPECT_LE(load_timing_info.request_start,
166 load_timing_info.connect_timing.connect_start);
167 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
168 connect_timing_flags);
169 EXPECT_LE(load_timing_info.connect_timing.connect_end,
170 load_timing_info.send_start);
171 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
172 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173
[email protected]58e32bb2013-01-21 18:23:25174 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
175 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
176}
177
[email protected]2bba3252013-04-08 19:50:59178// Same as above, but with proxy times.
179void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59180 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59181 int connect_timing_flags) {
182 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59183 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59184
185 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
186 EXPECT_FALSE(load_timing_info.request_start.is_null());
187
188 EXPECT_LE(load_timing_info.request_start,
189 load_timing_info.proxy_resolve_start);
190 EXPECT_LE(load_timing_info.proxy_resolve_start,
191 load_timing_info.proxy_resolve_end);
192 EXPECT_LE(load_timing_info.proxy_resolve_end,
193 load_timing_info.connect_timing.connect_start);
194 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
195 connect_timing_flags);
196 EXPECT_LE(load_timing_info.connect_timing.connect_end,
197 load_timing_info.send_start);
198 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
199 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
200}
201
202// Same as above, but with a reused socket and proxy times.
203void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59204 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59205 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59206 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59207
208 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
209 EXPECT_FALSE(load_timing_info.request_start.is_null());
210
211 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
212
213 EXPECT_LE(load_timing_info.request_start,
214 load_timing_info.proxy_resolve_start);
215 EXPECT_LE(load_timing_info.proxy_resolve_start,
216 load_timing_info.proxy_resolve_end);
217 EXPECT_LE(load_timing_info.proxy_resolve_end,
218 load_timing_info.send_start);
219 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
220 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
221}
222
xunjielia6888202015-04-14 21:34:25223#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25224// Tests load timing information in the case of a cache hit, when no cache
225// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17226base::StringPiece TestNetResourceProvider(int key) {
227 return "header";
228}
229
230void FillBuffer(char* buffer, size_t len) {
231 static bool called = false;
232 if (!called) {
233 called = true;
234 int seed = static_cast<int>(Time::Now().ToInternalValue());
235 srand(seed);
236 }
237
238 for (size_t i = 0; i < len; i++) {
239 buffer[i] = static_cast<char>(rand());
240 if (!buffer[i])
241 buffer[i] = 'g';
242 }
243}
xunjielia6888202015-04-14 21:34:25244#endif
[email protected]e3a85452013-11-14 01:46:17245
[email protected]3b23a222013-05-15 21:33:25246void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59247 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25248 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59249 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25250
251 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
252 EXPECT_FALSE(load_timing_info.request_start.is_null());
253
254 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
255 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
256 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
257 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
258
259 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
260 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
261}
262
mmenke9f2ec60c2015-06-01 20:59:47263#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25264// Tests load timing in the case that there is no HTTP response. This can be
265// used to test in the case of errors or non-HTTP requests.
266void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59267 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25268 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59269 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25270
271 // Only the request times should be non-null.
272 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
273 EXPECT_FALSE(load_timing_info.request_start.is_null());
274
275 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
276
277 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
278 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
279 EXPECT_TRUE(load_timing_info.send_start.is_null());
280 EXPECT_TRUE(load_timing_info.send_end.is_null());
281 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
282}
xunjielia6888202015-04-14 21:34:25283#endif
[email protected]58e32bb2013-01-21 18:23:25284
mmenkefb18c772015-09-30 22:22:50285// Test power monitor source that can simulate entering suspend mode. Can't use
286// the one in base/ because it insists on bringing its own MessageLoop.
287class TestPowerMonitorSource : public base::PowerMonitorSource {
288 public:
289 TestPowerMonitorSource() {}
290 ~TestPowerMonitorSource() override {}
291
292 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
293
294 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
295
296 bool IsOnBatteryPowerImpl() override { return false; }
297
298 private:
299 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
300};
301
mmenkeed0498b2015-12-08 23:20:42302// Job that allows monitoring of its priority.
303class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
304 public:
305 // The latest priority of the job is always written to |request_priority_|.
306 PriorityMonitoringURLRequestJob(URLRequest* request,
307 NetworkDelegate* network_delegate,
308 RequestPriority* request_priority)
309 : URLRequestTestJob(request, network_delegate),
310 request_priority_(request_priority) {
311 *request_priority_ = DEFAULT_PRIORITY;
312 }
313
314 void SetPriority(RequestPriority priority) override {
315 *request_priority_ = priority;
316 URLRequestTestJob::SetPriority(priority);
317 }
318
319 private:
320 RequestPriority* const request_priority_;
321};
322
[email protected]71c64f62008-11-15 04:36:51323// Do a case-insensitive search through |haystack| for |needle|.
324bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50325 std::string::const_iterator it = std::search(
326 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
327 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51328 return it != haystack.end();
329}
330
danakj8522a25b2016-04-16 00:17:36331std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
332 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28333 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48334 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23335}
336
[email protected]96adadb2010-08-28 01:16:17337// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51338void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17339 // -1 means unknown. 0 means no encryption.
340 EXPECT_GT(ssl_info.security_bits, 0);
341
342 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14343 uint16_t cipher_suite =
344 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29345 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17346}
347
[email protected]79e1fd62013-06-20 06:50:04348void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
349 const GURL& host_url) {
350 std::string sent_value;
351
352 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
353 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
354
355 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
356 EXPECT_EQ("keep-alive", sent_value);
357}
358
[email protected]dc5a5cf2012-09-26 02:49:30359// A network delegate that allows the user to choose a subset of request stages
360// to block in. When blocking, the delegate can do one of the following:
361// * synchronously return a pre-specified error code, or
362// * asynchronously return that value via an automatically called callback,
363// or
364// * block and wait for the user to do a callback.
365// Additionally, the user may also specify a redirect URL -- then each request
366// with the current URL different from the redirect target will be redirected
367// to that target, in the on-before-URL-request stage, independent of whether
368// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12369class BlockingNetworkDelegate : public TestNetworkDelegate {
370 public:
[email protected]dc5a5cf2012-09-26 02:49:30371 // Stages in which the delegate can block.
372 enum Stage {
[email protected]9045b8822012-01-13 20:35:35373 NOT_BLOCKED = 0,
374 ON_BEFORE_URL_REQUEST = 1 << 0,
375 ON_BEFORE_SEND_HEADERS = 1 << 1,
376 ON_HEADERS_RECEIVED = 1 << 2,
377 ON_AUTH_REQUIRED = 1 << 3
378 };
379
[email protected]dc5a5cf2012-09-26 02:49:30380 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59381 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30382 enum BlockMode {
383 SYNCHRONOUS, // No callback, returns specified return values.
384 AUTO_CALLBACK, // |this| posts a task to run the callback using the
385 // specified return codes.
386 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
387 // |auth_retval_| are ignored. In every blocking stage the
388 // message loop is quit.
389 };
390
391 // Creates a delegate which does not block at all.
392 explicit BlockingNetworkDelegate(BlockMode block_mode);
393
394 // For users to trigger a callback returning |response|.
395 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
396 // Only call if |block_mode_| == USER_CALLBACK.
397 void DoCallback(int response);
398 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
399
400 // Setters.
401 void set_retval(int retval) {
402 ASSERT_NE(USER_CALLBACK, block_mode_);
403 ASSERT_NE(ERR_IO_PENDING, retval);
404 ASSERT_NE(OK, retval);
405 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35406 }
407
[email protected]dc5a5cf2012-09-26 02:49:30408 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
409 // |auth_credentials_| will be passed with the response.
410 void set_auth_retval(AuthRequiredResponse auth_retval) {
411 ASSERT_NE(USER_CALLBACK, block_mode_);
412 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
413 auth_retval_ = auth_retval;
414 }
415 void set_auth_credentials(const AuthCredentials& auth_credentials) {
416 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35417 }
418
[email protected]dc5a5cf2012-09-26 02:49:30419 void set_redirect_url(const GURL& url) {
420 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35421 }
422
[email protected]dc5a5cf2012-09-26 02:49:30423 void set_block_on(int block_on) {
424 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35425 }
426
[email protected]dc5a5cf2012-09-26 02:49:30427 // Allows the user to check in which state did we block.
428 Stage stage_blocked_for_callback() const {
429 EXPECT_EQ(USER_CALLBACK, block_mode_);
430 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35431 }
432
433 private:
[email protected]dc5a5cf2012-09-26 02:49:30434 void RunCallback(int response, const CompletionCallback& callback);
435 void RunAuthCallback(AuthRequiredResponse response,
436 const AuthCallback& callback);
437
[email protected]9045b8822012-01-13 20:35:35438 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20439 int OnBeforeURLRequest(URLRequest* request,
440 const CompletionCallback& callback,
441 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35442
ryansturm2343cb62016-06-15 01:09:00443 int OnBeforeStartTransaction(URLRequest* request,
444 const CompletionCallback& callback,
445 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35446
dchengb03027d2014-10-21 12:00:20447 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35448 URLRequest* request,
449 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32450 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16451 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13452 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35453
dchengb03027d2014-10-21 12:00:20454 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35455 URLRequest* request,
456 const AuthChallengeInfo& auth_info,
457 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13458 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35459
[email protected]dc5a5cf2012-09-26 02:49:30460 // Resets the callbacks and |stage_blocked_for_callback_|.
461 void Reset();
[email protected]9045b8822012-01-13 20:35:35462
[email protected]dc5a5cf2012-09-26 02:49:30463 // Checks whether we should block in |stage|. If yes, returns an error code
464 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
465 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
466
467 // Configuration parameters, can be adjusted by public methods:
468 const BlockMode block_mode_;
469
470 // Values returned on blocking stages when mode is SYNCHRONOUS or
471 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
472 int retval_; // To be returned in non-auth stages.
473 AuthRequiredResponse auth_retval_;
474
[email protected]5f714132014-03-26 10:41:16475 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30476 int block_on_; // Bit mask: in which stages to block.
477
478 // |auth_credentials_| will be copied to |*target_auth_credential_| on
479 // callback.
480 AuthCredentials auth_credentials_;
481 AuthCredentials* target_auth_credentials_;
482
483 // Internal variables, not set by not the user:
484 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
485 // USER_CALLBACK).
486 Stage stage_blocked_for_callback_;
487
488 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35489 CompletionCallback callback_;
490 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30491
492 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
493
494 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35495};
496
[email protected]dc5a5cf2012-09-26 02:49:30497BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
498 : block_mode_(block_mode),
499 retval_(OK),
500 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
501 block_on_(0),
502 target_auth_credentials_(NULL),
503 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32504 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30505}
506
507void BlockingNetworkDelegate::DoCallback(int response) {
508 ASSERT_EQ(USER_CALLBACK, block_mode_);
509 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
510 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
511 CompletionCallback callback = callback_;
512 Reset();
513 RunCallback(response, callback);
514}
515
516void BlockingNetworkDelegate::DoAuthCallback(
517 NetworkDelegate::AuthRequiredResponse response) {
518 ASSERT_EQ(USER_CALLBACK, block_mode_);
519 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
520 AuthCallback auth_callback = auth_callback_;
521 Reset();
522 RunAuthCallback(response, auth_callback);
523}
524
525void BlockingNetworkDelegate::RunCallback(int response,
526 const CompletionCallback& callback) {
527 callback.Run(response);
528}
529
530void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
531 const AuthCallback& callback) {
532 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
533 ASSERT_TRUE(target_auth_credentials_ != NULL);
534 *target_auth_credentials_ = auth_credentials_;
535 }
536 callback.Run(response);
537}
538
539int BlockingNetworkDelegate::OnBeforeURLRequest(
540 URLRequest* request,
541 const CompletionCallback& callback,
542 GURL* new_url) {
543 if (redirect_url_ == request->url())
544 return OK; // We've already seen this request and redirected elsewhere.
545
546 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
547
548 if (!redirect_url_.is_empty())
549 *new_url = redirect_url_;
550
551 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
552}
553
ryansturm2343cb62016-06-15 01:09:00554int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30555 URLRequest* request,
556 const CompletionCallback& callback,
557 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00558 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30559
560 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
561}
562
563int BlockingNetworkDelegate::OnHeadersReceived(
564 URLRequest* request,
565 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32566 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16567 scoped_refptr<HttpResponseHeaders>* override_response_headers,
568 GURL* allowed_unsafe_redirect_url) {
569 TestNetworkDelegate::OnHeadersReceived(request,
570 callback,
571 original_response_headers,
572 override_response_headers,
573 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30574
575 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
576}
577
578NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
579 URLRequest* request,
580 const AuthChallengeInfo& auth_info,
581 const AuthCallback& callback,
582 AuthCredentials* credentials) {
583 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
584 credentials);
585 // Check that the user has provided callback for the previous blocked stage.
586 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
587
588 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
589 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
590 }
591
592 target_auth_credentials_ = credentials;
593
594 switch (block_mode_) {
595 case SYNCHRONOUS:
596 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
597 *target_auth_credentials_ = auth_credentials_;
598 return auth_retval_;
599
600 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45601 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30602 FROM_HERE,
603 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
604 weak_factory_.GetWeakPtr(), auth_retval_, callback));
605 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
606
607 case USER_CALLBACK:
608 auth_callback_ = callback;
609 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45610 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17611 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30612 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
613 }
614 NOTREACHED();
615 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
616}
617
618void BlockingNetworkDelegate::Reset() {
619 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
620 stage_blocked_for_callback_ = NOT_BLOCKED;
621 callback_.Reset();
622 auth_callback_.Reset();
623}
624
625int BlockingNetworkDelegate::MaybeBlockStage(
626 BlockingNetworkDelegate::Stage stage,
627 const CompletionCallback& callback) {
628 // Check that the user has provided callback for the previous blocked stage.
629 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
630
631 if ((block_on_ & stage) == 0) {
632 return OK;
633 }
634
635 switch (block_mode_) {
636 case SYNCHRONOUS:
637 EXPECT_NE(OK, retval_);
638 return retval_;
639
640 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45641 base::ThreadTaskRunnerHandle::Get()->PostTask(
642 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
643 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30644 return ERR_IO_PENDING;
645
646 case USER_CALLBACK:
647 callback_ = callback;
648 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45649 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17650 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30651 return ERR_IO_PENDING;
652 }
653 NOTREACHED();
654 return 0;
655}
656
[email protected]d5a4dd62012-05-23 01:41:04657class TestURLRequestContextWithProxy : public TestURLRequestContext {
658 public:
659 // Does not own |delegate|.
660 TestURLRequestContextWithProxy(const std::string& proxy,
661 NetworkDelegate* delegate)
662 : TestURLRequestContext(true) {
663 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
664 set_network_delegate(delegate);
665 Init();
666 }
dchengb03027d2014-10-21 12:00:20667 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04668};
669
stefanocsbd5be5202016-06-10 03:37:55670// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01671// URI and report to be sent.
672class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55673 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01674 public:
675 MockCertificateReportSender() {}
676 ~MockCertificateReportSender() override {}
677
678 void Send(const GURL& report_uri, const std::string& report) override {
679 latest_report_uri_ = report_uri;
680 latest_report_ = report;
681 }
682
estarkf2979122016-04-05 17:04:39683 void SetErrorCallback(
684 const base::Callback<void(const GURL&, int)>& error_callback) override {}
685
estark06e0dac2015-08-07 21:56:01686 const GURL& latest_report_uri() { return latest_report_uri_; }
687 const std::string& latest_report() { return latest_report_; }
688
689 private:
690 GURL latest_report_uri_;
691 std::string latest_report_;
692};
693
estarkcd39c11f2015-10-19 19:46:36694class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
695 public:
696 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34697 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36698};
699
dadrian612337a2016-07-20 22:36:58700// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
701// This is needed because after the certificate failure, the URLRequest will
702// retry the connection, and return a partial SSLInfo with a cached cert status.
703// The partial SSLInfo does not have the OCSP information filled out.
704class OCSPErrorTestDelegate : public TestDelegate {
705 public:
706 void OnSSLCertificateError(URLRequest* request,
707 const SSLInfo& ssl_info,
708 bool fatal) override {
709 ssl_info_ = ssl_info;
710 on_ssl_certificate_error_called_ = true;
711 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
712 }
713
714 bool on_ssl_certificate_error_called() {
715 return on_ssl_certificate_error_called_;
716 }
717
718 SSLInfo ssl_info() { return ssl_info_; }
719
720 private:
721 bool on_ssl_certificate_error_called_ = false;
722 SSLInfo ssl_info_;
723};
724
[email protected]d5a4dd62012-05-23 01:41:04725} // namespace
726
[email protected]a592c0432012-12-01 18:10:29727// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48728class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00729 public:
[email protected]ef2bf422012-05-11 03:27:09730 URLRequestTest() : default_context_(true) {
731 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25732 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50733 job_factory_impl_ = new URLRequestJobFactoryImpl();
734 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50735 }
bengr1bf8e942014-11-07 01:36:50736
dcheng67be2b1f2014-10-27 21:47:29737 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18738 // URLRequestJobs may post clean-up tasks on destruction.
739 base::RunLoop().RunUntilIdle();
740 }
[email protected]87a09a92011-07-14 15:50:50741
dcheng2339883c2014-12-23 00:23:05742 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50743 SetUpFactory();
744 default_context_.set_job_factory(job_factory_.get());
745 default_context_.Init();
746 PlatformTest::SetUp();
747 }
748
749 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20750 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36751 "data", base::WrapUnique(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50752#if !defined(DISABLE_FILE_SUPPORT)
753 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36754 "file", base::WrapUnique(new FileProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20755 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50756#endif
757 }
758
759 TestNetworkDelegate* default_network_delegate() {
760 return &default_network_delegate_;
761 }
762
763 const TestURLRequestContext& default_context() const {
764 return default_context_;
765 }
766
767
[email protected]3c5ca8c2011-09-29 01:14:51768 // Adds the TestJobInterceptor to the default context.
769 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23770 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20771 job_factory_impl_->SetProtocolHandler("http", nullptr);
772 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36773 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23774 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51775 }
776
[email protected]87a09a92011-07-14 15:50:50777 protected:
vishal.b62985ca92015-04-17 08:45:51778 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24779 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50780 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36781 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09782 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48783};
784
[email protected]316c1e5e2012-09-12 15:17:44785TEST_F(URLRequestTest, AboutBlankTest) {
786 TestDelegate d;
787 {
danakj8522a25b2016-04-16 00:17:36788 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36789 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44790
[email protected]f7022f32014-08-21 16:32:19791 r->Start();
792 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44793
[email protected]255620da2013-08-19 13:14:29794 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44795
[email protected]f7022f32014-08-21 16:32:19796 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44797 EXPECT_FALSE(d.received_data_before_response());
798 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19799 EXPECT_EQ("", r->GetSocketAddress().host());
800 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04801
802 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19803 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44804 }
805}
806
807TEST_F(URLRequestTest, DataURLImageTest) {
808 TestDelegate d;
809 {
810 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36811 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
812 GURL("data:image/png;base64,"
813 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
814 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
815 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
816 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
817 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
818 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
819 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
820 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
821 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
822 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
823 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
824 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
825 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
826 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
827 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
828 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
829 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
830 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
831 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36832 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44833
[email protected]f7022f32014-08-21 16:32:19834 r->Start();
835 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44836
[email protected]255620da2013-08-19 13:14:29837 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44838
[email protected]f7022f32014-08-21 16:32:19839 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44840 EXPECT_FALSE(d.received_data_before_response());
841 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19842 EXPECT_EQ("", r->GetSocketAddress().host());
843 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04844
845 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19846 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44847 }
848}
849
[email protected]5ecf7cb282014-05-11 01:49:55850#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44851TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15852 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04853
854#if defined(OS_ANDROID)
855 // Android devices are not guaranteed to be able to read /proc/self/exe
856 // Use /etc/hosts instead
857 app_path = base::FilePath("/etc/hosts");
858#else
[email protected]316c1e5e2012-09-12 15:17:44859 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04860#endif // OS_ANDROID
861
[email protected]316c1e5e2012-09-12 15:17:44862 GURL app_url = FilePathToFileURL(app_path);
863
864 TestDelegate d;
865 {
danakj8522a25b2016-04-16 00:17:36866 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36867 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44868
[email protected]f7022f32014-08-21 16:32:19869 r->Start();
870 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44871
[email protected]255620da2013-08-19 13:14:29872 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44873
avibf0746c2015-12-09 19:53:14874 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49875 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44876
[email protected]f7022f32014-08-21 16:32:19877 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44878 EXPECT_EQ(1, d.response_started_count());
879 EXPECT_FALSE(d.received_data_before_response());
880 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19881 EXPECT_EQ("", r->GetSocketAddress().host());
882 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04883
884 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19885 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44886 }
887}
888
[email protected]ba40bb762012-12-17 07:11:04889TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15890 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04891 PathService::Get(base::FILE_EXE, &app_path);
892 GURL app_url = FilePathToFileURL(app_path);
893
894 TestDelegate d;
895 {
danakj8522a25b2016-04-16 00:17:36896 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36897 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04898
[email protected]f7022f32014-08-21 16:32:19899 r->Start();
900 EXPECT_TRUE(r->is_pending());
901 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04902 }
[email protected]79e1fd62013-06-20 06:50:04903 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04904 // destroyed.
[email protected]255620da2013-08-19 13:14:29905 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04906}
907
[email protected]316c1e5e2012-09-12 15:17:44908TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
909 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36910 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44911 FillBuffer(buffer.get(), buffer_size);
912
[email protected]6cdfd7f2013-02-08 20:40:15913 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52914 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44915 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30916 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44917
avibf0746c2015-12-09 19:53:14918 int64_t file_size;
[email protected]56285702013-12-04 18:22:49919 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44920
921 const size_t first_byte_position = 500;
922 const size_t last_byte_position = buffer_size - first_byte_position;
923 const size_t content_length = last_byte_position - first_byte_position + 1;
924 std::string partial_buffer_string(buffer.get() + first_byte_position,
925 buffer.get() + last_byte_position + 1);
926
927 TestDelegate d;
928 {
danakj8522a25b2016-04-16 00:17:36929 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36930 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44931
932 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38933 headers.SetHeader(
934 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59935 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38936 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19937 r->SetExtraRequestHeaders(headers);
938 r->Start();
939 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44940
[email protected]255620da2013-08-19 13:14:29941 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19942 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44943 EXPECT_EQ(1, d.response_started_count());
944 EXPECT_FALSE(d.received_data_before_response());
945 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
946 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
947 EXPECT_TRUE(partial_buffer_string == d.data_received());
948 }
949
[email protected]dd3aa792013-07-16 19:10:23950 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44951}
952
953TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
954 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36955 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44956 FillBuffer(buffer.get(), buffer_size);
957
[email protected]6cdfd7f2013-02-08 20:40:15958 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52959 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44960 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30961 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44962
avibf0746c2015-12-09 19:53:14963 int64_t file_size;
[email protected]56285702013-12-04 18:22:49964 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44965
966 const size_t first_byte_position = 500;
967 const size_t last_byte_position = buffer_size - 1;
968 const size_t content_length = last_byte_position - first_byte_position + 1;
969 std::string partial_buffer_string(buffer.get() + first_byte_position,
970 buffer.get() + last_byte_position + 1);
971
972 TestDelegate d;
973 {
danakj8522a25b2016-04-16 00:17:36974 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36975 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44976
977 HttpRequestHeaders headers;
978 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59979 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38980 first_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, FileTestMultipleRanges) {
998 const size_t buffer_size = 400000;
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 TestDelegate d;
1011 {
danakj8522a25b2016-04-16 00:17:361012 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361013 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441014
1015 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381016 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191017 r->SetExtraRequestHeaders(headers);
1018 r->Start();
1019 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441020
[email protected]255620da2013-08-19 13:14:291021 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441022 EXPECT_TRUE(d.request_failed());
1023 }
1024
[email protected]dd3aa792013-07-16 19:10:231025 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441026}
1027
[email protected]3ca8b362013-11-11 22:18:071028TEST_F(URLRequestTest, AllowFileURLs) {
1029 base::ScopedTempDir temp_dir;
1030 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1031 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:521032 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071033 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301034 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591035 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071036
1037 {
1038 TestDelegate d;
1039 TestNetworkDelegate network_delegate;
1040 network_delegate.set_can_access_files(true);
1041 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361042 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361043 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191044 r->Start();
[email protected]3ca8b362013-11-11 22:18:071045 base::RunLoop().Run();
1046 EXPECT_FALSE(d.request_failed());
1047 EXPECT_EQ(test_data, d.data_received());
1048 }
1049
1050 {
1051 TestDelegate d;
1052 TestNetworkDelegate network_delegate;
1053 network_delegate.set_can_access_files(false);
1054 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361055 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361056 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191057 r->Start();
[email protected]3ca8b362013-11-11 22:18:071058 base::RunLoop().Run();
1059 EXPECT_TRUE(d.request_failed());
1060 EXPECT_EQ("", d.data_received());
1061 }
1062}
1063
[email protected]316c1e5e2012-09-12 15:17:441064
1065TEST_F(URLRequestTest, FileDirCancelTest) {
1066 // Put in mock resource provider.
1067 NetModule::SetResourceProvider(TestNetResourceProvider);
1068
1069 TestDelegate d;
1070 {
[email protected]6cdfd7f2013-02-08 20:40:151071 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441072 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1073 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1074 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1075
danakj8522a25b2016-04-16 00:17:361076 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361077 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191078 req->Start();
1079 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441080
1081 d.set_cancel_in_received_data_pending(true);
1082
[email protected]255620da2013-08-19 13:14:291083 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441084 }
1085
1086 // Take out mock resource provider.
1087 NetModule::SetResourceProvider(NULL);
1088}
1089
[email protected]5f9581402013-10-30 13:08:321090TEST_F(URLRequestTest, FileDirOutputSanity) {
1091 // Verify the general sanity of the the output of the file:
1092 // directory lister by checking for the output of a known existing
1093 // file.
1094 const char sentinel_name[] = "filedir-sentinel";
1095
1096 base::FilePath path;
1097 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471098 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321099
1100 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361101 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361102 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191103 req->Start();
[email protected]5f9581402013-10-30 13:08:321104 base::RunLoop().Run();
1105
1106 // Generate entry for the sentinel file.
1107 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581108 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491109 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321110 EXPECT_GT(info.size, 0);
1111 std::string sentinel_output = GetDirectoryListingEntry(
1112 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1113 std::string(sentinel_name),
1114 false /* is_dir */,
1115 info.size,
1116 info.last_modified);
1117
1118 ASSERT_LT(0, d.bytes_received());
1119 ASSERT_FALSE(d.request_failed());
mmenkefe5d0b112016-09-06 20:46:581120 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321121 // Check for the entry generated for the "sentinel" file.
1122 const std::string& data = d.data_received();
1123 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1124}
1125
[email protected]316c1e5e2012-09-12 15:17:441126TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1127 // There is an implicit redirect when loading a file path that matches a
1128 // directory and does not end with a slash. Ensure that following such
1129 // redirects does not crash. See http://crbug.com/18686.
1130
[email protected]6cdfd7f2013-02-08 20:40:151131 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441132 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471133 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441134
1135 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361136 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361137 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191138 req->Start();
[email protected]255620da2013-08-19 13:14:291139 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441140
1141 ASSERT_EQ(1, d.received_redirect_count());
1142 ASSERT_LT(0, d.bytes_received());
1143 ASSERT_FALSE(d.request_failed());
mmenkefe5d0b112016-09-06 20:46:581144 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441145}
1146
1147#if defined(OS_WIN)
1148// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1149TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1150 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361151 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361152 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191153 req->Start();
[email protected]255620da2013-08-19 13:14:291154 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441155
1156 ASSERT_EQ(1, d.received_redirect_count());
mmenkefe5d0b112016-09-06 20:46:581157 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441158}
[email protected]5ecf7cb282014-05-11 01:49:551159#endif // defined(OS_WIN)
1160
1161#endif // !defined(DISABLE_FILE_SUPPORT)
1162
1163TEST_F(URLRequestTest, InvalidUrlTest) {
1164 TestDelegate d;
1165 {
danakj8522a25b2016-04-16 00:17:361166 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361167 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551168
[email protected]f7022f32014-08-21 16:32:191169 r->Start();
1170 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551171
1172 base::RunLoop().Run();
1173 EXPECT_TRUE(d.request_failed());
1174 }
1175}
1176
jochen0e3b3a62014-09-16 18:31:231177TEST_F(URLRequestTest, InvalidReferrerTest) {
1178 TestURLRequestContext context;
1179 TestNetworkDelegate network_delegate;
1180 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1181 context.set_network_delegate(&network_delegate);
1182 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361183 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361184 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231185 req->SetReferrer("https://somewhere.com/");
1186
1187 req->Start();
1188 base::RunLoop().Run();
1189 EXPECT_TRUE(d.request_failed());
1190}
1191
[email protected]5ecf7cb282014-05-11 01:49:551192#if defined(OS_WIN)
1193TEST_F(URLRequestTest, ResolveShortcutTest) {
1194 base::FilePath app_path;
1195 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471196 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551197 app_path = app_path.AppendASCII("with-headers.html");
1198
1199 std::wstring lnk_path = app_path.value() + L".lnk";
1200
1201 base::win::ScopedCOMInitializer com_initializer;
1202
1203 // Temporarily create a shortcut for test
1204 {
1205 base::win::ScopedComPtr<IShellLink> shell;
1206 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1207 CLSCTX_INPROC_SERVER)));
1208 base::win::ScopedComPtr<IPersistFile> persist;
1209 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1210 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1211 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1212 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1213 }
1214
1215 TestDelegate d;
1216 {
danakj8522a25b2016-04-16 00:17:361217 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361218 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551219
[email protected]f7022f32014-08-21 16:32:191220 r->Start();
1221 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551222
1223 base::RunLoop().Run();
1224
1225 WIN32_FILE_ATTRIBUTE_DATA data;
1226 GetFileAttributesEx(app_path.value().c_str(),
1227 GetFileExInfoStandard, &data);
1228 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1229 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1230 FILE_ATTRIBUTE_NORMAL, NULL);
1231 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361232 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551233 DWORD read_size;
1234 BOOL result;
1235 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1236 &read_size, NULL);
1237 std::string content(buffer.get(), read_size);
1238 CloseHandle(file);
1239
[email protected]f7022f32014-08-21 16:32:191240 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551241 EXPECT_EQ(1, d.received_redirect_count());
1242 EXPECT_EQ(content, d.data_received());
1243 }
1244
1245 // Clean the shortcut
1246 DeleteFile(lnk_path.c_str());
1247}
1248#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441249
1250// Custom URLRequestJobs for use with interceptor tests
1251class RestartTestJob : public URLRequestTestJob {
1252 public:
1253 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1254 : URLRequestTestJob(request, network_delegate, true) {}
1255 protected:
dchengb03027d2014-10-21 12:00:201256 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441257 private:
dchengb03027d2014-10-21 12:00:201258 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441259};
1260
1261class CancelTestJob : public URLRequestTestJob {
1262 public:
1263 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1264 : URLRequestTestJob(request, network_delegate, true) {}
1265 protected:
dchengb03027d2014-10-21 12:00:201266 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441267 private:
dchengb03027d2014-10-21 12:00:201268 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441269};
1270
1271class CancelThenRestartTestJob : public URLRequestTestJob {
1272 public:
1273 explicit CancelThenRestartTestJob(URLRequest* request,
1274 NetworkDelegate* network_delegate)
1275 : URLRequestTestJob(request, network_delegate, true) {
1276 }
1277 protected:
dchengb03027d2014-10-21 12:00:201278 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441279 request_->Cancel();
1280 this->NotifyRestartRequired();
1281 }
1282 private:
dchengb03027d2014-10-21 12:00:201283 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441284};
1285
bengr1bf8e942014-11-07 01:36:501286// An Interceptor for use with interceptor tests.
1287class MockURLRequestInterceptor : public URLRequestInterceptor {
1288 public:
1289 // Static getters for canned response header and data strings.
1290 static std::string ok_data() {
1291 return URLRequestTestJob::test_data_1();
1292 }
1293
1294 static std::string ok_headers() {
1295 return URLRequestTestJob::test_headers();
1296 }
1297
1298 static std::string redirect_data() {
1299 return std::string();
1300 }
1301
1302 static std::string redirect_headers() {
1303 return URLRequestTestJob::test_redirect_headers();
1304 }
1305
1306 static std::string error_data() {
1307 return std::string("ohhh nooooo mr. bill!");
1308 }
1309
1310 static std::string error_headers() {
1311 return URLRequestTestJob::test_error_headers();
1312 }
1313
1314 MockURLRequestInterceptor()
1315 : intercept_main_request_(false), restart_main_request_(false),
1316 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1317 simulate_main_network_error_(false),
1318 intercept_redirect_(false), cancel_redirect_request_(false),
1319 intercept_final_response_(false), cancel_final_request_(false),
1320 use_url_request_http_job_(false),
1321 did_intercept_main_(false), did_restart_main_(false),
1322 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1323 did_simulate_error_main_(false),
1324 did_intercept_redirect_(false), did_cancel_redirect_(false),
1325 did_intercept_final_(false), did_cancel_final_(false) {
1326 }
1327
1328 ~MockURLRequestInterceptor() override {
1329 }
1330
1331 // URLRequestInterceptor implementation:
1332 URLRequestJob* MaybeInterceptRequest(
1333 URLRequest* request,
1334 NetworkDelegate* network_delegate) const override {
1335 if (restart_main_request_) {
1336 restart_main_request_ = false;
1337 did_restart_main_ = true;
1338 return new RestartTestJob(request, network_delegate);
1339 }
1340 if (cancel_main_request_) {
1341 cancel_main_request_ = false;
1342 did_cancel_main_ = true;
1343 return new CancelTestJob(request, network_delegate);
1344 }
1345 if (cancel_then_restart_main_request_) {
1346 cancel_then_restart_main_request_ = false;
1347 did_cancel_then_restart_main_ = true;
1348 return new CancelThenRestartTestJob(request, network_delegate);
1349 }
1350 if (simulate_main_network_error_) {
1351 simulate_main_network_error_ = false;
1352 did_simulate_error_main_ = true;
1353 if (use_url_request_http_job_) {
1354 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1355 }
1356 // This job will result in error since the requested URL is not one of the
1357 // URLs supported by these tests.
1358 return new URLRequestTestJob(request, network_delegate, true);
1359 }
1360 if (!intercept_main_request_)
1361 return nullptr;
1362 intercept_main_request_ = false;
1363 did_intercept_main_ = true;
1364 URLRequestTestJob* job = new URLRequestTestJob(request,
1365 network_delegate,
1366 main_headers_,
1367 main_data_,
1368 true);
1369 job->set_load_timing_info(main_request_load_timing_info_);
1370 return job;
1371 }
1372
1373 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1374 NetworkDelegate* network_delegate,
1375 const GURL& location) const override {
1376 if (cancel_redirect_request_) {
1377 cancel_redirect_request_ = false;
1378 did_cancel_redirect_ = true;
1379 return new CancelTestJob(request, network_delegate);
1380 }
1381 if (!intercept_redirect_)
1382 return nullptr;
1383 intercept_redirect_ = false;
1384 did_intercept_redirect_ = true;
1385 if (use_url_request_http_job_) {
1386 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1387 }
1388 return new URLRequestTestJob(request,
1389 network_delegate,
1390 redirect_headers_,
1391 redirect_data_,
1392 true);
1393 }
1394
1395 URLRequestJob* MaybeInterceptResponse(
1396 URLRequest* request,
1397 NetworkDelegate* network_delegate) const override {
1398 if (cancel_final_request_) {
1399 cancel_final_request_ = false;
1400 did_cancel_final_ = true;
1401 return new CancelTestJob(request, network_delegate);
1402 }
1403 if (!intercept_final_response_)
1404 return nullptr;
1405 intercept_final_response_ = false;
1406 did_intercept_final_ = true;
1407 if (use_url_request_http_job_) {
1408 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1409 }
1410 return new URLRequestTestJob(request,
1411 network_delegate,
1412 final_headers_,
1413 final_data_,
1414 true);
1415 }
1416
1417 void set_intercept_main_request(bool intercept_main_request) {
1418 intercept_main_request_ = intercept_main_request;
1419 }
1420
1421 void set_main_headers(const std::string& main_headers) {
1422 main_headers_ = main_headers;
1423 }
1424
1425 void set_main_data(const std::string& main_data) {
1426 main_data_ = main_data;
1427 }
1428
1429 void set_main_request_load_timing_info(
1430 const LoadTimingInfo& main_request_load_timing_info) {
1431 main_request_load_timing_info_ = main_request_load_timing_info;
1432 }
1433
1434 void set_restart_main_request(bool restart_main_request) {
1435 restart_main_request_ = restart_main_request;
1436 }
1437
1438 void set_cancel_main_request(bool cancel_main_request) {
1439 cancel_main_request_ = cancel_main_request;
1440 }
1441
1442 void set_cancel_then_restart_main_request(
1443 bool cancel_then_restart_main_request) {
1444 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1445 }
1446
1447 void set_simulate_main_network_error(bool simulate_main_network_error) {
1448 simulate_main_network_error_ = simulate_main_network_error;
1449 }
1450
1451 void set_intercept_redirect(bool intercept_redirect) {
1452 intercept_redirect_ = intercept_redirect;
1453 }
1454
1455 void set_redirect_headers(const std::string& redirect_headers) {
1456 redirect_headers_ = redirect_headers;
1457 }
1458
1459 void set_redirect_data(const std::string& redirect_data) {
1460 redirect_data_ = redirect_data;
1461 }
1462
1463 void set_cancel_redirect_request(bool cancel_redirect_request) {
1464 cancel_redirect_request_ = cancel_redirect_request;
1465 }
1466
1467 void set_intercept_final_response(bool intercept_final_response) {
1468 intercept_final_response_ = intercept_final_response;
1469 }
1470
1471 void set_final_headers(const std::string& final_headers) {
1472 final_headers_ = final_headers;
1473 }
1474
1475 void set_final_data(const std::string& final_data) {
1476 final_data_ = final_data;
1477 }
1478
1479 void set_cancel_final_request(bool cancel_final_request) {
1480 cancel_final_request_ = cancel_final_request;
1481 }
1482
1483 void set_use_url_request_http_job(bool use_url_request_http_job) {
1484 use_url_request_http_job_ = use_url_request_http_job;
1485 }
1486
1487 bool did_intercept_main() const {
1488 return did_intercept_main_;
1489 }
1490
1491 bool did_restart_main() const {
1492 return did_restart_main_;
1493 }
1494
1495 bool did_cancel_main() const {
1496 return did_cancel_main_;
1497 }
1498
1499 bool did_cancel_then_restart_main() const {
1500 return did_cancel_then_restart_main_;
1501 }
1502
1503 bool did_simulate_error_main() const {
1504 return did_simulate_error_main_;
1505 }
1506
1507 bool did_intercept_redirect() const {
1508 return did_intercept_redirect_;
1509 }
1510
1511 bool did_cancel_redirect() const {
1512 return did_cancel_redirect_;
1513 }
1514
1515 bool did_intercept_final() const {
1516 return did_intercept_final_;
1517 }
1518
1519 bool did_cancel_final() const {
1520 return did_cancel_final_;
1521 }
1522
1523 private:
1524 // Indicate whether to intercept the main request, and if so specify the
1525 // response to return and the LoadTimingInfo to use.
1526 mutable bool intercept_main_request_;
1527 mutable std::string main_headers_;
1528 mutable std::string main_data_;
1529 mutable LoadTimingInfo main_request_load_timing_info_;
1530
1531 // These indicate actions that can be taken within MaybeInterceptRequest.
1532 mutable bool restart_main_request_;
1533 mutable bool cancel_main_request_;
1534 mutable bool cancel_then_restart_main_request_;
1535 mutable bool simulate_main_network_error_;
1536
1537 // Indicate whether to intercept redirects, and if so specify the response to
1538 // return.
1539 mutable bool intercept_redirect_;
1540 mutable std::string redirect_headers_;
1541 mutable std::string redirect_data_;
1542
1543 // Cancel the request within MaybeInterceptRedirect.
1544 mutable bool cancel_redirect_request_;
1545
1546 // Indicate whether to intercept the final response, and if so specify the
1547 // response to return.
1548 mutable bool intercept_final_response_;
1549 mutable std::string final_headers_;
1550 mutable std::string final_data_;
1551
1552 // Cancel the final request within MaybeInterceptResponse.
1553 mutable bool cancel_final_request_;
1554
1555 // Instruct the interceptor to use a real URLRequestHTTPJob.
1556 mutable bool use_url_request_http_job_;
1557
1558 // These indicate if the interceptor did something or not.
1559 mutable bool did_intercept_main_;
1560 mutable bool did_restart_main_;
1561 mutable bool did_cancel_main_;
1562 mutable bool did_cancel_then_restart_main_;
1563 mutable bool did_simulate_error_main_;
1564 mutable bool did_intercept_redirect_;
1565 mutable bool did_cancel_redirect_;
1566 mutable bool did_intercept_final_;
1567 mutable bool did_cancel_final_;
1568};
1569
1570// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1571class URLRequestInterceptorTest : public URLRequestTest {
1572 public:
1573 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1574 }
1575
1576 ~URLRequestInterceptorTest() override {
1577 // URLRequestJobs may post clean-up tasks on destruction.
1578 base::RunLoop().RunUntilIdle();
1579 }
1580
1581 void SetUpFactory() override {
1582 interceptor_ = new MockURLRequestInterceptor();
1583 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361584 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501585 }
1586
1587 MockURLRequestInterceptor* interceptor() const {
1588 return interceptor_;
1589 }
1590
1591 private:
1592 MockURLRequestInterceptor* interceptor_;
1593};
1594
1595TEST_F(URLRequestInterceptorTest, Intercept) {
1596 // Intercept the main request and respond with a simple response.
1597 interceptor()->set_intercept_main_request(true);
1598 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1599 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591600 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361601 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361602 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501603 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1604 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1605 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1606 req->SetUserData(nullptr, user_data0);
1607 req->SetUserData(&user_data1, user_data1);
1608 req->SetUserData(&user_data2, user_data2);
1609 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191610 req->Start();
[email protected]255620da2013-08-19 13:14:291611 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591612
bengr1bf8e942014-11-07 01:36:501613 // Make sure we can retrieve our specific user data.
1614 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1615 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1616 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591617
bengr1bf8e942014-11-07 01:36:501618 // Check that we got one good response.
mmenkefe5d0b112016-09-06 20:46:581619 EXPECT_TRUE(req->status().is_success());
bengr1bf8e942014-11-07 01:36:501620 EXPECT_EQ(200, req->response_headers()->response_code());
1621 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1622 EXPECT_EQ(1, d.response_started_count());
1623 EXPECT_EQ(0, d.received_redirect_count());
1624}
[email protected]2bba3252013-04-08 19:50:591625
bengr1bf8e942014-11-07 01:36:501626TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1627 // Intercept the main request and respond with a redirect.
1628 interceptor()->set_intercept_main_request(true);
1629 interceptor()->set_main_headers(
1630 MockURLRequestInterceptor::redirect_headers());
1631 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1632
1633 // Intercept that redirect and respond with a final OK response.
1634 interceptor()->set_intercept_redirect(true);
1635 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1636 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1637
1638 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361639 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361640 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501641 req->set_method("GET");
1642 req->Start();
1643 base::RunLoop().Run();
1644
1645 // Check that the interceptor got called as expected.
1646 EXPECT_TRUE(interceptor()->did_intercept_main());
1647 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1648
1649 // Check that we got one good response.
mmenkefe5d0b112016-09-06 20:46:581650 EXPECT_TRUE(req->status().is_success());
1651 if (req->status().is_success())
bengr1bf8e942014-11-07 01:36:501652 EXPECT_EQ(200, req->response_headers()->response_code());
1653
1654 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1655 EXPECT_EQ(1, d.response_started_count());
1656 EXPECT_EQ(0, d.received_redirect_count());
1657}
1658
1659TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1660 // Intercept the main request to generate a server error response.
1661 interceptor()->set_intercept_main_request(true);
1662 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1663 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1664
1665 // Intercept that error and respond with an OK response.
1666 interceptor()->set_intercept_final_response(true);
1667 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1668 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1669
1670 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361671 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361672 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501673 req->set_method("GET");
1674 req->Start();
1675 base::RunLoop().Run();
1676
1677 // Check that the interceptor got called as expected.
1678 EXPECT_TRUE(interceptor()->did_intercept_main());
1679 EXPECT_TRUE(interceptor()->did_intercept_final());
1680
1681 // Check that we got one good response.
mmenkefe5d0b112016-09-06 20:46:581682 EXPECT_TRUE(req->status().is_success());
bengr1bf8e942014-11-07 01:36:501683 EXPECT_EQ(200, req->response_headers()->response_code());
1684 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1685 EXPECT_EQ(1, d.response_started_count());
1686 EXPECT_EQ(0, d.received_redirect_count());
1687}
1688
1689TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1690 // Intercept the main request to simulate a network error.
1691 interceptor()->set_simulate_main_network_error(true);
1692
1693 // Intercept that error and respond with an OK response.
1694 interceptor()->set_intercept_final_response(true);
1695 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1696 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1697
1698 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361699 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361700 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501701 req->set_method("GET");
1702 req->Start();
1703 base::RunLoop().Run();
1704
1705 // Check that the interceptor got called as expected.
1706 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1707 EXPECT_TRUE(interceptor()->did_intercept_final());
1708
1709 // Check that we received one good response.
mmenkefe5d0b112016-09-06 20:46:581710 EXPECT_TRUE(req->status().is_success());
bengr1bf8e942014-11-07 01:36:501711 EXPECT_EQ(200, req->response_headers()->response_code());
1712 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1713 EXPECT_EQ(1, d.response_started_count());
1714 EXPECT_EQ(0, d.received_redirect_count());
1715}
1716
1717TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1718 // Restart the main request.
1719 interceptor()->set_restart_main_request(true);
1720
1721 // then intercept the new main request and respond with an OK response
1722 interceptor()->set_intercept_main_request(true);
1723 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1724 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1725
1726 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361727 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361728 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501729 req->set_method("GET");
1730 req->Start();
1731 base::RunLoop().Run();
1732
1733 // Check that the interceptor got called as expected.
1734 EXPECT_TRUE(interceptor()->did_restart_main());
1735 EXPECT_TRUE(interceptor()->did_intercept_main());
1736
1737 // Check that we received one good response.
mmenkefe5d0b112016-09-06 20:46:581738 EXPECT_TRUE(req->status().is_success());
1739 if (req->status().is_success())
bengr1bf8e942014-11-07 01:36:501740 EXPECT_EQ(200, req->response_headers()->response_code());
1741
1742 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1743 EXPECT_EQ(1, d.response_started_count());
1744 EXPECT_EQ(0, d.received_redirect_count());
1745}
1746
1747TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1748 // Intercept the main request and cancel from within the restarted job.
1749 interceptor()->set_cancel_main_request(true);
1750
1751 // Set up to intercept the final response and override it with an OK response.
1752 interceptor()->set_intercept_final_response(true);
1753 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1754 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1755
1756 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361757 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361758 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501759 req->set_method("GET");
1760 req->Start();
1761 base::RunLoop().Run();
1762
1763 // Check that the interceptor got called as expected.
1764 EXPECT_TRUE(interceptor()->did_cancel_main());
1765 EXPECT_FALSE(interceptor()->did_intercept_final());
1766
1767 // Check that we see a canceled request.
mmenkefe5d0b112016-09-06 20:46:581768 EXPECT_FALSE(req->status().is_success());
1769 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
bengr1bf8e942014-11-07 01:36:501770}
1771
1772TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1773 // Intercept the main request and respond with a redirect.
1774 interceptor()->set_intercept_main_request(true);
1775 interceptor()->set_main_headers(
1776 MockURLRequestInterceptor::redirect_headers());
1777 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1778
1779 // Intercept the redirect and cancel from within that job.
1780 interceptor()->set_cancel_redirect_request(true);
1781
1782 // Set up to intercept the final response and override it with an OK response.
1783 interceptor()->set_intercept_final_response(true);
1784 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1785 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1786
1787 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361788 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361789 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501790 req->set_method("GET");
1791 req->Start();
1792 base::RunLoop().Run();
1793
1794 // Check that the interceptor got called as expected.
1795 EXPECT_TRUE(interceptor()->did_intercept_main());
1796 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1797 EXPECT_FALSE(interceptor()->did_intercept_final());
1798
1799 // Check that we see a canceled request.
mmenkefe5d0b112016-09-06 20:46:581800 EXPECT_FALSE(req->status().is_success());
1801 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
bengr1bf8e942014-11-07 01:36:501802}
1803
1804TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1805 // Intercept the main request to simulate a network error.
1806 interceptor()->set_simulate_main_network_error(true);
1807
1808 // Set up to intercept final the response and cancel from within that job.
1809 interceptor()->set_cancel_final_request(true);
1810
1811 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361812 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361813 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501814 req->set_method("GET");
1815 req->Start();
1816 base::RunLoop().Run();
1817
1818 // Check that the interceptor got called as expected.
1819 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1820 EXPECT_TRUE(interceptor()->did_cancel_final());
1821
1822 // Check that we see a canceled request.
mmenkefe5d0b112016-09-06 20:46:581823 EXPECT_FALSE(req->status().is_success());
1824 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
bengr1bf8e942014-11-07 01:36:501825}
1826
1827TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1828 // Intercept the main request and cancel then restart from within that job.
1829 interceptor()->set_cancel_then_restart_main_request(true);
1830
1831 // Set up to intercept the final response and override it with an OK response.
1832 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501833 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1834 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501835
1836 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361837 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361838 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501839 req->set_method("GET");
1840 req->Start();
1841 base::RunLoop().Run();
1842
1843 // Check that the interceptor got called as expected.
1844 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1845 EXPECT_FALSE(interceptor()->did_intercept_final());
1846
1847 // Check that we see a canceled request.
mmenkefe5d0b112016-09-06 20:46:581848 EXPECT_FALSE(req->status().is_success());
1849 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591850}
1851
1852// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1853// reused. |connect_time_flags| is used to indicate if there should be dns
1854// or SSL times, and |used_proxy| is used for proxy times.
1855LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1856 int connect_time_flags,
1857 bool used_proxy) {
1858 LoadTimingInfo load_timing;
1859 load_timing.socket_log_id = 1;
1860
1861 if (used_proxy) {
1862 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1863 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1864 }
1865
1866 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1867 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1868 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1869 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1870 }
1871 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1872 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1873 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1874 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1875 }
1876 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1877
1878 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1879 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1880 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1881 return load_timing;
1882}
1883
1884// Same as above, but in the case of a reused socket.
1885LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1886 bool used_proxy) {
1887 LoadTimingInfo load_timing;
1888 load_timing.socket_log_id = 1;
1889 load_timing.socket_reused = true;
1890
1891 if (used_proxy) {
1892 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1893 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1894 }
1895
1896 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1897 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1898 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1899 return load_timing;
1900}
1901
bengr1bf8e942014-11-07 01:36:501902LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1903 const LoadTimingInfo& job_load_timing,
1904 const URLRequestContext& context,
1905 MockURLRequestInterceptor* interceptor) {
1906 interceptor->set_intercept_main_request(true);
1907 interceptor->set_main_request_load_timing_info(job_load_timing);
1908 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361909 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361910 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501911 req->Start();
1912 base::RunLoop().Run();
1913
1914 LoadTimingInfo resulting_load_timing;
1915 req->GetLoadTimingInfo(&resulting_load_timing);
1916
1917 // None of these should be modified by the URLRequest.
1918 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1919 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1920 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1921 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1922 EXPECT_EQ(job_load_timing.receive_headers_end,
1923 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571924 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1925 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501926
1927 return resulting_load_timing;
1928}
1929
[email protected]2bba3252013-04-08 19:50:591930// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501931TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591932 base::TimeTicks now = base::TimeTicks::Now();
1933 LoadTimingInfo job_load_timing =
1934 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1935
[email protected]2ca01e52013-10-31 22:05:191936 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501937 RunURLRequestInterceptorLoadTimingTest(
1938 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591939
1940 // Nothing should have been changed by the URLRequest.
1941 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1942 load_timing_result.proxy_resolve_start);
1943 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1944 load_timing_result.proxy_resolve_end);
1945 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1946 load_timing_result.connect_timing.dns_start);
1947 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1948 load_timing_result.connect_timing.dns_end);
1949 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1950 load_timing_result.connect_timing.connect_start);
1951 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1952 load_timing_result.connect_timing.connect_end);
1953 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1954 load_timing_result.connect_timing.ssl_start);
1955 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1956 load_timing_result.connect_timing.ssl_end);
1957
1958 // Redundant sanity check.
1959 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1960}
1961
1962// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501963TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591964 base::TimeTicks now = base::TimeTicks::Now();
1965 LoadTimingInfo job_load_timing =
1966 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1967
[email protected]2ca01e52013-10-31 22:05:191968 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501969 RunURLRequestInterceptorLoadTimingTest(
1970 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591971
1972 // Nothing should have been changed by the URLRequest.
1973 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1974 load_timing_result.proxy_resolve_start);
1975 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1976 load_timing_result.proxy_resolve_end);
1977 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1978 load_timing_result.connect_timing.dns_start);
1979 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1980 load_timing_result.connect_timing.dns_end);
1981 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1982 load_timing_result.connect_timing.connect_start);
1983 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1984 load_timing_result.connect_timing.connect_end);
1985 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1986 load_timing_result.connect_timing.ssl_start);
1987 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1988 load_timing_result.connect_timing.ssl_end);
1989
1990 // Redundant sanity check.
1991 TestLoadTimingNotReusedWithProxy(load_timing_result,
1992 CONNECT_TIMING_HAS_SSL_TIMES);
1993}
1994
1995// Make sure that URLRequest correctly adjusts proxy times when they're before
1996// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101997// the case of reusing a SPDY session. The connected socket is not considered
1998// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591999//
2000// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502001TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592002 base::TimeTicks now = base::TimeTicks::Now();
2003 LoadTimingInfo job_load_timing =
2004 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2005 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2006 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2007 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2008 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2009 job_load_timing.connect_timing.connect_start =
2010 now - base::TimeDelta::FromDays(2);
2011 job_load_timing.connect_timing.connect_end =
2012 now - base::TimeDelta::FromDays(1);
2013
[email protected]2ca01e52013-10-31 22:05:192014 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502015 RunURLRequestInterceptorLoadTimingTest(
2016 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592017
2018 // Proxy times, connect times, and DNS times should all be replaced with
2019 // request_start.
2020 EXPECT_EQ(load_timing_result.request_start,
2021 load_timing_result.proxy_resolve_start);
2022 EXPECT_EQ(load_timing_result.request_start,
2023 load_timing_result.proxy_resolve_end);
2024 EXPECT_EQ(load_timing_result.request_start,
2025 load_timing_result.connect_timing.dns_start);
2026 EXPECT_EQ(load_timing_result.request_start,
2027 load_timing_result.connect_timing.dns_end);
2028 EXPECT_EQ(load_timing_result.request_start,
2029 load_timing_result.connect_timing.connect_start);
2030 EXPECT_EQ(load_timing_result.request_start,
2031 load_timing_result.connect_timing.connect_end);
2032
2033 // Other times should have been left null.
2034 TestLoadTimingNotReusedWithProxy(load_timing_result,
2035 CONNECT_TIMING_HAS_DNS_TIMES);
2036}
2037
2038// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502039TEST_F(URLRequestInterceptorTest,
2040 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592041 base::TimeTicks now = base::TimeTicks::Now();
2042 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2043 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2044 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2045
[email protected]2ca01e52013-10-31 22:05:192046 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502047 RunURLRequestInterceptorLoadTimingTest(
2048 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592049
2050 // Proxy times and connect times should all be replaced with request_start.
2051 EXPECT_EQ(load_timing_result.request_start,
2052 load_timing_result.proxy_resolve_start);
2053 EXPECT_EQ(load_timing_result.request_start,
2054 load_timing_result.proxy_resolve_end);
2055
2056 // Other times should have been left null.
2057 TestLoadTimingReusedWithProxy(load_timing_result);
2058}
2059
2060// Make sure that URLRequest correctly adjusts connect times when they're before
2061// |request_start|, due to reusing a connected socket. The connected socket is
2062// not considered reused in this test (May be a preconnect).
2063//
2064// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502065TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592066 base::TimeTicks now = base::TimeTicks::Now();
2067 LoadTimingInfo job_load_timing =
2068 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2069 job_load_timing.connect_timing.connect_start =
2070 now - base::TimeDelta::FromDays(1);
2071 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2072 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2073 job_load_timing.connect_timing.connect_end =
2074 now - base::TimeDelta::FromDays(4);
2075
[email protected]2ca01e52013-10-31 22:05:192076 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502077 RunURLRequestInterceptorLoadTimingTest(
2078 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592079
2080 // Connect times, and SSL times should be replaced with request_start.
2081 EXPECT_EQ(load_timing_result.request_start,
2082 load_timing_result.connect_timing.connect_start);
2083 EXPECT_EQ(load_timing_result.request_start,
2084 load_timing_result.connect_timing.ssl_start);
2085 EXPECT_EQ(load_timing_result.request_start,
2086 load_timing_result.connect_timing.ssl_end);
2087 EXPECT_EQ(load_timing_result.request_start,
2088 load_timing_result.connect_timing.connect_end);
2089
2090 // Other times should have been left null.
2091 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2092}
2093
2094// Make sure that URLRequest correctly adjusts connect times when they're before
2095// |request_start|, due to reusing a connected socket in the case that there
2096// are also proxy times. The connected socket is not considered reused in this
2097// test (May be a preconnect).
2098//
2099// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502100TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592101 base::TimeTicks now = base::TimeTicks::Now();
2102 LoadTimingInfo job_load_timing =
2103 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2104 job_load_timing.connect_timing.connect_start =
2105 now - base::TimeDelta::FromDays(1);
2106 job_load_timing.connect_timing.connect_end =
2107 now - base::TimeDelta::FromDays(2);
2108
[email protected]2ca01e52013-10-31 22:05:192109 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502110 RunURLRequestInterceptorLoadTimingTest(
2111 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592112
2113 // Connect times should be replaced with proxy_resolve_end.
2114 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2115 load_timing_result.connect_timing.connect_start);
2116 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2117 load_timing_result.connect_timing.connect_end);
2118
2119 // Other times should have been left null.
2120 TestLoadTimingNotReusedWithProxy(load_timing_result,
2121 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2122}
2123
[email protected]316c1e5e2012-09-12 15:17:442124// Check that two different URL requests have different identifiers.
2125TEST_F(URLRequestTest, Identifiers) {
2126 TestDelegate d;
2127 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362128 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362129 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362130 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362131 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442132
mmenke19378d22014-09-09 04:12:592133 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442134}
2135
blundellb8163592f2015-12-16 14:22:422136#if defined(OS_IOS)
2137// TODO(droger): Check that a failure to connect to the proxy is reported to
2138// the network delegate. crbug.com/496743
2139#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2140#else
2141#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2142#endif
2143TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442144 MockHostResolver host_resolver;
2145 host_resolver.rules()->AddSimulatedFailure("*");
2146
[email protected]ceefd7fd2012-11-29 00:36:242147 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442148 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2149
2150 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362151 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362152 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192153 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442154
[email protected]f7022f32014-08-21 16:32:192155 req->Start();
[email protected]255620da2013-08-19 13:14:292156 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442157
2158 // Check we see a failed request.
mmenkefe5d0b112016-09-06 20:46:582159 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152160 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192161 EXPECT_TRUE(req->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:582162 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2163 EXPECT_THAT(req->status().error(), IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442164
2165 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012166 EXPECT_THAT(network_delegate.last_error(),
2167 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442168 EXPECT_EQ(1, network_delegate.completed_requests());
2169}
2170
[email protected]cba24642014-08-15 20:49:592171// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442172// content is empty.
2173TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2174 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362175 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362176 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192177 req->Start();
[email protected]255620da2013-08-19 13:14:292178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442179 EXPECT_EQ("", d.data_received());
2180 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2181}
2182
[email protected]5033ab82013-03-22 20:17:462183// Make sure that SetPriority actually sets the URLRequest's priority
2184// correctly, both before and after start.
2185TEST_F(URLRequestTest, SetPriorityBasic) {
2186 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362187 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362188 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192189 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462190
[email protected]f7022f32014-08-21 16:32:192191 req->SetPriority(LOW);
2192 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462193
[email protected]f7022f32014-08-21 16:32:192194 req->Start();
2195 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462196
[email protected]f7022f32014-08-21 16:32:192197 req->SetPriority(MEDIUM);
2198 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462199}
2200
2201// Make sure that URLRequest calls SetPriority on a job before calling
2202// Start on it.
2203TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2204 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362205 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362206 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192207 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462208
mmenkeed0498b2015-12-08 23:20:422209 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362210 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422211 req.get(), &default_network_delegate_, &job_priority));
2212 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2213 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462214
[email protected]f7022f32014-08-21 16:32:192215 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462216
[email protected]f7022f32014-08-21 16:32:192217 req->Start();
mmenkeed0498b2015-12-08 23:20:422218 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462219}
2220
2221// Make sure that URLRequest passes on its priority updates to its
2222// job.
2223TEST_F(URLRequestTest, SetJobPriority) {
2224 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362225 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362226 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462227
mmenkeed0498b2015-12-08 23:20:422228 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362229 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422230 req.get(), &default_network_delegate_, &job_priority));
2231 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462232
[email protected]f7022f32014-08-21 16:32:192233 req->SetPriority(LOW);
2234 req->Start();
mmenkeed0498b2015-12-08 23:20:422235 EXPECT_EQ(LOW, job_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());
mmenkeed0498b2015-12-08 23:20:422239 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462240}
2241
[email protected]bb1c4662013-11-14 00:00:072242// Setting the IGNORE_LIMITS load flag should be okay if the priority
2243// is MAXIMUM_PRIORITY.
2244TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2245 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362246 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362247 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192248 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072249
mmenkeed0498b2015-12-08 23:20:422250 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362251 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422252 req.get(), &default_network_delegate_, &job_priority));
2253 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072254
[email protected]f7022f32014-08-21 16:32:192255 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2256 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072257
[email protected]f7022f32014-08-21 16:32:192258 req->SetPriority(MAXIMUM_PRIORITY);
2259 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072260
[email protected]f7022f32014-08-21 16:32:192261 req->Start();
2262 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422263 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072264}
2265
nick5d570de92015-05-04 20:16:162266namespace {
2267
2268// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552269class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442270 public:
tommycli59a63432015-11-06 00:10:552271 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2272 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272273 }
tommycli59a63432015-11-06 00:10:552274
2275 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2276};
tommyclieae5f75f2015-11-05 19:07:272277
nick5d570de92015-05-04 20:16:162278} // namespace
2279
[email protected]f2f31b32013-01-16 23:24:092280TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442281 LocalHttpTestServer test_server;
2282 ASSERT_TRUE(test_server.Start());
2283
2284 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362285 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502286 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442287
2288 // Set up a cookie.
2289 {
2290 TestNetworkDelegate network_delegate;
2291 context.set_network_delegate(&network_delegate);
2292 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362293 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552294 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362295 &d));
[email protected]f7022f32014-08-21 16:32:192296 req->Start();
[email protected]255620da2013-08-19 13:14:292297 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442298 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2299 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2300 EXPECT_EQ(1, network_delegate.set_cookie_count());
2301 }
2302
2303 // Verify that the cookie is set.
2304 {
2305 TestNetworkDelegate network_delegate;
2306 context.set_network_delegate(&network_delegate);
2307 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362308 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552309 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192310 req->Start();
[email protected]255620da2013-08-19 13:14:292311 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442312
2313 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2314 != std::string::npos);
2315 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2316 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2317 }
2318}
2319
[email protected]f2f31b32013-01-16 23:24:092320TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442321 LocalHttpTestServer test_server;
2322 ASSERT_TRUE(test_server.Start());
2323
2324 // Set up a cookie.
2325 {
2326 TestNetworkDelegate network_delegate;
2327 default_context_.set_network_delegate(&network_delegate);
2328 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362329 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552330 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362331 &d));
[email protected]f7022f32014-08-21 16:32:192332 req->Start();
[email protected]255620da2013-08-19 13:14:292333 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442334 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2335 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2336 }
2337
2338 // Verify that the cookie is set.
2339 {
2340 TestNetworkDelegate network_delegate;
2341 default_context_.set_network_delegate(&network_delegate);
2342 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362343 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552344 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192345 req->Start();
[email protected]255620da2013-08-19 13:14:292346 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442347
2348 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2349 != std::string::npos);
2350 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2351 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2352 }
2353
2354 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2355 {
2356 TestNetworkDelegate network_delegate;
2357 default_context_.set_network_delegate(&network_delegate);
2358 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362359 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552360 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192361 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2362 req->Start();
[email protected]255620da2013-08-19 13:14:292363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442364
2365 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2366 == std::string::npos);
2367
2368 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2369 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2370 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2371 }
2372}
2373
2374TEST_F(URLRequestTest, DoNotSaveCookies) {
2375 LocalHttpTestServer test_server;
2376 ASSERT_TRUE(test_server.Start());
2377
2378 // Set up a cookie.
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("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362385 &d));
[email protected]f7022f32014-08-21 16:32:192386 req->Start();
[email protected]255620da2013-08-19 13:14:292387 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442388
2389 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2390 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2391 EXPECT_EQ(1, network_delegate.set_cookie_count());
2392 }
2393
2394 // Try to set-up another cookie and update the previous cookie.
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("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362401 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192402 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2403 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442404
[email protected]255620da2013-08-19 13:14:292405 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442406
2407 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2408 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2409 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2410 EXPECT_EQ(0, network_delegate.set_cookie_count());
2411 }
2412
2413 // Verify the cookies weren't saved or updated.
2414 {
2415 TestNetworkDelegate network_delegate;
2416 default_context_.set_network_delegate(&network_delegate);
2417 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362418 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552419 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192420 req->Start();
[email protected]255620da2013-08-19 13:14:292421 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442422
2423 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2424 == std::string::npos);
2425 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2426 != std::string::npos);
2427
2428 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2429 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2430 EXPECT_EQ(0, network_delegate.set_cookie_count());
2431 }
2432}
2433
2434TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2435 LocalHttpTestServer test_server;
2436 ASSERT_TRUE(test_server.Start());
2437
2438 // Set up a cookie.
2439 {
2440 TestNetworkDelegate network_delegate;
2441 default_context_.set_network_delegate(&network_delegate);
2442 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362443 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552444 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362445 &d));
[email protected]f7022f32014-08-21 16:32:192446 req->Start();
[email protected]255620da2013-08-19 13:14:292447 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442448
2449 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2450 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2451 }
2452
2453 // Verify that the cookie is set.
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("CookieToNotSend=1")
2464 != std::string::npos);
2465
2466 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2467 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2468 }
2469
2470 // Verify that the cookie isn't sent.
2471 {
2472 TestNetworkDelegate network_delegate;
2473 default_context_.set_network_delegate(&network_delegate);
2474 TestDelegate d;
2475 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362476 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552477 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192478 req->Start();
[email protected]255620da2013-08-19 13:14:292479 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442480
2481 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2482 == std::string::npos);
2483
[email protected]22e045f2013-09-20 03:54:032484 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442485 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2486 }
2487}
2488
marqf14fff8d2015-12-02 15:52:292489// TODO(crbug.com/564656) This test is flaky on iOS.
2490#if defined(OS_IOS)
2491#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2492#else
2493#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2494#endif
[email protected]316c1e5e2012-09-12 15:17:442495TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2496 LocalHttpTestServer test_server;
2497 ASSERT_TRUE(test_server.Start());
2498
2499 // Set up a cookie.
2500 {
2501 TestNetworkDelegate network_delegate;
2502 default_context_.set_network_delegate(&network_delegate);
2503 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362504 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552505 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362506 &d));
[email protected]f7022f32014-08-21 16:32:192507 req->Start();
[email protected]255620da2013-08-19 13:14:292508 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442509
2510 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2511 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2512 }
2513
2514 // Try to set-up another cookie and update the previous cookie.
2515 {
2516 TestNetworkDelegate network_delegate;
2517 default_context_.set_network_delegate(&network_delegate);
2518 TestDelegate d;
2519 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362520 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552521 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362522 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192523 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442524
[email protected]255620da2013-08-19 13:14:292525 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442526
2527 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2528 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2529 }
2530
2531 // Verify the cookies weren't saved or updated.
2532 {
2533 TestNetworkDelegate network_delegate;
2534 default_context_.set_network_delegate(&network_delegate);
2535 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362536 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552537 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192538 req->Start();
[email protected]255620da2013-08-19 13:14:292539 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442540
2541 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2542 == std::string::npos);
2543 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2544 != std::string::npos);
2545
2546 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2547 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2548 }
2549}
2550
2551TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2552 LocalHttpTestServer test_server;
2553 ASSERT_TRUE(test_server.Start());
2554
2555 // Set up an empty cookie.
2556 {
2557 TestNetworkDelegate network_delegate;
2558 default_context_.set_network_delegate(&network_delegate);
2559 TestDelegate d;
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"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192562 req->Start();
[email protected]255620da2013-08-19 13:14:292563 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442564
2565 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2566 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2567 EXPECT_EQ(0, network_delegate.set_cookie_count());
2568 }
2569}
2570
2571TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2572 LocalHttpTestServer test_server;
2573 ASSERT_TRUE(test_server.Start());
2574
2575 // Set up a cookie.
2576 {
2577 TestNetworkDelegate network_delegate;
2578 default_context_.set_network_delegate(&network_delegate);
2579 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362580 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552581 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362582 &d));
[email protected]f7022f32014-08-21 16:32:192583 req->Start();
[email protected]255620da2013-08-19 13:14:292584 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442585
2586 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2587 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2588 }
2589
2590 // Verify that the cookie is set.
2591 {
2592 TestNetworkDelegate network_delegate;
2593 default_context_.set_network_delegate(&network_delegate);
2594 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362595 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552596 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192597 req->Start();
[email protected]255620da2013-08-19 13:14:292598 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442599
2600 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2601 != std::string::npos);
2602
2603 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2604 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2605 }
2606
2607 // Verify that the cookie isn't sent.
2608 {
2609 TestNetworkDelegate network_delegate;
2610 default_context_.set_network_delegate(&network_delegate);
2611 TestDelegate d;
2612 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362613 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552614 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192615 req->Start();
[email protected]255620da2013-08-19 13:14:292616 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442617
2618 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2619 == std::string::npos);
2620
[email protected]22e045f2013-09-20 03:54:032621 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442622 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2623 }
2624}
2625
2626TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2627 LocalHttpTestServer test_server;
2628 ASSERT_TRUE(test_server.Start());
2629
2630 // Set up a cookie.
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("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362637 &d));
[email protected]f7022f32014-08-21 16:32:192638 req->Start();
[email protected]255620da2013-08-19 13:14:292639 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442640
2641 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2642 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2643 }
2644
2645 // Try to set-up another cookie and update the previous cookie.
2646 {
2647 TestNetworkDelegate network_delegate;
2648 default_context_.set_network_delegate(&network_delegate);
2649 TestDelegate d;
2650 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362651 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552652 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362653 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192654 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442655
[email protected]255620da2013-08-19 13:14:292656 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442657
2658 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2659 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2660 }
2661
2662 // Verify the cookies weren't saved or updated.
2663 {
2664 TestNetworkDelegate network_delegate;
2665 default_context_.set_network_delegate(&network_delegate);
2666 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362667 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552668 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192669 req->Start();
[email protected]255620da2013-08-19 13:14:292670 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442671
2672 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2673 == std::string::npos);
2674 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2675 != std::string::npos);
2676
2677 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2678 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2679 }
2680}
2681
mkwstc5fa7762016-03-28 09:28:232682TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262683 LocalHttpTestServer test_server;
2684 ASSERT_TRUE(test_server.Start());
2685
mkwst202534e32016-01-15 16:07:152686 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152687 default_context_.set_network_delegate(&network_delegate);
2688
mkwstf71d0bd2016-03-21 14:15:242689 const std::string kHost = "example.test";
2690 const std::string kSubHost = "subdomain.example.test";
2691 const std::string kCrossHost = "cross-origin.test";
2692
2693 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262694 {
mkwst3f3daac2015-02-26 20:15:262695 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362696 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242697 test_server.GetURL(kHost,
2698 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2699 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362700 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262701 req->Start();
2702 base::RunLoop().Run();
2703 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2704 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242705 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262706 }
2707
mkwstf71d0bd2016-03-21 14:15:242708 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262709 {
mkwst3f3daac2015-02-26 20:15:262710 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362711 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242712 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2713 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2714 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262715 req->Start();
2716 base::RunLoop().Run();
2717
mkwstf71d0bd2016-03-21 14:15:242718 EXPECT_NE(std::string::npos,
2719 d.data_received().find("StrictSameSiteCookie=1"));
2720 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262721 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2722 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2723 }
2724
mkwstf71d0bd2016-03-21 14:15:242725 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262726 {
mkwst3f3daac2015-02-26 20:15:262727 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362728 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242729 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2730 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2731 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152732 req->Start();
2733 base::RunLoop().Run();
2734
mkwstf71d0bd2016-03-21 14:15:242735 EXPECT_NE(std::string::npos,
2736 d.data_received().find("StrictSameSiteCookie=1"));
2737 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152738 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2739 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2740 }
2741
mkwstf71d0bd2016-03-21 14:15:242742 // Verify that neither cookie is not sent for cross-site requests.
2743 {
2744 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362745 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242746 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2747 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2748 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2749 req->Start();
2750 base::RunLoop().Run();
2751
2752 EXPECT_EQ(std::string::npos,
2753 d.data_received().find("StrictSameSiteCookie=1"));
2754 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2755 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2756 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2757 }
2758
2759 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152760 // method is "safe".
2761 {
2762 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362763 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242764 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2765 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2766 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2767 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152768 req->Start();
2769 base::RunLoop().Run();
2770
mkwstf71d0bd2016-03-21 14:15:242771 EXPECT_EQ(std::string::npos,
2772 d.data_received().find("StrictSameSiteCookie=1"));
2773 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152774 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2775 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2776 }
2777
mkwstf71d0bd2016-03-21 14:15:242778 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152779 // method is unsafe (e.g. POST).
2780 {
2781 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362782 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242783 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2784 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2785 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152786 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262787 req->Start();
2788 base::RunLoop().Run();
2789
mkwstf71d0bd2016-03-21 14:15:242790 EXPECT_EQ(std::string::npos,
2791 d.data_received().find("StrictSameSiteCookie=1"));
2792 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262793 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2794 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2795 }
2796}
2797
estark557a5eb82015-12-01 22:57:102798// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362799TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552800 EmbeddedTestServer http_server;
2801 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362802 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552803 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2804 https_server.AddDefaultHandlers(
2805 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2806 ASSERT_TRUE(http_server.Start());
2807 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362808
estarkb15166b2015-12-18 16:56:382809 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362810 TestURLRequestContext context(true);
2811 context.set_network_delegate(&network_delegate);
2812 context.Init();
2813
estarkb15166b2015-12-18 16:56:382814 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362815 {
2816 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362817 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102818 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362819 DEFAULT_PRIORITY, &d));
2820 req->Start();
2821 base::RunLoop().Run();
2822 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2823 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2824 }
2825
2826 // Verify that the cookie is not set.
2827 {
2828 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362829 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552830 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362831 req->Start();
2832 base::RunLoop().Run();
2833
jww79aceda2015-12-07 01:56:342834 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2835 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362836 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2837 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2838 }
2839}
2840
estarkb15166b2015-12-18 16:56:382841TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552842 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2843 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362844 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552845 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362846
2847 TestNetworkDelegate network_delegate;
2848 TestURLRequestContext context(true);
2849 context.set_network_delegate(&network_delegate);
2850 context.Init();
2851
estarkb15166b2015-12-18 16:56:382852 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362853 {
2854 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362855 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102856 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552857 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362858 req->Start();
2859 base::RunLoop().Run();
2860 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2861 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2862 }
2863
2864 // Verify that the cookie is not set.
2865 {
2866 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362867 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552868 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362869 req->Start();
2870 base::RunLoop().Run();
2871
jww79aceda2015-12-07 01:56:342872 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362873 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2874 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2875 }
2876}
2877
estarkb15166b2015-12-18 16:56:382878TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552879 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2880 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362881 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552882 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362883
estarkb15166b2015-12-18 16:56:382884 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362885 TestURLRequestContext context(true);
2886 context.set_network_delegate(&network_delegate);
2887 context.Init();
2888
estarkb15166b2015-12-18 16:56:382889 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362890 {
2891 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362892 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102893 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552894 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362895 req->Start();
2896 base::RunLoop().Run();
2897 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2898 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2899 }
2900
2901 // Verify that the cookie is set.
2902 {
2903 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362904 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552905 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362906 req->Start();
2907 base::RunLoop().Run();
2908
jww79aceda2015-12-07 01:56:342909 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2910 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2911 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2912 }
2913}
2914
2915// Tests that secure cookies can't be set on non-secure origins if strict secure
2916// cookies are enabled.
2917TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2918 EmbeddedTestServer http_server;
2919 http_server.AddDefaultHandlers(
2920 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2921 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2922 https_server.AddDefaultHandlers(
2923 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2924 ASSERT_TRUE(http_server.Start());
2925 ASSERT_TRUE(https_server.Start());
2926
2927 TestExperimentalFeaturesNetworkDelegate network_delegate;
2928 TestURLRequestContext context(true);
2929 context.set_network_delegate(&network_delegate);
2930 context.Init();
2931
2932 // Try to set a Secure cookie, with experimental features enabled.
2933 {
2934 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362935 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342936 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2937 DEFAULT_PRIORITY, &d));
2938 req->Start();
2939 base::RunLoop().Run();
2940 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2941 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2942 }
2943
2944 // Verify that the cookie is not set.
2945 {
2946 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362947 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342948 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2949 req->Start();
2950 base::RunLoop().Run();
2951
2952 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2953 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2954 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2955 }
2956}
2957
2958// Tests that secure cookies can be set on secure origins even if strict secure
2959// cookies are enabled.
2960TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2961 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2962 https_server.AddDefaultHandlers(
2963 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2964 ASSERT_TRUE(https_server.Start());
2965
2966 TestExperimentalFeaturesNetworkDelegate network_delegate;
2967 TestURLRequestContext context(true);
2968 context.set_network_delegate(&network_delegate);
2969 context.Init();
2970
2971 // Try to set a Secure cookie, with experimental features enabled.
2972 {
2973 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362974 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342975 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2976 DEFAULT_PRIORITY, &d));
2977 req->Start();
2978 base::RunLoop().Run();
2979 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2980 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2981 }
2982
2983 // Verify that the cookie is not set.
2984 {
2985 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362986 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342987 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2988 req->Start();
2989 base::RunLoop().Run();
2990
2991 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362992 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2993 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2994 }
2995}
2996
mmenkefb18c772015-09-30 22:22:502997// Tests that a request is cancelled while entering suspend mode. Uses mocks
2998// rather than a spawned test server because the connection used to talk to
2999// the test server is affected by entering suspend mode on Android.
3000TEST_F(URLRequestTest, CancelOnSuspend) {
3001 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363002 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503003
3004 URLRequestFailedJob::AddUrlHandler();
3005
3006 TestDelegate d;
3007 // Request that just hangs.
3008 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:363009 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:503010 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3011 r->Start();
3012
3013 power_monitor_source->Suspend();
3014 // Wait for the suspend notification to cause the request to fail.
3015 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:583016 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
mmenkefb18c772015-09-30 22:22:503017 EXPECT_TRUE(d.request_failed());
3018 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3019
3020 URLRequestFilter::GetInstance()->ClearHandlers();
3021
3022 // Shouldn't be needed, but just in case.
3023 power_monitor_source->Resume();
3024}
3025
[email protected]5095cd72012-11-01 10:29:163026// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3027// value for the |fixed_date| argument given to the constructor.
3028class FixedDateNetworkDelegate : public TestNetworkDelegate {
3029 public:
3030 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3031 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203032 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163033
[email protected]cba24642014-08-15 20:49:593034 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203035 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593036 URLRequest* request,
3037 const CompletionCallback& callback,
3038 const HttpResponseHeaders* original_response_headers,
3039 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133040 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163041
3042 private:
3043 std::string fixed_date_;
3044
3045 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3046};
3047
3048int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593049 URLRequest* request,
3050 const CompletionCallback& callback,
3051 const HttpResponseHeaders* original_response_headers,
3052 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163053 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593054 HttpResponseHeaders* new_response_headers =
3055 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163056
3057 new_response_headers->RemoveHeader("Date");
3058 new_response_headers->AddHeader("Date: " + fixed_date_);
3059
3060 *override_response_headers = new_response_headers;
3061 return TestNetworkDelegate::OnHeadersReceived(request,
3062 callback,
3063 original_response_headers,
[email protected]5f714132014-03-26 10:41:163064 override_response_headers,
3065 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163066}
3067
3068// Test that cookie expiration times are adjusted for server/client clock
3069// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3070// headers by defaulting to GMT. (crbug.com/135131)
3071TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3072 LocalHttpTestServer test_server;
3073 ASSERT_TRUE(test_server.Start());
3074
3075 // Set up an expired cookie.
3076 {
3077 TestNetworkDelegate network_delegate;
3078 default_context_.set_network_delegate(&network_delegate);
3079 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363080 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193081 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553082 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363083 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193084 req->Start();
[email protected]255620da2013-08-19 13:14:293085 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163086 }
3087 // Verify that the cookie is not set.
3088 {
3089 TestNetworkDelegate network_delegate;
3090 default_context_.set_network_delegate(&network_delegate);
3091 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363092 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553093 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193094 req->Start();
[email protected]255620da2013-08-19 13:14:293095 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163096
3097 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3098 }
3099 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3100 {
3101 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3102 default_context_.set_network_delegate(&network_delegate);
3103 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363104 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193105 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553106 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363107 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193108 req->Start();
[email protected]255620da2013-08-19 13:14:293109 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163110 }
3111 // Verify that the cookie is set.
3112 {
3113 TestNetworkDelegate network_delegate;
3114 default_context_.set_network_delegate(&network_delegate);
3115 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363116 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553117 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193118 req->Start();
[email protected]255620da2013-08-19 13:14:293119 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163120
3121 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3122 }
3123}
3124
3125
[email protected]316c1e5e2012-09-12 15:17:443126// Check that it is impossible to change the referrer in the extra headers of
3127// an URLRequest.
3128TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3129 LocalHttpTestServer test_server;
3130 ASSERT_TRUE(test_server.Start());
3131
3132 // If extra headers contain referer and the request contains a referer,
3133 // only the latter shall be respected.
3134 {
3135 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363136 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553137 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193138 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443139
3140 HttpRequestHeaders headers;
3141 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193142 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443143
[email protected]f7022f32014-08-21 16:32:193144 req->Start();
[email protected]255620da2013-08-19 13:14:293145 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443146
3147 EXPECT_EQ("http://foo.com/", d.data_received());
3148 }
3149
3150 // If extra headers contain a referer but the request does not, no referer
3151 // shall be sent in the header.
3152 {
3153 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363154 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553155 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443156
3157 HttpRequestHeaders headers;
3158 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193159 req->SetExtraRequestHeaders(headers);
3160 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443161
[email protected]f7022f32014-08-21 16:32:193162 req->Start();
[email protected]255620da2013-08-19 13:14:293163 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443164
3165 EXPECT_EQ("None", d.data_received());
3166 }
3167}
3168
[email protected]b89290212009-08-14 22:37:353169class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113170 public:
mmenke9f2ec60c2015-06-01 20:59:473171 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113172
[email protected]b89290212009-08-14 22:37:353173 protected:
[email protected]21184962011-10-26 00:50:303174 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3175 // |request_method| is the method to use for the initial request.
3176 // |redirect_method| is the method that is expected to be used for the second
3177 // request, after redirection.
3178 // If |include_data| is true, data is uploaded with the request. The
3179 // response body is expected to match it exactly, if and only if
3180 // |request_method| == |redirect_method|.
3181 void HTTPRedirectMethodTest(const GURL& redirect_url,
3182 const std::string& request_method,
3183 const std::string& redirect_method,
3184 bool include_data) {
3185 static const char kData[] = "hello world";
3186 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363187 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363188 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193189 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303190 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073191 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303192 HttpRequestHeaders headers;
3193 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513194 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543195 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193196 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303197 }
[email protected]f7022f32014-08-21 16:32:193198 req->Start();
[email protected]255620da2013-08-19 13:14:293199 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193200 EXPECT_EQ(redirect_method, req->method());
mmenkefe5d0b112016-09-06 20:46:583201 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3202 EXPECT_THAT(req->status().error(), IsOk());
[email protected]21184962011-10-26 00:50:303203 if (include_data) {
3204 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543205 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3206 HttpRequestHeaders::kContentLength));
3207 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3208 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303209 EXPECT_EQ(kData, d.data_received());
3210 } else {
svaldez5b3a8972015-10-09 23:23:543211 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3212 HttpRequestHeaders::kContentLength));
3213 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3214 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303215 EXPECT_NE(kData, d.data_received());
3216 }
3217 }
3218 if (HasFailure())
3219 LOG(WARNING) << "Request method was: " << request_method;
3220 }
3221
jww5fe460ff2015-03-28 00:22:513222 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3223 // |request_method| is the method to use for the initial request.
3224 // |redirect_method| is the method that is expected to be used for the second
3225 // request, after redirection.
3226 // |origin_value| is the expected value for the Origin header after
3227 // redirection. If empty, expects that there will be no Origin header.
3228 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3229 const std::string& request_method,
3230 const std::string& redirect_method,
3231 const std::string& origin_value) {
3232 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363233 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513234 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3235 req->set_method(request_method);
3236 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3237 redirect_url.GetOrigin().spec(), false);
3238 req->Start();
3239
3240 base::RunLoop().Run();
3241
3242 EXPECT_EQ(redirect_method, req->method());
3243 // Note that there is no check for request success here because, for
3244 // purposes of testing, the request very well may fail. For example, if the
3245 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3246 // origin, there is not an HTTPS server in this unit test framework, so the
3247 // request would fail. However, that's fine, as long as the request headers
3248 // are in order and pass the checks below.
3249 if (origin_value.empty()) {
3250 EXPECT_FALSE(
3251 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3252 } else {
3253 std::string origin_header;
3254 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3255 HttpRequestHeaders::kOrigin, &origin_header));
3256 EXPECT_EQ(origin_value, origin_header);
3257 }
3258 }
3259
[email protected]762d2db2010-01-11 19:03:013260 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013261 const int kMsgSize = 20000; // multiple of 10
3262 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483263 char* uploadBytes = new char[kMsgSize+1];
3264 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013265 char marker = 'a';
3266 for (int idx = 0; idx < kMsgSize/10; idx++) {
3267 memcpy(ptr, "----------", 10);
3268 ptr += 10;
3269 if (idx % 100 == 0) {
3270 ptr--;
3271 *ptr++ = marker;
3272 if (++marker > 'z')
3273 marker = 'a';
3274 }
3275 }
3276 uploadBytes[kMsgSize] = '\0';
3277
[email protected]762d2db2010-01-11 19:03:013278 for (int i = 0; i < kIterations; ++i) {
3279 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363280 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553281 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193282 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013283
mmenkecbc2b712014-10-09 20:29:073284 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013285
[email protected]f7022f32014-08-21 16:32:193286 r->Start();
3287 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013288
[email protected]255620da2013-08-19 13:14:293289 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013290
mmenkefe5d0b112016-09-06 20:46:583291 ASSERT_EQ(1, d.response_started_count())
3292 << "request failed: " << r->status().status()
3293 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013294
3295 EXPECT_FALSE(d.received_data_before_response());
3296 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013297 }
3298 delete[] uploadBytes;
3299 }
3300
[email protected]ede03212012-09-07 12:52:263301 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343302 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363303 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553304 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363305 base::IntToString(num_cookies)),
3306 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343307
[email protected]f7022f32014-08-21 16:32:193308 r->Start();
3309 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343310
[email protected]255620da2013-08-19 13:14:293311 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343312
mmenkefe5d0b112016-09-06 20:46:583313 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343314
mmenkefe5d0b112016-09-06 20:46:583315 if (!is_success)
3316 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
3317
3318 return is_success;
[email protected]263163f2012-06-14 22:40:343319 }
3320
tommycli59a63432015-11-06 00:10:553321 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503322
tommycli59a63432015-11-06 00:10:553323 private:
[email protected]1700c6a2012-02-22 18:07:073324 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353325};
3326
tommycli59a63432015-11-06 00:10:553327namespace {
3328
danakj8522a25b2016-04-16 00:17:363329std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553330 const test_server::HttpRequest& request) {
3331 if (request.headers.find("Host") == request.headers.end() ||
3332 request.headers.at("Host") != "www.redirect.com" ||
3333 request.method != test_server::METHOD_CONNECT) {
3334 return nullptr;
3335 }
3336
danakj8522a25b2016-04-16 00:17:363337 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553338 new test_server::BasicHttpResponse);
3339 http_response->set_code(HTTP_FOUND);
3340 http_response->AddCustomHeader("Location",
3341 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483342 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553343}
3344
3345} // namespace
3346
nharperb7441ef2016-01-25 23:54:143347class TestSSLConfigService : public SSLConfigService {
3348 public:
3349 TestSSLConfigService(bool ev_enabled,
3350 bool online_rev_checking,
3351 bool rev_checking_required_local_anchors,
3352 bool token_binding_enabled)
3353 : ev_enabled_(ev_enabled),
3354 online_rev_checking_(online_rev_checking),
3355 rev_checking_required_local_anchors_(
3356 rev_checking_required_local_anchors),
3357 token_binding_enabled_(token_binding_enabled),
davidben5a312152016-06-27 22:11:473358 min_version_(kDefaultSSLVersionMin) {}
nharperb7441ef2016-01-25 23:54:143359
3360 void set_min_version(uint16_t version) { min_version_ = version; }
3361
nharperb7441ef2016-01-25 23:54:143362 // SSLConfigService:
3363 void GetSSLConfig(SSLConfig* config) override {
3364 *config = SSLConfig();
3365 config->rev_checking_enabled = online_rev_checking_;
3366 config->verify_ev_cert = ev_enabled_;
3367 config->rev_checking_required_local_anchors =
3368 rev_checking_required_local_anchors_;
nharperb7441ef2016-01-25 23:54:143369 if (min_version_) {
3370 config->version_min = min_version_;
3371 }
3372 if (token_binding_enabled_) {
3373 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3374 }
3375 }
3376
3377 protected:
3378 ~TestSSLConfigService() override {}
3379
3380 private:
3381 const bool ev_enabled_;
3382 const bool online_rev_checking_;
3383 const bool rev_checking_required_local_anchors_;
3384 const bool token_binding_enabled_;
3385 uint16_t min_version_;
nharperb7441ef2016-01-25 23:54:143386};
3387
3388// TODO(svaldez): Update tests to use EmbeddedTestServer.
3389#if !defined(OS_IOS)
3390class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3391 public:
3392 void SetUp() override {
3393 default_context_.set_ssl_config_service(
3394 new TestSSLConfigService(false, false, false, true));
3395 channel_id_service_.reset(new ChannelIDService(
3396 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3397 default_context_.set_channel_id_service(channel_id_service_.get());
3398 URLRequestTestHTTP::SetUp();
3399 }
3400
3401 protected:
danakj8522a25b2016-04-16 00:17:363402 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143403};
3404
3405TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3406 SpawnedTestServer::SSLOptions ssl_options;
3407 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3408 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3409 ssl_options,
3410 base::FilePath(kTestFilePath));
3411 ASSERT_TRUE(https_test_server.Start());
3412
3413 TestDelegate d;
3414 {
danakj8522a25b2016-04-16 00:17:363415 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143416 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3417 r->Start();
3418 EXPECT_TRUE(r->is_pending());
3419
3420 base::RunLoop().Run();
3421
mmenkefe5d0b112016-09-06 20:46:583422 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
nharperb7441ef2016-01-25 23:54:143423
3424 HttpRequestHeaders headers;
3425 std::string token_binding_header, token_binding_message;
3426 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3427 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3428 &token_binding_header));
3429 EXPECT_TRUE(base::Base64UrlDecode(
3430 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3431 &token_binding_message));
nharperd6e65822016-03-30 23:05:483432 std::vector<TokenBinding> token_bindings;
3433 ASSERT_TRUE(
3434 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3435 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143436
3437 EXPECT_GT(d.bytes_received(), 0);
3438 std::string ekm = d.data_received();
3439
nharperd6e65822016-03-30 23:05:483440 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3441 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3442 token_bindings[0].signature, ekm));
nharperb7441ef2016-01-25 23:54:143443 }
3444}
nharperd6e65822016-03-30 23:05:483445
3446TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3447 SpawnedTestServer::SSLOptions ssl_options;
3448 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3449 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3450 ssl_options,
3451 base::FilePath(kTestFilePath));
3452 ASSERT_TRUE(https_test_server.Start());
3453
3454 TestDelegate d;
3455 {
3456 GURL redirect_url =
3457 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363458 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483459 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3460 r->Start();
3461 EXPECT_TRUE(r->is_pending());
3462
3463 base::RunLoop().Run();
3464
mmenkefe5d0b112016-09-06 20:46:583465 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
nharperd6e65822016-03-30 23:05:483466
3467 HttpRequestHeaders headers;
3468 std::string token_binding_header, token_binding_message;
3469 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3470 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3471 &token_binding_header));
3472 EXPECT_TRUE(base::Base64UrlDecode(
3473 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3474 &token_binding_message));
3475 std::vector<TokenBinding> token_bindings;
3476 ASSERT_TRUE(
3477 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3478 ASSERT_EQ(2ull, token_bindings.size());
3479
3480 EXPECT_GT(d.bytes_received(), 0);
3481 std::string ekm = d.data_received();
3482
3483 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3484 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3485 token_bindings[0].signature, ekm));
3486 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
3487 EXPECT_TRUE(VerifyEKMSignature(token_bindings[1].ec_point,
3488 token_bindings[1].signature, ekm));
3489 }
3490}
3491
3492// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3493// EmbeddedTestServer once crbug.com/599187 is resolved.
3494#if !defined(OS_ANDROID)
3495TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3496 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3497 SpawnedTestServer::kLocalhost,
3498 base::FilePath());
3499 ASSERT_TRUE(http_server.Start());
3500 SpawnedTestServer::SSLOptions ssl_options;
3501 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3502 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3503 ssl_options,
3504 base::FilePath(kTestFilePath));
3505 ASSERT_TRUE(https_test_server.Start());
3506
3507 TestDelegate d;
3508 {
3509 GURL redirect_url = http_server.GetURL(
3510 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363511 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483512 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3513 r->Start();
3514 EXPECT_TRUE(r->is_pending());
3515
3516 base::RunLoop().Run();
3517
mmenkefe5d0b112016-09-06 20:46:583518 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
nharperd6e65822016-03-30 23:05:483519
3520 HttpRequestHeaders headers;
3521 std::string token_binding_header, token_binding_message;
3522 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3523 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3524 &token_binding_header));
3525 EXPECT_TRUE(base::Base64UrlDecode(
3526 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3527 &token_binding_message));
3528 std::vector<TokenBinding> token_bindings;
3529 ASSERT_TRUE(
3530 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3531 ASSERT_EQ(1ull, token_bindings.size());
3532
3533 EXPECT_GT(d.bytes_received(), 0);
3534 std::string ekm = d.data_received();
3535
3536 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3537 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3538 token_bindings[0].signature, ekm));
3539 }
3540}
3541
3542// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363543// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483544// support Token Binding, then we do not send a Sec-Token-Binding when following
3545// the redirect.
3546TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3547 SpawnedTestServer::SSLOptions ssl_options;
3548 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3549 ssl_options,
3550 base::FilePath(kTestFilePath));
3551 ASSERT_TRUE(https_test_server.Start());
3552 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3553 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3554 ssl_options,
3555 base::FilePath(kTestFilePath));
3556 ASSERT_TRUE(token_binding_test_server.Start());
3557
3558 TestDelegate d;
3559 {
3560 GURL redirect_url = token_binding_test_server.GetURL(
3561 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363562 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483563 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3564 r->Start();
3565 EXPECT_TRUE(r->is_pending());
3566
3567 base::RunLoop().Run();
3568
mmenkefe5d0b112016-09-06 20:46:583569 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
nharperd6e65822016-03-30 23:05:483570
3571 HttpRequestHeaders headers;
3572 std::string token_binding_header, token_binding_message;
3573 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3574 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3575 &token_binding_header));
3576 }
3577}
3578#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143579#endif // !defined(OS_IOS)
3580
3581// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113582// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553583// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113584// follow.
[email protected]f2f31b32013-01-16 23:24:093585TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553586 http_test_server()->RegisterRequestHandler(
3587 base::Bind(&HandleRedirectConnect));
3588 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113589
[email protected]ceefd7fd2012-11-29 00:36:243590 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043591 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553592 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503593
[email protected]d1ec59082009-02-11 02:48:153594 TestDelegate d;
3595 {
danakj8522a25b2016-04-16 00:17:363596 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363597 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193598 r->Start();
3599 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153600
[email protected]255620da2013-08-19 13:14:293601 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153602
mmenkefe5d0b112016-09-06 20:46:583603 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153604 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193605 EXPECT_TRUE(r->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:583606 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]dc651782009-02-14 01:45:083607 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153608 // We should not have followed the redirect.
3609 EXPECT_EQ(0, d.received_redirect_count());
3610 }
3611}
3612
[email protected]8202d0c2011-02-23 08:31:143613// This is the same as the previous test, but checks that the network delegate
3614// registers the error.
[email protected]c044616e2013-02-20 02:01:263615TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553616 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143617
[email protected]ceefd7fd2012-11-29 00:36:243618 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043619 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553620 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503621
[email protected]8202d0c2011-02-23 08:31:143622 TestDelegate d;
3623 {
danakj8522a25b2016-04-16 00:17:363624 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363625 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193626 r->Start();
3627 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143628
[email protected]255620da2013-08-19 13:14:293629 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143630
mmenkefe5d0b112016-09-06 20:46:583631 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153632 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193633 EXPECT_TRUE(r->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:583634 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143635 EXPECT_EQ(1, d.response_started_count());
3636 // We should not have followed the redirect.
3637 EXPECT_EQ(0, d.received_redirect_count());
3638
3639 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:013640 EXPECT_THAT(network_delegate.last_error(),
3641 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143642 }
3643}
3644
[email protected]dc5a5cf2012-09-26 02:49:303645// Tests that we can block and asynchronously return OK in various stages.
3646TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3647 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3648 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3649 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3650 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3651 };
3652 static const size_t blocking_stages_length = arraysize(blocking_stages);
3653
tommycli59a63432015-11-06 00:10:553654 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303655
3656 TestDelegate d;
3657 BlockingNetworkDelegate network_delegate(
3658 BlockingNetworkDelegate::USER_CALLBACK);
3659 network_delegate.set_block_on(
3660 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3661 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3662 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3663
3664 TestURLRequestContext context(true);
3665 context.set_network_delegate(&network_delegate);
3666 context.Init();
3667
3668 {
danakj8522a25b2016-04-16 00:17:363669 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553670 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303671
[email protected]f7022f32014-08-21 16:32:193672 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303673 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293674 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303675 EXPECT_EQ(blocking_stages[i],
3676 network_delegate.stage_blocked_for_callback());
3677 network_delegate.DoCallback(OK);
3678 }
[email protected]255620da2013-08-19 13:14:293679 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193680 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:583681 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303682 EXPECT_EQ(1, network_delegate.created_requests());
3683 EXPECT_EQ(0, network_delegate.destroyed_requests());
3684 }
3685 EXPECT_EQ(1, network_delegate.destroyed_requests());
3686}
3687
[email protected]4c76d7c2011-04-15 19:14:123688// Tests that the network delegate can block and cancel a request.
3689TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553690 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123691
3692 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303693 BlockingNetworkDelegate network_delegate(
3694 BlockingNetworkDelegate::AUTO_CALLBACK);
3695 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3696 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123697
[email protected]d5a4dd62012-05-23 01:41:043698 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553699 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503700
[email protected]4c76d7c2011-04-15 19:14:123701 {
danakj8522a25b2016-04-16 00:17:363702 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553703 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123704
[email protected]f7022f32014-08-21 16:32:193705 r->Start();
[email protected]255620da2013-08-19 13:14:293706 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123707
mmenkefe5d0b112016-09-06 20:46:583708 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153709 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193710 EXPECT_TRUE(r->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:583711 EXPECT_THAT(r->status().error(), IsError(ERR_EMPTY_RESPONSE));
[email protected]4c76d7c2011-04-15 19:14:123712 EXPECT_EQ(1, network_delegate.created_requests());
3713 EXPECT_EQ(0, network_delegate.destroyed_requests());
3714 }
3715 EXPECT_EQ(1, network_delegate.destroyed_requests());
3716}
3717
[email protected]b4438d32012-09-27 06:15:303718// Helper function for NetworkDelegateCancelRequestAsynchronously and
3719// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3720// delegate operating in |block_mode| and a request for |url|. It blocks the
3721// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3722void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3723 BlockingNetworkDelegate::Stage stage,
3724 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363725 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303726 BlockingNetworkDelegate network_delegate(block_mode);
3727 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3728 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363729
[email protected]b4438d32012-09-27 06:15:303730 TestURLRequestContext context(true);
3731 context.set_network_delegate(&network_delegate);
3732 context.Init();
[email protected]3cd384c602011-08-31 16:12:363733
3734 {
danakj8522a25b2016-04-16 00:17:363735 std::unique_ptr<URLRequest> r(
3736 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363737
[email protected]f7022f32014-08-21 16:32:193738 r->Start();
[email protected]255620da2013-08-19 13:14:293739 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363740
mmenkefe5d0b112016-09-06 20:46:583741 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153742 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193743 EXPECT_TRUE(r->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:583744 EXPECT_THAT(r->status().error(), IsError(ERR_BLOCKED_BY_CLIENT));
[email protected]3cd384c602011-08-31 16:12:363745 EXPECT_EQ(1, network_delegate.created_requests());
3746 EXPECT_EQ(0, network_delegate.destroyed_requests());
3747 }
3748 EXPECT_EQ(1, network_delegate.destroyed_requests());
3749}
3750
[email protected]b4438d32012-09-27 06:15:303751// The following 3 tests check that the network delegate can cancel a request
3752// synchronously in various stages of the request.
3753TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553754 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303755 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3756 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553757 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303758}
3759
3760TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553761 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303762 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3763 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553764 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303765}
3766
3767TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553768 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303769 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3770 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553771 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303772}
3773
3774// The following 3 tests check that the network delegate can cancel a request
3775// asynchronously in various stages of the request.
3776TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553777 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303778 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3779 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553780 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303781}
3782
3783TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553784 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303785 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3786 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553787 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303788}
3789
3790TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553791 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303792 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3793 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553794 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303795}
3796
[email protected]4c76d7c2011-04-15 19:14:123797// Tests that the network delegate can block and redirect a request to a new
3798// URL.
3799TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553800 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123801
3802 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303803 BlockingNetworkDelegate network_delegate(
3804 BlockingNetworkDelegate::AUTO_CALLBACK);
3805 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553806 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123807 network_delegate.set_redirect_url(redirect_url);
3808
[email protected]d5a4dd62012-05-23 01:41:043809 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553810 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503811
[email protected]4c76d7c2011-04-15 19:14:123812 {
tommycli59a63432015-11-06 00:10:553813 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363814 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363815 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123816
[email protected]6be6fa92014-08-06 23:44:563817 // Quit after hitting the redirect, so can check the headers.
3818 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193819 r->Start();
[email protected]255620da2013-08-19 13:14:293820 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123821
[email protected]6be6fa92014-08-06 23:44:563822 // Check headers from URLRequestJob.
mmenkefe5d0b112016-09-06 20:46:583823 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]f7022f32014-08-21 16:32:193824 EXPECT_EQ(307, r->GetResponseCode());
3825 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563826 std::string location;
[email protected]f7022f32014-08-21 16:32:193827 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3828 &location));
[email protected]6be6fa92014-08-06 23:44:563829 EXPECT_EQ(redirect_url, GURL(location));
3830
3831 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193832 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563833 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:583834 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553835 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093836 // before_send_headers_with_proxy_count only increments for headers sent
3837 // through an untunneled proxy.
3838 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553839 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3840 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273841
mmenkefe5d0b112016-09-06 20:46:583842 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:193843 EXPECT_EQ(redirect_url, r->url());
3844 EXPECT_EQ(original_url, r->original_url());
3845 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123846 EXPECT_EQ(1, network_delegate.created_requests());
3847 EXPECT_EQ(0, network_delegate.destroyed_requests());
3848 }
3849 EXPECT_EQ(1, network_delegate.destroyed_requests());
3850}
3851
[email protected]b813ed72012-04-05 08:21:363852// Tests that the network delegate can block and redirect a request to a new
3853// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3854TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553855 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363856
3857 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303858 BlockingNetworkDelegate network_delegate(
3859 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553860 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363861 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363862
[email protected]d5a4dd62012-05-23 01:41:043863 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553864 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363865
3866 {
tommycli59a63432015-11-06 00:10:553867 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363868 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363869 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363870
[email protected]6be6fa92014-08-06 23:44:563871 // Quit after hitting the redirect, so can check the headers.
3872 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193873 r->Start();
[email protected]255620da2013-08-19 13:14:293874 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363875
[email protected]6be6fa92014-08-06 23:44:563876 // Check headers from URLRequestJob.
mmenkefe5d0b112016-09-06 20:46:583877 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]f7022f32014-08-21 16:32:193878 EXPECT_EQ(307, r->GetResponseCode());
3879 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563880 std::string location;
[email protected]f7022f32014-08-21 16:32:193881 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3882 &location));
[email protected]6be6fa92014-08-06 23:44:563883 EXPECT_EQ(redirect_url, GURL(location));
3884
3885 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193886 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563887 base::RunLoop().Run();
3888
mmenkefe5d0b112016-09-06 20:46:583889 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553890 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093891 // before_send_headers_with_proxy_count only increments for headers sent
3892 // through an untunneled proxy.
3893 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553894 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3895 http_test_server()->host_port_pair()));
mmenkefe5d0b112016-09-06 20:46:583896 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:193897 EXPECT_EQ(redirect_url, r->url());
3898 EXPECT_EQ(original_url, r->original_url());
3899 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363900 EXPECT_EQ(1, network_delegate.created_requests());
3901 EXPECT_EQ(0, network_delegate.destroyed_requests());
3902 }
3903 EXPECT_EQ(1, network_delegate.destroyed_requests());
3904}
3905
[email protected]3c5ca8c2011-09-29 01:14:513906// Tests that redirects caused by the network delegate preserve POST data.
3907TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553908 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513909
3910 const char kData[] = "hello world";
3911
3912 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303913 BlockingNetworkDelegate network_delegate(
3914 BlockingNetworkDelegate::AUTO_CALLBACK);
3915 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553916 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513917 network_delegate.set_redirect_url(redirect_url);
3918
[email protected]ef2bf422012-05-11 03:27:093919 TestURLRequestContext context(true);
3920 context.set_network_delegate(&network_delegate);
3921 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513922
3923 {
tommycli59a63432015-11-06 00:10:553924 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363925 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363926 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193927 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073928 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513929 HttpRequestHeaders headers;
3930 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513931 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193932 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563933
3934 // 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]3c5ca8c2011-09-29 01:14:513938
[email protected]6be6fa92014-08-06 23:44:563939 // Check headers from URLRequestJob.
mmenkefe5d0b112016-09-06 20:46:583940 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]f7022f32014-08-21 16:32:193941 EXPECT_EQ(307, r->GetResponseCode());
3942 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563943 std::string location;
[email protected]f7022f32014-08-21 16:32:193944 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3945 &location));
[email protected]6be6fa92014-08-06 23:44:563946 EXPECT_EQ(redirect_url, GURL(location));
3947
3948 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193949 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563950 base::RunLoop().Run();
3951
mmenkefe5d0b112016-09-06 20:46:583952 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3953 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:193954 EXPECT_EQ(redirect_url, r->url());
3955 EXPECT_EQ(original_url, r->original_url());
3956 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513957 EXPECT_EQ(1, network_delegate.created_requests());
3958 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193959 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513960 EXPECT_EQ(kData, d.data_received());
3961 }
3962 EXPECT_EQ(1, network_delegate.destroyed_requests());
3963}
3964
[email protected]5f714132014-03-26 10:41:163965// Tests that the network delegate can block and redirect a request to a new
3966// URL during OnHeadersReceived.
3967TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553968 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163969
3970 TestDelegate d;
3971 BlockingNetworkDelegate network_delegate(
3972 BlockingNetworkDelegate::AUTO_CALLBACK);
3973 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553974 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163975 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3976
3977 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553978 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163979
3980 {
tommycli59a63432015-11-06 00:10:553981 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363982 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363983 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163984
[email protected]f7022f32014-08-21 16:32:193985 r->Start();
[email protected]5f714132014-03-26 10:41:163986 base::RunLoop().Run();
3987
mmenkefe5d0b112016-09-06 20:46:583988 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553989 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093990 // before_send_headers_with_proxy_count only increments for headers sent
3991 // through an untunneled proxy.
3992 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553993 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3994 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193995
mmenkefe5d0b112016-09-06 20:46:583996 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:193997 EXPECT_EQ(redirect_url, r->url());
3998 EXPECT_EQ(original_url, r->original_url());
3999 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164000 EXPECT_EQ(2, network_delegate.created_requests());
4001 EXPECT_EQ(0, network_delegate.destroyed_requests());
4002 }
4003 EXPECT_EQ(1, network_delegate.destroyed_requests());
4004}
4005
[email protected]c2911d72011-10-03 22:16:364006// Tests that the network delegate can synchronously complete OnAuthRequired
4007// by taking no action. This indicates that the NetworkDelegate does not want to
4008// handle the challenge, and is passing the buck along to the
4009// URLRequest::Delegate.
4010TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554011 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364012
4013 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304014 BlockingNetworkDelegate network_delegate(
4015 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364016
[email protected]ef2bf422012-05-11 03:27:094017 TestURLRequestContext context(true);
4018 context.set_network_delegate(&network_delegate);
4019 context.Init();
[email protected]c2911d72011-10-03 22:16:364020
[email protected]f3cf9802011-10-28 18:44:584021 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364022
4023 {
tommycli59a63432015-11-06 00:10:554024 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364025 std::unique_ptr<URLRequest> r(
4026 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194027 r->Start();
[email protected]79e1fd62013-06-20 06:50:044028
[email protected]255620da2013-08-19 13:14:294029 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044030
mmenkefe5d0b112016-09-06 20:46:584031 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4032 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:194033 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044034 EXPECT_TRUE(d.auth_required_called());
4035 EXPECT_EQ(1, network_delegate.created_requests());
4036 EXPECT_EQ(0, network_delegate.destroyed_requests());
4037 }
4038 EXPECT_EQ(1, network_delegate.destroyed_requests());
4039}
4040
4041TEST_F(URLRequestTestHTTP,
4042 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554043 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044044
4045 TestDelegate d;
4046 BlockingNetworkDelegate network_delegate(
4047 BlockingNetworkDelegate::SYNCHRONOUS);
4048
4049 TestURLRequestContext context(true);
4050 context.set_network_delegate(&network_delegate);
4051 context.Init();
4052
4053 d.set_credentials(AuthCredentials(kUser, kSecret));
4054
4055 {
tommycli59a63432015-11-06 00:10:554056 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364057 std::unique_ptr<URLRequest> r(
4058 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194059 r->Start();
[email protected]79e1fd62013-06-20 06:50:044060
4061 {
4062 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194063 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044064 EXPECT_FALSE(headers.HasHeader("Authorization"));
4065 }
4066
[email protected]255620da2013-08-19 13:14:294067 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364068
mmenkefe5d0b112016-09-06 20:46:584069 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4070 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:194071 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364072 EXPECT_TRUE(d.auth_required_called());
4073 EXPECT_EQ(1, network_delegate.created_requests());
4074 EXPECT_EQ(0, network_delegate.destroyed_requests());
4075 }
4076 EXPECT_EQ(1, network_delegate.destroyed_requests());
4077}
4078
4079// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404080// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364081TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554082 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364083
4084 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304085 BlockingNetworkDelegate network_delegate(
4086 BlockingNetworkDelegate::SYNCHRONOUS);
4087 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364088 network_delegate.set_auth_retval(
4089 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4090
[email protected]f3cf9802011-10-28 18:44:584091 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364092
[email protected]ef2bf422012-05-11 03:27:094093 TestURLRequestContext context(true);
4094 context.set_network_delegate(&network_delegate);
4095 context.Init();
[email protected]c2911d72011-10-03 22:16:364096
4097 {
tommycli59a63432015-11-06 00:10:554098 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364099 std::unique_ptr<URLRequest> r(
4100 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194101 r->Start();
[email protected]255620da2013-08-19 13:14:294102 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364103
mmenkefe5d0b112016-09-06 20:46:584104 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4105 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:194106 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364107 EXPECT_FALSE(d.auth_required_called());
4108 EXPECT_EQ(1, network_delegate.created_requests());
4109 EXPECT_EQ(0, network_delegate.destroyed_requests());
4110 }
4111 EXPECT_EQ(1, network_delegate.destroyed_requests());
4112}
4113
[email protected]79e1fd62013-06-20 06:50:044114// Same as above, but also tests that GetFullRequestHeaders returns the proper
4115// headers (for the first or second request) when called at the proper times.
4116TEST_F(URLRequestTestHTTP,
4117 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554118 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044119
4120 TestDelegate d;
4121 BlockingNetworkDelegate network_delegate(
4122 BlockingNetworkDelegate::SYNCHRONOUS);
4123 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4124 network_delegate.set_auth_retval(
4125 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4126
4127 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4128
4129 TestURLRequestContext context(true);
4130 context.set_network_delegate(&network_delegate);
4131 context.Init();
4132
4133 {
tommycli59a63432015-11-06 00:10:554134 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364135 std::unique_ptr<URLRequest> r(
4136 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194137 r->Start();
[email protected]255620da2013-08-19 13:14:294138 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044139
mmenkefe5d0b112016-09-06 20:46:584140 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4141 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:194142 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044143 EXPECT_FALSE(d.auth_required_called());
4144 EXPECT_EQ(1, network_delegate.created_requests());
4145 EXPECT_EQ(0, network_delegate.destroyed_requests());
4146
4147 {
4148 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194149 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044150 EXPECT_TRUE(headers.HasHeader("Authorization"));
4151 }
4152 }
4153 EXPECT_EQ(1, network_delegate.destroyed_requests());
4154}
4155
[email protected]c2911d72011-10-03 22:16:364156// Tests that the network delegate can synchronously complete OnAuthRequired
4157// by cancelling authentication.
4158TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554159 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364160
4161 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304162 BlockingNetworkDelegate network_delegate(
4163 BlockingNetworkDelegate::SYNCHRONOUS);
4164 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364165 network_delegate.set_auth_retval(
4166 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4167
[email protected]ef2bf422012-05-11 03:27:094168 TestURLRequestContext context(true);
4169 context.set_network_delegate(&network_delegate);
4170 context.Init();
[email protected]c2911d72011-10-03 22:16:364171
4172 {
tommycli59a63432015-11-06 00:10:554173 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364174 std::unique_ptr<URLRequest> r(
4175 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194176 r->Start();
[email protected]255620da2013-08-19 13:14:294177 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364178
mmenkefe5d0b112016-09-06 20:46:584179 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4180 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:194181 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364182 EXPECT_FALSE(d.auth_required_called());
4183 EXPECT_EQ(1, network_delegate.created_requests());
4184 EXPECT_EQ(0, network_delegate.destroyed_requests());
4185 }
4186 EXPECT_EQ(1, network_delegate.destroyed_requests());
4187}
4188
4189// Tests that the network delegate can asynchronously complete OnAuthRequired
4190// by taking no action. This indicates that the NetworkDelegate does not want
4191// to handle the challenge, and is passing the buck along to the
4192// URLRequest::Delegate.
4193TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554194 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364195
4196 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304197 BlockingNetworkDelegate network_delegate(
4198 BlockingNetworkDelegate::AUTO_CALLBACK);
4199 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364200
[email protected]ef2bf422012-05-11 03:27:094201 TestURLRequestContext context(true);
4202 context.set_network_delegate(&network_delegate);
4203 context.Init();
[email protected]c2911d72011-10-03 22:16:364204
[email protected]f3cf9802011-10-28 18:44:584205 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364206
4207 {
tommycli59a63432015-11-06 00:10:554208 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364209 std::unique_ptr<URLRequest> r(
4210 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194211 r->Start();
[email protected]255620da2013-08-19 13:14:294212 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364213
mmenkefe5d0b112016-09-06 20:46:584214 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4215 EXPECT_EQ(0, r->status().error());
[email protected]f7022f32014-08-21 16:32:194216 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364217 EXPECT_TRUE(d.auth_required_called());
4218 EXPECT_EQ(1, network_delegate.created_requests());
4219 EXPECT_EQ(0, network_delegate.destroyed_requests());
4220 }
4221 EXPECT_EQ(1, network_delegate.destroyed_requests());
4222}
4223
4224// Tests that the network delegate can asynchronously complete OnAuthRequired
4225// by setting credentials.
4226TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554227 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364228
4229 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304230 BlockingNetworkDelegate network_delegate(
4231 BlockingNetworkDelegate::AUTO_CALLBACK);
4232 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364233 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364234 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4235
[email protected]f3cf9802011-10-28 18:44:584236 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364237 network_delegate.set_auth_credentials(auth_credentials);
4238
[email protected]ef2bf422012-05-11 03:27:094239 TestURLRequestContext context(true);
4240 context.set_network_delegate(&network_delegate);
4241 context.Init();
[email protected]c2911d72011-10-03 22:16:364242
4243 {
tommycli59a63432015-11-06 00:10:554244 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364245 std::unique_ptr<URLRequest> r(
4246 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194247 r->Start();
[email protected]255620da2013-08-19 13:14:294248 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364249
mmenkefe5d0b112016-09-06 20:46:584250 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4251 EXPECT_EQ(0, r->status().error());
4252
[email protected]f7022f32014-08-21 16:32:194253 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364254 EXPECT_FALSE(d.auth_required_called());
4255 EXPECT_EQ(1, network_delegate.created_requests());
4256 EXPECT_EQ(0, network_delegate.destroyed_requests());
4257 }
4258 EXPECT_EQ(1, network_delegate.destroyed_requests());
4259}
4260
4261// Tests that the network delegate can asynchronously complete OnAuthRequired
4262// by cancelling authentication.
4263TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554264 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364265
4266 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304267 BlockingNetworkDelegate network_delegate(
4268 BlockingNetworkDelegate::AUTO_CALLBACK);
4269 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364270 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364271 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4272
[email protected]ef2bf422012-05-11 03:27:094273 TestURLRequestContext context(true);
4274 context.set_network_delegate(&network_delegate);
4275 context.Init();
[email protected]c2911d72011-10-03 22:16:364276
4277 {
tommycli59a63432015-11-06 00:10:554278 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364279 std::unique_ptr<URLRequest> r(
4280 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194281 r->Start();
[email protected]255620da2013-08-19 13:14:294282 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364283
mmenkefe5d0b112016-09-06 20:46:584284 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4285 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:194286 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364287 EXPECT_FALSE(d.auth_required_called());
4288 EXPECT_EQ(1, network_delegate.created_requests());
4289 EXPECT_EQ(0, network_delegate.destroyed_requests());
4290 }
4291 EXPECT_EQ(1, network_delegate.destroyed_requests());
4292}
4293
[email protected]9045b8822012-01-13 20:35:354294// Tests that we can handle when a network request was canceled while we were
4295// waiting for the network delegate.
4296// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4297TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554298 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354299
4300 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304301 BlockingNetworkDelegate network_delegate(
4302 BlockingNetworkDelegate::USER_CALLBACK);
4303 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354304
[email protected]ef2bf422012-05-11 03:27:094305 TestURLRequestContext context(true);
4306 context.set_network_delegate(&network_delegate);
4307 context.Init();
[email protected]9045b8822012-01-13 20:35:354308
4309 {
danakj8522a25b2016-04-16 00:17:364310 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554311 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354312
[email protected]f7022f32014-08-21 16:32:194313 r->Start();
[email protected]255620da2013-08-19 13:14:294314 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304315 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4316 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354317 EXPECT_EQ(0, network_delegate.completed_requests());
4318 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194319 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354320 // Ensure that network delegate is notified.
4321 EXPECT_EQ(1, network_delegate.completed_requests());
mmenkefe5d0b112016-09-06 20:46:584322 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4323 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354324 EXPECT_EQ(1, network_delegate.created_requests());
4325 EXPECT_EQ(0, network_delegate.destroyed_requests());
4326 }
4327 EXPECT_EQ(1, network_delegate.destroyed_requests());
4328}
4329
4330// Tests that we can handle when a network request was canceled while we were
4331// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004332// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4333// callback.
[email protected]9045b8822012-01-13 20:35:354334TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554335 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354336
4337 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304338 BlockingNetworkDelegate network_delegate(
4339 BlockingNetworkDelegate::USER_CALLBACK);
4340 network_delegate.set_block_on(
4341 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354342
[email protected]ef2bf422012-05-11 03:27:094343 TestURLRequestContext context(true);
4344 context.set_network_delegate(&network_delegate);
4345 context.Init();
[email protected]9045b8822012-01-13 20:35:354346
4347 {
danakj8522a25b2016-04-16 00:17:364348 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554349 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354350
[email protected]f7022f32014-08-21 16:32:194351 r->Start();
[email protected]255620da2013-08-19 13:14:294352 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304353 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4354 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354355 EXPECT_EQ(0, network_delegate.completed_requests());
4356 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194357 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354358 // Ensure that network delegate is notified.
4359 EXPECT_EQ(1, network_delegate.completed_requests());
mmenkefe5d0b112016-09-06 20:46:584360 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4361 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354362 EXPECT_EQ(1, network_delegate.created_requests());
4363 EXPECT_EQ(0, network_delegate.destroyed_requests());
4364 }
4365 EXPECT_EQ(1, network_delegate.destroyed_requests());
4366}
4367
4368// Tests that we can handle when a network request was canceled while we were
4369// waiting for the network delegate.
4370// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4371TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554372 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354373
4374 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304375 BlockingNetworkDelegate network_delegate(
4376 BlockingNetworkDelegate::USER_CALLBACK);
4377 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354378
[email protected]ef2bf422012-05-11 03:27:094379 TestURLRequestContext context(true);
4380 context.set_network_delegate(&network_delegate);
4381 context.Init();
[email protected]9045b8822012-01-13 20:35:354382
4383 {
danakj8522a25b2016-04-16 00:17:364384 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554385 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354386
[email protected]f7022f32014-08-21 16:32:194387 r->Start();
[email protected]255620da2013-08-19 13:14:294388 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304389 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4390 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354391 EXPECT_EQ(0, network_delegate.completed_requests());
4392 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194393 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354394 // Ensure that network delegate is notified.
4395 EXPECT_EQ(1, network_delegate.completed_requests());
mmenkefe5d0b112016-09-06 20:46:584396 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4397 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354398 EXPECT_EQ(1, network_delegate.created_requests());
4399 EXPECT_EQ(0, network_delegate.destroyed_requests());
4400 }
4401 EXPECT_EQ(1, network_delegate.destroyed_requests());
4402}
4403
4404// Tests that we can handle when a network request was canceled while we were
4405// waiting for the network delegate.
4406// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024407TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554408 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354409
4410 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304411 BlockingNetworkDelegate network_delegate(
4412 BlockingNetworkDelegate::USER_CALLBACK);
4413 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354414
[email protected]ef2bf422012-05-11 03:27:094415 TestURLRequestContext context(true);
4416 context.set_network_delegate(&network_delegate);
4417 context.Init();
[email protected]9045b8822012-01-13 20:35:354418
4419 {
danakj8522a25b2016-04-16 00:17:364420 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554421 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354422
[email protected]f7022f32014-08-21 16:32:194423 r->Start();
[email protected]255620da2013-08-19 13:14:294424 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304425 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4426 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354427 EXPECT_EQ(0, network_delegate.completed_requests());
4428 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194429 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354430 // Ensure that network delegate is notified.
4431 EXPECT_EQ(1, network_delegate.completed_requests());
mmenkefe5d0b112016-09-06 20:46:584432 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4433 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354434 EXPECT_EQ(1, network_delegate.created_requests());
4435 EXPECT_EQ(0, network_delegate.destroyed_requests());
4436 }
4437 EXPECT_EQ(1, network_delegate.destroyed_requests());
4438}
4439
tommycli59a63432015-11-06 00:10:554440namespace {
4441
danakj8522a25b2016-04-16 00:17:364442std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554443 const test_server::HttpRequest& request) {
4444 if (request.headers.find("Host") == request.headers.end() ||
4445 request.headers.at("Host") != "www.server-auth.com" ||
4446 request.method != test_server::METHOD_CONNECT) {
4447 return nullptr;
4448 }
4449
danakj8522a25b2016-04-16 00:17:364450 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554451 new test_server::BasicHttpResponse);
4452 http_response->set_code(HTTP_UNAUTHORIZED);
4453 http_response->AddCustomHeader("WWW-Authenticate",
4454 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484455 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554456}
4457
4458} // namespace
4459
4460// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114461// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554462// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354463TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554464 http_test_server()->RegisterRequestHandler(
4465 base::Bind(&HandleServerAuthConnect));
4466 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114467
[email protected]ceefd7fd2012-11-29 00:36:244468 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044469 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554470 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504471
[email protected]dc651782009-02-14 01:45:084472 TestDelegate d;
4473 {
danakj8522a25b2016-04-16 00:17:364474 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364475 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084476
[email protected]f7022f32014-08-21 16:32:194477 r->Start();
4478 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084479
[email protected]255620da2013-08-19 13:14:294480 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084481
mmenkefe5d0b112016-09-06 20:46:584482 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154483 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194484 EXPECT_TRUE(r->proxy_server().IsEmpty());
mmenkefe5d0b112016-09-06 20:46:584485 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]dc651782009-02-14 01:45:084486 }
4487}
4488
[email protected]b89290212009-08-14 22:37:354489TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554490 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114491
initial.commit586acc5fe2008-07-26 22:42:524492 TestDelegate d;
4493 {
danakj8522a25b2016-04-16 00:17:364494 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554495 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524496
[email protected]f7022f32014-08-21 16:32:194497 r->Start();
4498 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524499
[email protected]255620da2013-08-19 13:14:294500 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524501
4502 EXPECT_EQ(1, d.response_started_count());
4503 EXPECT_FALSE(d.received_data_before_response());
4504 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554505 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194506 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554507 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194508 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164509
[email protected]9e743cd2010-03-16 07:03:534510 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524511 }
initial.commit586acc5fe2008-07-26 22:42:524512}
4513
[email protected]263163f2012-06-14 22:40:344514// This test has the server send a large number of cookies to the client.
4515// To ensure that no number of cookies causes a crash, a galloping binary
4516// search is used to estimate that maximum number of cookies that are accepted
4517// by the browser. Beyond the maximum number, the request will fail with
4518// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304519#if defined(OS_WIN)
4520// http://crbug.com/177916
4521#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4522#else
4523#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4524#endif // defined(OS_WIN)
4525TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554526 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344527
4528 int lower_bound = 0;
4529 int upper_bound = 1;
4530
4531 // Double the number of cookies until the response header limits are
4532 // exceeded.
4533 while (DoManyCookiesRequest(upper_bound)) {
4534 lower_bound = upper_bound;
4535 upper_bound *= 2;
4536 ASSERT_LT(upper_bound, 1000000);
4537 }
4538
pkasting6b68a162014-12-01 22:10:294539 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344540 if (tolerance < 2)
4541 tolerance = 2;
4542
4543 // Perform a binary search to find the highest possible number of cookies,
4544 // within the desired tolerance.
4545 while (upper_bound - lower_bound >= tolerance) {
4546 int num_cookies = (lower_bound + upper_bound) / 2;
4547
4548 if (DoManyCookiesRequest(num_cookies))
4549 lower_bound = num_cookies;
4550 else
4551 upper_bound = num_cookies;
4552 }
4553 // Success: the test did not crash.
4554}
4555
[email protected]b89290212009-08-14 22:37:354556TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554557 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114558
initial.commit586acc5fe2008-07-26 22:42:524559 TestDelegate d;
4560 {
danakj8522a25b2016-04-16 00:17:364561 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554562 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524563
[email protected]f7022f32014-08-21 16:32:194564 r->Start();
4565 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524566
[email protected]255620da2013-08-19 13:14:294567 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524568
4569 EXPECT_EQ(1, d.response_started_count());
4570 EXPECT_FALSE(d.received_data_before_response());
4571 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554572 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194573 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554574 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194575 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524576 }
[email protected]5d7b373e2009-09-02 07:19:034577}
4578
[email protected]79e1fd62013-06-20 06:50:044579TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554580 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044581
4582 TestDelegate d;
4583 {
tommycli59a63432015-11-06 00:10:554584 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364585 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364586 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044587
4588 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194589 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044590
[email protected]f7022f32014-08-21 16:32:194591 r->Start();
4592 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044593
[email protected]255620da2013-08-19 13:14:294594 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044595
4596 EXPECT_EQ(1, d.response_started_count());
4597 EXPECT_FALSE(d.received_data_before_response());
4598 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554599 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194600 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554601 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194602 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044603
4604 EXPECT_TRUE(d.have_full_request_headers());
4605 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4606 }
4607}
4608
[email protected]58e32bb2013-01-21 18:23:254609TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554610 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254611
4612 TestDelegate d;
4613 {
danakj8522a25b2016-04-16 00:17:364614 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554615 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254616
[email protected]f7022f32014-08-21 16:32:194617 r->Start();
4618 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254619
[email protected]255620da2013-08-19 13:14:294620 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254621
4622 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194623 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254624 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4625
4626 EXPECT_EQ(1, d.response_started_count());
4627 EXPECT_FALSE(d.received_data_before_response());
4628 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554629 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194630 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554631 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194632 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254633 }
4634}
4635
tommycli59a63432015-11-06 00:10:554636// TODO(svaldez): Update tests to use EmbeddedTestServer.
4637#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394638TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554639 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4640 SpawnedTestServer::kLocalhost,
4641 base::FilePath(kTestFilePath));
4642
4643 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394644
4645 // Parameter that specifies the Content-Length field in the response:
4646 // C - Compressed length.
4647 // U - Uncompressed length.
4648 // L - Large length (larger than both C & U).
4649 // M - Medium length (between C & U).
4650 // S - Small length (smaller than both C & U).
4651 const char test_parameters[] = "CULMS";
4652 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4653 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444654 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394655 // S has too little data, but we seem to accept it.
4656 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374657 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394658
xunjielifb4da222016-07-14 18:38:594659 base::FilePath file_path;
4660 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
4661 file_path = file_path.Append(kTestFilePath);
4662 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
4663 std::string expected_content;
4664 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
4665
4666 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:394667 TestDelegate d;
4668 {
tommycli59a63432015-11-06 00:10:554669 std::string test_file = base::StringPrintf(
4670 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394671
[email protected]ceefd7fd2012-11-29 00:36:244672 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094673 TestURLRequestContext context(true);
4674 context.set_network_delegate(&network_delegate);
4675 context.Init();
[email protected]87a09a92011-07-14 15:50:504676
danakj8522a25b2016-04-16 00:17:364677 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554678 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194679 r->Start();
4680 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394681
[email protected]255620da2013-08-19 13:14:294682 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394683
4684 EXPECT_EQ(1, d.response_started_count());
4685 EXPECT_FALSE(d.received_data_before_response());
4686 VLOG(1) << " Received " << d.bytes_received() << " bytes"
mmenkefe5d0b112016-09-06 20:46:584687 << " status = " << r->status().status()
4688 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394689 if (test_expect_success[i]) {
mmenkefe5d0b112016-09-06 20:46:584690 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
4691 << " Parameter = \"" << test_file << "\"";
xunjielifb4da222016-07-14 18:38:594692 if (test_parameters[i] == 'S') {
4693 // When content length is smaller than both compressed length and
4694 // uncompressed length, HttpStreamParser might not read the full
4695 // response body.
4696 continue;
4697 }
4698 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:394699 } else {
mmenkefe5d0b112016-09-06 20:46:584700 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4701 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394702 << " Parameter = \"" << test_file << "\"";
4703 }
4704 }
4705 }
4706}
tommycli59a63432015-11-06 00:10:554707#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394708
[email protected]58e32bb2013-01-21 18:23:254709TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554710 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254711
tommycli59a63432015-11-06 00:10:554712 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454713 GURL original_url =
tommycli59a63432015-11-06 00:10:554714 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254715 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364716 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364717 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194718 req->Start();
[email protected]255620da2013-08-19 13:14:294719 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254720
4721 EXPECT_EQ(1, d.response_started_count());
4722 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194723 EXPECT_EQ(destination_url, req->url());
4724 EXPECT_EQ(original_url, req->original_url());
4725 ASSERT_EQ(2U, req->url_chain().size());
4726 EXPECT_EQ(original_url, req->url_chain()[0]);
4727 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254728
4729 LoadTimingInfo load_timing_info_before_redirect;
4730 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4731 &load_timing_info_before_redirect));
4732 TestLoadTimingNotReused(load_timing_info_before_redirect,
4733 CONNECT_TIMING_HAS_DNS_TIMES);
4734
4735 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194736 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254737 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4738
4739 // Check that a new socket was used on redirect, since the server does not
4740 // supposed keep-alive sockets, and that the times before the redirect are
4741 // before the ones recorded for the second request.
4742 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4743 load_timing_info.socket_log_id);
4744 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4745 load_timing_info.connect_timing.connect_start);
4746}
4747
[email protected]8f1ac082011-04-19 21:14:134748TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554749 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134750
tommycli59a63432015-11-06 00:10:554751 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454752 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554753 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4754 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4755 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134756 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364757 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364758 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194759 req->Start();
[email protected]255620da2013-08-19 13:14:294760 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134761
4762 EXPECT_EQ(1, d.response_started_count());
4763 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194764 EXPECT_EQ(destination_url, req->url());
4765 EXPECT_EQ(original_url, req->original_url());
4766 ASSERT_EQ(3U, req->url_chain().size());
4767 EXPECT_EQ(original_url, req->url_chain()[0]);
4768 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4769 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134770}
4771
[email protected]abe1c4a2013-10-25 19:28:514772// First and second pieces of information logged by delegates to URLRequests.
4773const char kFirstDelegateInfo[] = "Wonderful delegate";
4774const char kSecondDelegateInfo[] = "Exciting delegate";
4775
4776// Logs delegate information to a URLRequest. The first string is logged
4777// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4778// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4779// another asynchronous call is used to clear the delegate information
4780// before calling a callback. The object then deletes itself.
4781class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4782 public:
4783 typedef base::Callback<void()> Callback;
4784
4785 // Each time delegate information is added to the URLRequest, the resulting
4786 // load state is checked. The expected load state after each request is
4787 // passed in as an argument.
4788 static void Run(URLRequest* url_request,
4789 LoadState expected_first_load_state,
4790 LoadState expected_second_load_state,
4791 LoadState expected_third_load_state,
4792 const Callback& callback) {
4793 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4794 url_request,
4795 expected_first_load_state,
4796 expected_second_load_state,
4797 expected_third_load_state,
4798 callback);
4799 logger->Start();
4800 }
4801
4802 // Checks that the log entries, starting with log_position, contain the
4803 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4804 // recorded. Returns the index of entry after the expected number of
4805 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464806 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514807 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514808 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4809 if (log_position + 3 >= entries.size()) {
4810 ADD_FAILURE() << "Not enough log entries";
4811 return entries.size();
4812 }
4813 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:004814 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4815 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514816 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4817 &delegate_info));
4818 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4819
4820 ++log_position;
mikecirone8b85c432016-09-08 19:11:004821 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4822 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514823
4824 ++log_position;
mikecirone8b85c432016-09-08 19:11:004825 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4826 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514827 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4828 &delegate_info));
4829 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4830
4831 ++log_position;
mikecirone8b85c432016-09-08 19:11:004832 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4833 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514834
4835 return log_position + 1;
4836 }
4837
4838 private:
4839 friend class base::RefCounted<AsyncDelegateLogger>;
4840
4841 AsyncDelegateLogger(URLRequest* url_request,
4842 LoadState expected_first_load_state,
4843 LoadState expected_second_load_state,
4844 LoadState expected_third_load_state,
4845 const Callback& callback)
4846 : url_request_(url_request),
4847 expected_first_load_state_(expected_first_load_state),
4848 expected_second_load_state_(expected_second_load_state),
4849 expected_third_load_state_(expected_third_load_state),
4850 callback_(callback) {
4851 }
4852
4853 ~AsyncDelegateLogger() {}
4854
4855 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534856 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514857 LoadStateWithParam load_state = url_request_->GetLoadState();
4858 EXPECT_EQ(expected_first_load_state_, load_state.state);
4859 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454860 base::ThreadTaskRunnerHandle::Get()->PostTask(
4861 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514862 }
4863
4864 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534865 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514866 LoadStateWithParam load_state = url_request_->GetLoadState();
4867 EXPECT_EQ(expected_second_load_state_, load_state.state);
4868 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4869 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4870 } else {
4871 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4872 }
skyostil4891b25b2015-06-11 11:43:454873 base::ThreadTaskRunnerHandle::Get()->PostTask(
4874 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514875 }
4876
4877 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534878 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514879 LoadStateWithParam load_state = url_request_->GetLoadState();
4880 EXPECT_EQ(expected_third_load_state_, load_state.state);
4881 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084882 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514883 callback_.Run();
4884 }
4885
4886 URLRequest* url_request_;
4887 const int expected_first_load_state_;
4888 const int expected_second_load_state_;
4889 const int expected_third_load_state_;
4890 const Callback callback_;
4891
4892 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4893};
4894
4895// NetworkDelegate that logs delegate information before a request is started,
4896// before headers are sent, when headers are read, and when auth information
4897// is requested. Uses AsyncDelegateLogger.
4898class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4899 public:
4900 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204901 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514902
4903 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204904 int OnBeforeURLRequest(URLRequest* request,
4905 const CompletionCallback& callback,
4906 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514907 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4908 return RunCallbackAsynchronously(request, callback);
4909 }
4910
ryansturm2343cb62016-06-15 01:09:004911 int OnBeforeStartTransaction(URLRequest* request,
4912 const CompletionCallback& callback,
4913 HttpRequestHeaders* headers) override {
4914 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514915 return RunCallbackAsynchronously(request, callback);
4916 }
4917
dchengb03027d2014-10-21 12:00:204918 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514919 URLRequest* request,
4920 const CompletionCallback& callback,
4921 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164922 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134923 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164924 TestNetworkDelegate::OnHeadersReceived(request,
4925 callback,
[email protected]abe1c4a2013-10-25 19:28:514926 original_response_headers,
[email protected]5f714132014-03-26 10:41:164927 override_response_headers,
4928 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514929 return RunCallbackAsynchronously(request, callback);
4930 }
4931
dchengb03027d2014-10-21 12:00:204932 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514933 URLRequest* request,
4934 const AuthChallengeInfo& auth_info,
4935 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134936 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514937 AsyncDelegateLogger::Run(
4938 request,
4939 LOAD_STATE_WAITING_FOR_DELEGATE,
4940 LOAD_STATE_WAITING_FOR_DELEGATE,
4941 LOAD_STATE_WAITING_FOR_DELEGATE,
4942 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4943 callback, credentials));
4944 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4945 }
4946
4947 private:
4948 static int RunCallbackAsynchronously(
4949 URLRequest* request,
4950 const CompletionCallback& callback) {
4951 AsyncDelegateLogger::Run(
4952 request,
4953 LOAD_STATE_WAITING_FOR_DELEGATE,
4954 LOAD_STATE_WAITING_FOR_DELEGATE,
4955 LOAD_STATE_WAITING_FOR_DELEGATE,
4956 base::Bind(callback, OK));
4957 return ERR_IO_PENDING;
4958 }
4959
4960 static void SetAuthAndResume(const AuthCallback& callback,
4961 AuthCredentials* credentials) {
4962 *credentials = AuthCredentials(kUser, kSecret);
4963 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4964 }
4965
4966 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4967};
4968
4969// URLRequest::Delegate that logs delegate information when the headers
4970// are received, when each read completes, and during redirects. Uses
4971// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4972//
4973// Inherits from TestDelegate to reuse the TestDelegate code to handle
4974// advancing to the next step in most cases, as well as cancellation.
4975class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4976 public:
4977 enum CancelStage {
4978 NO_CANCEL = 0,
4979 CANCEL_ON_RECEIVED_REDIRECT,
4980 CANCEL_ON_RESPONSE_STARTED,
4981 CANCEL_ON_READ_COMPLETED
4982 };
4983
4984 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4985 : cancel_stage_(cancel_stage) {
4986 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4987 set_cancel_in_received_redirect(true);
4988 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4989 set_cancel_in_response_started(true);
4990 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4991 set_cancel_in_received_data(true);
4992 }
dchengb03027d2014-10-21 12:00:204993 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514994
4995 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204996 void OnReceivedRedirect(URLRequest* request,
4997 const RedirectInfo& redirect_info,
4998 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514999 *defer_redirect = true;
5000 AsyncDelegateLogger::Run(
5001 request,
5002 LOAD_STATE_WAITING_FOR_DELEGATE,
5003 LOAD_STATE_WAITING_FOR_DELEGATE,
5004 LOAD_STATE_WAITING_FOR_DELEGATE,
5005 base::Bind(
5006 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595007 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515008 }
5009
maksim.sisov0f4aa142016-09-05 05:55:285010 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515011 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285012 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5013 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5014 base::Bind(
5015 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5016 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515017 }
5018
dchengb03027d2014-10-21 12:00:205019 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515020 AsyncDelegateLogger::Run(
5021 request,
5022 LOAD_STATE_IDLE,
5023 LOAD_STATE_IDLE,
5024 LOAD_STATE_IDLE,
5025 base::Bind(
5026 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5027 base::Unretained(this), request, bytes_read));
5028 }
5029
5030 private:
5031 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595032 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515033 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595034 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515035 // FollowDeferredRedirect should not be called after cancellation.
5036 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5037 return;
5038 if (!defer_redirect)
5039 request->FollowDeferredRedirect();
5040 }
5041
maksim.sisov0f4aa142016-09-05 05:55:285042 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515043 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285044 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515045 }
5046
5047 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5048 // The parent class continues the request.
5049 TestDelegate::OnReadCompleted(request, bytes_read);
5050 }
5051
5052 const CancelStage cancel_stage_;
5053
5054 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5055};
5056
5057// Tests handling of delegate info before a request starts.
5058TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555059 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515060
5061 TestDelegate request_delegate;
5062 TestURLRequestContext context(true);
5063 context.set_network_delegate(NULL);
5064 context.set_net_log(&net_log_);
5065 context.Init();
5066
5067 {
danakj8522a25b2016-04-16 00:17:365068 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555069 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365070 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195071 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515072 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085073 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515074
5075 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195076 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515077 LOAD_STATE_WAITING_FOR_DELEGATE,
5078 LOAD_STATE_WAITING_FOR_DELEGATE,
5079 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195080 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515081
5082 base::RunLoop().Run();
5083
[email protected]f7022f32014-08-21 16:32:195084 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585085 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515086 }
5087
mmenke43758e62015-05-04 21:09:465088 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515089 net_log_.GetEntries(&entries);
5090 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005091 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515092
5093 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5094
5095 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005096 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5097 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515098}
5099
5100// Tests handling of delegate info from a network delegate.
5101TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555102 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515103
5104 TestDelegate request_delegate;
5105 AsyncLoggingNetworkDelegate network_delegate;
5106 TestURLRequestContext context(true);
5107 context.set_network_delegate(&network_delegate);
5108 context.set_net_log(&net_log_);
5109 context.Init();
5110
5111 {
danakj8522a25b2016-04-16 00:17:365112 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555113 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365114 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195115 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515116 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085117 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515118
[email protected]f7022f32014-08-21 16:32:195119 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515120 base::RunLoop().Run();
5121
[email protected]f7022f32014-08-21 16:32:195122 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585123 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515124 EXPECT_EQ(1, network_delegate.created_requests());
5125 EXPECT_EQ(0, network_delegate.destroyed_requests());
5126 }
5127 EXPECT_EQ(1, network_delegate.destroyed_requests());
5128
5129 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465130 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515131 net_log_.GetEntries(&entries);
5132 for (size_t i = 0; i < 3; ++i) {
5133 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005134 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5135 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515136
5137 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5138 log_position + 1);
5139
5140 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005141 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5142 entries[log_position].type);
5143 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515144 }
5145
mikecirone8b85c432016-09-08 19:11:005146 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5147 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515148}
5149
5150// Tests handling of delegate info from a network delegate in the case of an
5151// HTTP redirect.
5152TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555153 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515154
5155 TestDelegate request_delegate;
5156 AsyncLoggingNetworkDelegate network_delegate;
5157 TestURLRequestContext context(true);
5158 context.set_network_delegate(&network_delegate);
5159 context.set_net_log(&net_log_);
5160 context.Init();
5161
5162 {
danakj8522a25b2016-04-16 00:17:365163 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555164 http_test_server()->GetURL("/server-redirect?simple.html"),
5165 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195166 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515167 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085168 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515169
[email protected]f7022f32014-08-21 16:32:195170 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515171 base::RunLoop().Run();
5172
[email protected]f7022f32014-08-21 16:32:195173 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585174 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515175 EXPECT_EQ(2, network_delegate.created_requests());
5176 EXPECT_EQ(0, network_delegate.destroyed_requests());
5177 }
5178 EXPECT_EQ(1, network_delegate.destroyed_requests());
5179
5180 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465181 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515182 net_log_.GetEntries(&entries);
5183 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005184 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515185 for (size_t i = 0; i < 3; ++i) {
5186 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005187 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5188 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515189
5190 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5191 log_position + 1);
5192
5193 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005194 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5195 entries[log_position].type);
5196 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515197 }
5198
5199 // The URLRequest::Delegate then gets informed about the redirect.
5200 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005201 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5202 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515203
5204 // The NetworkDelegate logged information in the same three events as before.
5205 for (size_t i = 0; i < 3; ++i) {
5206 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005207 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5208 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515209
5210 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5211 log_position + 1);
5212
5213 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005214 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5215 entries[log_position].type);
5216 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515217 }
5218
mikecirone8b85c432016-09-08 19:11:005219 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5220 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515221}
5222
5223// Tests handling of delegate info from a network delegate in the case of HTTP
5224// AUTH.
5225TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555226 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515227
5228 TestDelegate request_delegate;
5229 AsyncLoggingNetworkDelegate network_delegate;
5230 TestURLRequestContext context(true);
5231 context.set_network_delegate(&network_delegate);
5232 context.set_net_log(&net_log_);
5233 context.Init();
5234
5235 {
danakj8522a25b2016-04-16 00:17:365236 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555237 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365238 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195239 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515240 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085241 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515242
[email protected]f7022f32014-08-21 16:32:195243 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515244 base::RunLoop().Run();
5245
[email protected]f7022f32014-08-21 16:32:195246 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585247 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515248 EXPECT_EQ(1, network_delegate.created_requests());
5249 EXPECT_EQ(0, network_delegate.destroyed_requests());
5250 }
5251 EXPECT_EQ(1, network_delegate.destroyed_requests());
5252
5253 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465254 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515255 net_log_.GetEntries(&entries);
5256 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005257 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5258 // in
5259 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515260 for (size_t i = 0; i < 6; ++i) {
5261 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005262 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5263 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515264
5265 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5266 log_position + 1);
5267
5268 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005269 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5270 entries[log_position].type);
5271 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515272 }
5273
mikecirone8b85c432016-09-08 19:11:005274 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5275 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515276}
5277
tommycli59a63432015-11-06 00:10:555278// TODO(svaldez): Update tests to use EmbeddedTestServer.
5279#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515280// Tests handling of delegate info from a URLRequest::Delegate.
5281TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555282 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5283 SpawnedTestServer::kLocalhost,
5284 base::FilePath(kTestFilePath));
5285
5286 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515287
5288 AsyncLoggingUrlRequestDelegate request_delegate(
5289 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5290 TestURLRequestContext context(true);
5291 context.set_network_delegate(NULL);
5292 context.set_net_log(&net_log_);
5293 context.Init();
5294
5295 {
5296 // A chunked response with delays between chunks is used to make sure that
5297 // attempts by the URLRequest delegate to log information while reading the
5298 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485299 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515300 // that it occurs.
danakj8522a25b2016-04-16 00:17:365301 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555302 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365303 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195304 LoadStateWithParam load_state = r->GetLoadState();
5305 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515306 base::RunLoop().Run();
5307
[email protected]f7022f32014-08-21 16:32:195308 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585309 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515310 }
5311
mmenke43758e62015-05-04 21:09:465312 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515313 net_log_.GetEntries(&entries);
5314
[email protected]1826a402014-01-08 15:40:485315 size_t log_position = 0;
5316
[email protected]abe1c4a2013-10-25 19:28:515317 // The delegate info should only have been logged on header complete. Other
5318 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005319 log_position = ExpectLogContainsSomewhereAfter(
5320 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5321 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515322
5323 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5324 log_position + 1);
5325
5326 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005327 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5328 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515329
mikecirone8b85c432016-09-08 19:11:005330 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5331 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515332 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005333 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515334}
tommycli59a63432015-11-06 00:10:555335#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515336
5337// Tests handling of delegate info from a URLRequest::Delegate in the case of
5338// an HTTP redirect.
5339TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555340 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515341
5342 AsyncLoggingUrlRequestDelegate request_delegate(
5343 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5344 TestURLRequestContext context(true);
5345 context.set_network_delegate(NULL);
5346 context.set_net_log(&net_log_);
5347 context.Init();
5348
5349 {
danakj8522a25b2016-04-16 00:17:365350 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555351 http_test_server()->GetURL("/server-redirect?simple.html"),
5352 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195353 LoadStateWithParam load_state = r->GetLoadState();
5354 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515355 base::RunLoop().Run();
5356
[email protected]f7022f32014-08-21 16:32:195357 EXPECT_EQ(200, r->GetResponseCode());
mmenkefe5d0b112016-09-06 20:46:585358 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515359 }
5360
mmenke43758e62015-05-04 21:09:465361 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515362 net_log_.GetEntries(&entries);
5363
5364 // Delegate info should only have been logged in OnReceivedRedirect and
5365 // OnResponseStarted.
5366 size_t log_position = 0;
5367 for (int i = 0; i < 2; ++i) {
5368 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005369 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5370 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515371
5372 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5373 log_position + 1);
5374
5375 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005376 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5377 entries[log_position].type);
5378 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515379 }
5380
mikecirone8b85c432016-09-08 19:11:005381 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5382 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515383 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005384 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515385}
5386
5387// Tests handling of delegate info from a URLRequest::Delegate in the case of
5388// an HTTP redirect, with cancellation at various points.
5389TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555390 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515391
5392 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5393 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5394 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5395 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5396 };
5397
5398 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5399 ++test_case) {
5400 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5401 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515402 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515403 context.set_network_delegate(NULL);
5404 context.set_net_log(&net_log);
5405 context.Init();
5406
5407 {
danakj8522a25b2016-04-16 00:17:365408 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555409 http_test_server()->GetURL("/server-redirect?simple.html"),
5410 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195411 LoadStateWithParam load_state = r->GetLoadState();
5412 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515413 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:585414 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515415 }
5416
mmenke43758e62015-05-04 21:09:465417 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515418 net_log.GetEntries(&entries);
5419
5420 // Delegate info is always logged in both OnReceivedRedirect and
5421 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5422 // OnResponseStarted delegate call is after cancellation, but logging is
5423 // still currently supported in that call.
5424 size_t log_position = 0;
5425 for (int i = 0; i < 2; ++i) {
5426 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005427 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5428 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515429
5430 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5431 log_position + 1);
5432
5433 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005434 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5435 entries[log_position].type);
5436 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515437 }
5438
mikecirone8b85c432016-09-08 19:11:005439 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5440 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515441 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005442 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515443 }
5444}
5445
[email protected]847c0fa92012-11-06 16:37:425446namespace {
5447
5448const char kExtraHeader[] = "Allow-Snafu";
5449const char kExtraValue[] = "fubar";
5450
5451class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205452 void OnReceivedRedirect(URLRequest* request,
5453 const RedirectInfo& redirect_info,
5454 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595455 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425456 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5457 }
5458};
5459
5460} // namespace
5461
5462TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555463 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425464
tommycli59a63432015-11-06 00:10:555465 GURL destination_url =
5466 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5467 GURL original_url =
5468 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425469 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365470 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365471 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195472 req->Start();
[email protected]255620da2013-08-19 13:14:295473 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425474
5475 std::string value;
[email protected]f7022f32014-08-21 16:32:195476 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425477 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5478 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195479 EXPECT_FALSE(req->is_pending());
5480 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425481 EXPECT_EQ(kExtraValue, d.data_received());
5482}
5483
[email protected]251a1b92012-11-13 11:01:095484namespace {
5485
5486const char kExtraHeaderToRemove[] = "To-Be-Removed";
5487
5488class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205489 void OnReceivedRedirect(URLRequest* request,
5490 const RedirectInfo& redirect_info,
5491 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595492 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095493 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5494 }
5495};
5496
5497} // namespace
5498
5499TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555500 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095501
tommycli59a63432015-11-06 00:10:555502 GURL destination_url = http_test_server()->GetURL(
5503 "/echoheader?" + std::string(kExtraHeaderToRemove));
5504 GURL original_url =
5505 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095506 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365507 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365508 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195509 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5510 req->Start();
[email protected]255620da2013-08-19 13:14:295511 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095512
5513 std::string value;
[email protected]f7022f32014-08-21 16:32:195514 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095515 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195516 EXPECT_FALSE(req->is_pending());
5517 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095518 EXPECT_EQ("None", d.data_received());
5519}
5520
[email protected]316c1e5e2012-09-12 15:17:445521TEST_F(URLRequestTestHTTP, CancelTest) {
5522 TestDelegate d;
5523 {
danakj8522a25b2016-04-16 00:17:365524 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365525 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445526
[email protected]f7022f32014-08-21 16:32:195527 r->Start();
5528 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445529
[email protected]f7022f32014-08-21 16:32:195530 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445531
[email protected]255620da2013-08-19 13:14:295532 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445533
5534 // We expect to receive OnResponseStarted even though the request has been
5535 // cancelled.
5536 EXPECT_EQ(1, d.response_started_count());
5537 EXPECT_EQ(0, d.bytes_received());
5538 EXPECT_FALSE(d.received_data_before_response());
5539 }
5540}
5541
5542TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555543 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445544
5545 TestDelegate d;
5546 {
danakj8522a25b2016-04-16 00:17:365547 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555548 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445549
5550 d.set_cancel_in_response_started(true);
5551
[email protected]f7022f32014-08-21 16:32:195552 r->Start();
5553 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445554
[email protected]255620da2013-08-19 13:14:295555 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445556
5557 EXPECT_EQ(1, d.response_started_count());
5558 EXPECT_EQ(0, d.bytes_received());
5559 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:585560 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445561 }
5562}
5563
5564TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555565 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445566
5567 TestDelegate d;
5568 {
danakj8522a25b2016-04-16 00:17:365569 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555570 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445571
5572 d.set_cancel_in_received_data(true);
5573
[email protected]f7022f32014-08-21 16:32:195574 r->Start();
5575 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445576
[email protected]255620da2013-08-19 13:14:295577 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445578
5579 EXPECT_EQ(1, d.response_started_count());
5580 // There is no guarantee about how much data was received
5581 // before the cancel was issued. It could have been 0 bytes,
5582 // or it could have been all the bytes.
5583 // EXPECT_EQ(0, d.bytes_received());
5584 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:585585 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445586 }
5587}
5588
5589TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555590 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445591
5592 TestDelegate d;
5593 {
danakj8522a25b2016-04-16 00:17:365594 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555595 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445596
[email protected]f7022f32014-08-21 16:32:195597 r->Start();
5598 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445599
5600 // The request will be implicitly canceled when it is destroyed. The
5601 // test delegate must not post a quit message when this happens because
5602 // this test doesn't actually have a message loop. The quit message would
5603 // get put on this thread's message queue and the next test would exit
5604 // early, causing problems.
5605 d.set_quit_on_complete(false);
5606 }
5607 // expect things to just cleanup properly.
5608
kimwjdalsl2bb4ff02015-12-16 22:06:025609 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445610 // message loop
5611 EXPECT_FALSE(d.received_data_before_response());
5612 EXPECT_EQ(0, d.bytes_received());
5613}
5614
5615TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555616 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445617
5618 // populate cache
5619 {
5620 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365621 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555622 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195623 r->Start();
[email protected]255620da2013-08-19 13:14:295624 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:585625 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445626 }
5627
5628 // cancel read from cache (see bug 990242)
5629 {
5630 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365631 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555632 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195633 r->Start();
5634 r->Cancel();
[email protected]255620da2013-08-19 13:14:295635 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445636
mmenkefe5d0b112016-09-06 20:46:585637 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445638 EXPECT_EQ(1, d.response_started_count());
5639 EXPECT_EQ(0, d.bytes_received());
5640 EXPECT_FALSE(d.received_data_before_response());
5641 }
5642}
5643
5644TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555645 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445646 HTTPUploadDataOperationTest("POST");
5647}
5648
5649TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555650 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445651 HTTPUploadDataOperationTest("PUT");
5652}
5653
5654TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555655 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445656
5657 TestDelegate d;
5658 {
danakj8522a25b2016-04-16 00:17:365659 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555660 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195661 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445662
[email protected]f7022f32014-08-21 16:32:195663 r->Start();
5664 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445665
[email protected]255620da2013-08-19 13:14:295666 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445667
mmenkefe5d0b112016-09-06 20:46:585668 ASSERT_EQ(1, d.response_started_count())
5669 << "request failed: " << r->status().status()
5670 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445671
5672 EXPECT_FALSE(d.received_data_before_response());
5673 EXPECT_TRUE(d.data_received().empty());
5674 }
5675}
5676
5677TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555678 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445679
5680 TestDelegate d;
5681 {
danakj8522a25b2016-04-16 00:17:365682 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555683 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195684 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445685
[email protected]6cdfd7f2013-02-08 20:40:155686 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445687 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025688 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445689
danakj8522a25b2016-04-16 00:17:365690 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445691
[email protected]6cdfd7f2013-02-08 20:40:155692 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445693 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475694 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445695 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
danakj8522a25b2016-04-16 00:17:365696 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
avibf0746c2015-12-09 19:53:145697 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5698 std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365699 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225700 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445701
[email protected]f7022f32014-08-21 16:32:195702 r->Start();
5703 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445704
[email protected]255620da2013-08-19 13:14:295705 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445706
avibf0746c2015-12-09 19:53:145707 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295708 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5709 ASSERT_LE(size64, std::numeric_limits<int>::max());
5710 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365711 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445712
[email protected]7600d0b2013-12-08 21:43:305713 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445714
mmenkefe5d0b112016-09-06 20:46:585715 ASSERT_EQ(1, d.response_started_count())
5716 << "request failed: " << r->status().status()
5717 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445718
5719 EXPECT_FALSE(d.received_data_before_response());
5720
[email protected]329b68b2012-11-14 17:54:275721 EXPECT_EQ(size, d.bytes_received());
5722 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445723 }
5724}
5725
[email protected]999dd8c2013-11-12 06:45:545726TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555727 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545728
5729 TestDelegate d;
5730 {
danakj8522a25b2016-04-16 00:17:365731 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555732 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195733 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545734
danakj8522a25b2016-04-16 00:17:365735 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545736
danakj8522a25b2016-04-16 00:17:365737 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455738 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545739 base::FilePath(FILE_PATH_LITERAL(
5740 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145741 0, std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365742 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225743 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545744
[email protected]f7022f32014-08-21 16:32:195745 r->Start();
5746 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545747
5748 base::RunLoop().Run();
5749
[email protected]999dd8c2013-11-12 06:45:545750 EXPECT_TRUE(d.request_failed());
5751 EXPECT_FALSE(d.received_data_before_response());
5752 EXPECT_EQ(0, d.bytes_received());
mmenkefe5d0b112016-09-06 20:46:585753 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5754 EXPECT_THAT(r->status().error(), IsError(ERR_FILE_NOT_FOUND));
[email protected]999dd8c2013-11-12 06:45:545755 }
5756}
5757
mmenke56b0cbb912016-03-28 21:34:535758namespace {
5759
5760// Adds a standard set of data to an upload for chunked upload integration
5761// tests.
5762void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5763 writer->AppendData("a", 1, false);
5764 writer->AppendData("bcd", 3, false);
5765 writer->AppendData("this is a longer chunk than before.", 35, false);
5766 writer->AppendData("\r\n\r\n", 4, false);
5767 writer->AppendData("0", 1, false);
5768 writer->AppendData("2323", 4, true);
5769}
5770
5771// Checks that the upload data added in AddChunksToUpload() was echoed back from
5772// the server.
5773void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5774 // This should match the chunks sent by AddChunksToUpload().
5775 const std::string expected_data =
5776 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5777
mmenkefe5d0b112016-09-06 20:46:585778 ASSERT_EQ(1, d->response_started_count())
5779 << "request failed: " << r->status().status()
5780 << ", os error: " << r->status().error();
mmenke56b0cbb912016-03-28 21:34:535781
5782 EXPECT_FALSE(d->received_data_before_response());
5783
5784 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5785 EXPECT_EQ(expected_data, d->data_received());
5786}
5787
5788} // namespace
5789
[email protected]316c1e5e2012-09-12 15:17:445790TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555791 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445792
5793 TestDelegate d;
5794 {
danakj8522a25b2016-04-16 00:17:365795 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555796 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365797 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535798 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365799 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535800 upload_data_stream->CreateWriter();
5801 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195802 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535803 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195804 r->Start();
5805 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445806
[email protected]255620da2013-08-19 13:14:295807 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445808
[email protected]f7022f32014-08-21 16:32:195809 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445810 }
5811}
5812
[email protected]329b68b2012-11-14 17:54:275813TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555814 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275815
5816 TestDelegate d;
5817 {
danakj8522a25b2016-04-16 00:17:365818 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555819 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365820 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535821 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365822 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535823 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365824 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195825 r->set_method("POST");
5826 r->Start();
5827 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535828 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295829 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275830
[email protected]f7022f32014-08-21 16:32:195831 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275832 }
5833}
5834
[email protected]316c1e5e2012-09-12 15:17:445835TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555836 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445837
5838 TestDelegate d;
5839 {
danakj8522a25b2016-04-16 00:17:365840 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555841 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365842 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535843 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365844 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535845 upload_data_stream->CreateWriter();
5846 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195847 r->set_method("POST");
5848 r->Start();
5849 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445850
[email protected]255620da2013-08-19 13:14:295851 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535852 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295853 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445854
[email protected]f7022f32014-08-21 16:32:195855 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445856 }
5857}
5858
5859TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555860 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445861
5862 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365863 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555864 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195865 req->Start();
[email protected]255620da2013-08-19 13:14:295866 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445867
[email protected]f7022f32014-08-21 16:32:195868 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445869
5870 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195871 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445872
5873 std::string header;
5874 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5875 EXPECT_EQ("private", header);
5876
5877 header.clear();
5878 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5879 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5880
5881 // The response has two "X-Multiple-Entries" headers.
5882 // This verfies our output has them concatenated together.
5883 header.clear();
5884 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5885 EXPECT_EQ("a, b", header);
5886}
5887
tommycli59a63432015-11-06 00:10:555888// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5889// security state. (see http://crbug.com/550977).
5890#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465891TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555892 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5893 https_test_server.SetSSLConfig(
5894 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5895 https_test_server.ServeFilesFromSourceDirectory(
5896 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465897 ASSERT_TRUE(https_test_server.Start());
5898
tommycli59a63432015-11-06 00:10:555899 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465900 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365901 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555902 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195903 request->Start();
[email protected]255620da2013-08-19 13:14:295904 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465905
5906 TransportSecurityState* security_state =
5907 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405908 TransportSecurityState::STSState sts_state;
5909 TransportSecurityState::PKPState pkp_state;
5910 EXPECT_TRUE(
5911 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5912 EXPECT_FALSE(
5913 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5914 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5915 sts_state.upgrade_mode);
5916 EXPECT_TRUE(sts_state.include_subdomains);
5917 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035918#if defined(OS_ANDROID)
5919 // Android's CertVerifyProc does not (yet) handle pins.
5920#else
martijnc0d6b622015-06-30 19:14:405921 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035922#endif
[email protected]37fd55fb2013-06-29 13:13:275923}
5924
estarka5da76702015-04-09 04:00:165925TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555926 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5927 https_test_server.ServeFilesFromSourceDirectory(
5928 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165929 ASSERT_TRUE(https_test_server.Start());
5930 // Make sure this test fails if the test server is changed to not
5931 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555932 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5933 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165934
5935 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365936 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555937 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165938 request->Start();
5939 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165940 TransportSecurityState* security_state =
5941 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405942 TransportSecurityState::STSState sts_state;
5943 EXPECT_FALSE(
5944 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165945}
5946
estark06e0dac2015-08-07 21:56:015947namespace {
estark1614475f2016-03-10 03:46:475948const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:245949const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
5950const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:015951const char kHPKPReportUri[] = "https://hpkp-report.test";
5952} // namespace
5953
[email protected]37fd55fb2013-06-29 13:13:275954// Tests that enabling HPKP on a domain does not affect the HSTS
5955// validity/expiration.
dadrian2faf2062016-07-16 00:03:175956TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:015957 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555958 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5959 https_test_server.SetSSLConfig(
5960 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5961 https_test_server.ServeFilesFromSourceDirectory(
5962 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275963 ASSERT_TRUE(https_test_server.Start());
5964
tommycli59a63432015-11-06 00:10:555965 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165966
[email protected]37fd55fb2013-06-29 13:13:275967 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365968 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555969 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195970 request->Start();
[email protected]255620da2013-08-19 13:14:295971 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275972 TransportSecurityState* security_state =
5973 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405974 TransportSecurityState::STSState sts_state;
5975 TransportSecurityState::PKPState pkp_state;
5976 EXPECT_FALSE(
5977 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5978 EXPECT_TRUE(
5979 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5980 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5981 sts_state.upgrade_mode);
5982 EXPECT_FALSE(sts_state.include_subdomains);
5983 EXPECT_FALSE(pkp_state.include_subdomains);
5984 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015985 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405986 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465987}
5988
estark06e0dac2015-08-07 21:56:015989// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:175990TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015991 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555992 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5993 https_test_server.SetSSLConfig(
5994 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5995 https_test_server.ServeFilesFromSourceDirectory(
5996 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015997 ASSERT_TRUE(https_test_server.Start());
5998
tommycli59a63432015-11-06 00:10:555999 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016000
6001 // Set up a pin for |test_server_hostname|.
6002 TransportSecurityState security_state;
6003 const base::Time current_time(base::Time::Now());
6004 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6005 HashValueVector hashes;
6006 HashValue hash1;
6007 HashValue hash2;
6008 // The values here don't matter, as long as they are different from
6009 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446010 ASSERT_TRUE(
6011 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6012 ASSERT_TRUE(
6013 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016014 hashes.push_back(hash1);
6015 hashes.push_back(hash2);
6016 security_state.AddHPKP(test_server_hostname, expiry,
6017 false, /* include subdomains */
6018 hashes, report_uri);
6019
6020 MockCertificateReportSender mock_report_sender;
6021 security_state.SetReportSender(&mock_report_sender);
6022
6023 // Set up a MockCertVerifier to trigger a violation of the previously
6024 // set pin.
6025 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6026 ASSERT_TRUE(cert);
6027
6028 MockCertVerifier cert_verifier;
6029 CertVerifyResult verify_result;
6030 verify_result.verified_cert = cert;
6031 verify_result.is_issued_by_known_root = true;
6032 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446033 ASSERT_TRUE(
6034 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016035 verify_result.public_key_hashes.push_back(hash3);
6036 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6037
6038 TestNetworkDelegate network_delegate;
6039 TestURLRequestContext context(true);
6040 context.set_transport_security_state(&security_state);
6041 context.set_network_delegate(&network_delegate);
6042 context.set_cert_verifier(&cert_verifier);
6043 context.Init();
6044
6045 // Now send a request to trigger the violation.
6046 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366047 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556048 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016049 violating_request->Start();
6050 base::RunLoop().Run();
6051
6052 // Check that a report was sent.
6053 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6054 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366055 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016056 base::JSONReader::Read(mock_report_sender.latest_report()));
6057 ASSERT_TRUE(value);
6058 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6059 base::DictionaryValue* report_dict;
6060 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6061 std::string report_hostname;
6062 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6063 EXPECT_EQ(test_server_hostname, report_hostname);
6064}
6065
6066// Tests that reports get sent on requests with
6067// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176068TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016069 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556070 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6071 https_test_server.SetSSLConfig(
6072 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6073 https_test_server.ServeFilesFromSourceDirectory(
6074 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016075 ASSERT_TRUE(https_test_server.Start());
6076
tommycli59a63432015-11-06 00:10:556077 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016078
6079 TransportSecurityState security_state;
6080 MockCertificateReportSender mock_report_sender;
6081 security_state.SetReportSender(&mock_report_sender);
6082
6083 // Set up a MockCertVerifier to violate the pin in the Report-Only
6084 // header.
6085 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6086 ASSERT_TRUE(cert);
6087
6088 MockCertVerifier cert_verifier;
6089 CertVerifyResult verify_result;
6090 verify_result.verified_cert = cert;
6091 verify_result.is_issued_by_known_root = true;
6092 HashValue hash;
6093 // This value doesn't matter, as long as it is different from the pins
6094 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446095 ASSERT_TRUE(
6096 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016097 verify_result.public_key_hashes.push_back(hash);
6098 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6099
6100 TestNetworkDelegate network_delegate;
6101 TestURLRequestContext context(true);
6102 context.set_transport_security_state(&security_state);
6103 context.set_network_delegate(&network_delegate);
6104 context.set_cert_verifier(&cert_verifier);
6105 context.Init();
6106
6107 // Now send a request to trigger the violation.
6108 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366109 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556110 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016111 DEFAULT_PRIORITY, &d));
6112 violating_request->Start();
6113 base::RunLoop().Run();
6114
6115 // Check that a report was sent.
6116 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6117 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366118 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016119 base::JSONReader::Read(mock_report_sender.latest_report()));
6120 ASSERT_TRUE(value);
6121 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6122 base::DictionaryValue* report_dict;
6123 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6124 std::string report_hostname;
6125 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6126 EXPECT_EQ(test_server_hostname, report_hostname);
6127}
6128
6129// Tests that reports do not get sent on requests with
6130// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176131TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016132 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556133 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6134 https_test_server.SetSSLConfig(
6135 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6136 https_test_server.ServeFilesFromSourceDirectory(
6137 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016138 ASSERT_TRUE(https_test_server.Start());
6139
tommycli59a63432015-11-06 00:10:556140 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016141
6142 TransportSecurityState security_state;
6143 MockCertificateReportSender mock_report_sender;
6144 security_state.SetReportSender(&mock_report_sender);
6145
6146 TestNetworkDelegate network_delegate;
6147 MockCertVerifier mock_cert_verifier;
6148 TestURLRequestContext context(true);
6149 context.set_transport_security_state(&security_state);
6150 context.set_network_delegate(&network_delegate);
6151 context.set_cert_verifier(&mock_cert_verifier);
6152 mock_cert_verifier.set_default_result(OK);
6153 context.Init();
6154
6155 // Now send a request that does not trigger the violation.
6156 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366157 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556158 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016159 DEFAULT_PRIORITY, &d));
6160 request->Start();
6161 base::RunLoop().Run();
6162
6163 // Check that a report was not sent.
6164 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6165 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6166}
6167
estarka5da76702015-04-09 04:00:166168TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556169 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6170 https_test_server.ServeFilesFromSourceDirectory(
6171 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166172 ASSERT_TRUE(https_test_server.Start());
6173 // Make sure this test fails if the test server is changed to not
6174 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556175 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6176 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166177
6178 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366179 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556180 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166181 request->Start();
6182 base::RunLoop().Run();
6183
6184 TransportSecurityState* security_state =
6185 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406186 TransportSecurityState::PKPState pkp_state;
6187 EXPECT_FALSE(
6188 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166189}
6190
dadriandf302c42016-06-10 18:48:596191TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6192 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6193 https_test_server.SetSSLConfig(
6194 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6195 https_test_server.ServeFilesFromSourceDirectory(
6196 base::FilePath(kTestFilePath));
6197 ASSERT_TRUE(https_test_server.Start());
6198
6199 // Set up a MockCertVerifier to be a local root that violates the pin
6200 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6201 ASSERT_TRUE(cert);
6202
6203 MockCertVerifier cert_verifier;
6204 CertVerifyResult verify_result;
6205 verify_result.verified_cert = cert;
6206 verify_result.is_issued_by_known_root = false;
6207 HashValue hash;
6208 ASSERT_TRUE(
6209 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6210 verify_result.public_key_hashes.push_back(hash);
6211 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6212 cert_verifier.set_default_result(OK);
6213
6214 std::string test_server_hostname = https_test_server.GetURL("/").host();
6215
6216 // Set up HPKP
6217 base::Time current_time = base::Time::Now();
6218 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6219 HashValue pin;
6220 ASSERT_TRUE(
6221 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6222 HashValueVector hashes;
6223 hashes.push_back(pin);
6224 GURL report_uri(kHPKPReportUri);
6225 TransportSecurityState security_state;
6226 security_state.AddHPKP(test_server_hostname, expiry,
6227 false, /* include subdomains */
6228 hashes, report_uri);
6229
6230 TestNetworkDelegate network_delegate;
6231 TestURLRequestContext context(true);
6232 context.set_transport_security_state(&security_state);
6233 context.set_network_delegate(&network_delegate);
6234 context.set_cert_verifier(&cert_verifier);
6235 context.Init();
6236
6237 TestDelegate d;
6238 std::unique_ptr<URLRequest> request(context.CreateRequest(
6239 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6240 request->Start();
6241 base::RunLoop().Run();
6242
6243 TransportSecurityState::PKPState pkp_state;
6244 EXPECT_TRUE(
6245 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6246 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6247}
6248
[email protected]242d8562012-10-30 21:20:466249TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556250 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6251 https_test_server.SetSSLConfig(
6252 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6253 https_test_server.ServeFilesFromSourceDirectory(
6254 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466255 ASSERT_TRUE(https_test_server.Start());
6256
tommycli59a63432015-11-06 00:10:556257 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166258
[email protected]242d8562012-10-30 21:20:466259 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366260 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556261 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6262 &d));
[email protected]f7022f32014-08-21 16:32:196263 request->Start();
[email protected]255620da2013-08-19 13:14:296264 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466265
6266 // We should have set parameters from the first header, not the second.
6267 TransportSecurityState* security_state =
6268 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406269 TransportSecurityState::STSState sts_state;
6270 EXPECT_TRUE(
6271 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6272 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6273 sts_state.upgrade_mode);
6274 EXPECT_FALSE(sts_state.include_subdomains);
6275 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466276}
6277
[email protected]9f972ec2013-04-10 20:24:366278TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556279 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6280 https_test_server.SetSSLConfig(
6281 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6282 https_test_server.ServeFilesFromSourceDirectory(
6283 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366284 ASSERT_TRUE(https_test_server.Start());
6285
tommycli59a63432015-11-06 00:10:556286 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166287
[email protected]9f972ec2013-04-10 20:24:366288 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366289 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556290 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6291 &d));
[email protected]f7022f32014-08-21 16:32:196292 request->Start();
[email protected]255620da2013-08-19 13:14:296293 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366294
6295 // We should have set parameters from the first header, not the second.
6296 TransportSecurityState* security_state =
6297 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406298 TransportSecurityState::STSState sts_state;
6299 TransportSecurityState::PKPState pkp_state;
6300 EXPECT_TRUE(
6301 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6302 EXPECT_TRUE(
6303 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6304 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6305 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036306#if defined(OS_ANDROID)
6307 // Android's CertVerifyProc does not (yet) handle pins.
6308#else
martijnc0d6b622015-06-30 19:14:406309 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036310#endif
martijnc0d6b622015-06-30 19:14:406311 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366312
[email protected]a165f092013-06-12 16:10:056313 // Even though there is an HSTS header asserting includeSubdomains, it is
6314 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406315 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056316 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406317 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366318}
6319
[email protected]37fd55fb2013-06-29 13:13:276320// Tests that when multiple HPKP headers are present, asserting different
6321// policies, that only the first such policy is processed.
6322TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556323 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6324 https_test_server.SetSSLConfig(
6325 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6326 https_test_server.ServeFilesFromSourceDirectory(
6327 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276328 ASSERT_TRUE(https_test_server.Start());
6329
tommycli59a63432015-11-06 00:10:556330 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166331
[email protected]37fd55fb2013-06-29 13:13:276332 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366333 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556334 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366335 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196336 request->Start();
[email protected]255620da2013-08-19 13:14:296337 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276338
6339 TransportSecurityState* security_state =
6340 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406341 TransportSecurityState::STSState sts_state;
6342 TransportSecurityState::PKPState pkp_state;
6343 EXPECT_TRUE(
6344 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6345 EXPECT_TRUE(
6346 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6347 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6348 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036349#if defined(OS_ANDROID)
6350 // Android's CertVerifyProc does not (yet) handle pins.
6351#else
martijnc0d6b622015-06-30 19:14:406352 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036353#endif
martijnc0d6b622015-06-30 19:14:406354 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276355
martijnc0d6b622015-06-30 19:14:406356 EXPECT_TRUE(sts_state.include_subdomains);
6357 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276358}
6359
estark1614475f2016-03-10 03:46:476360// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6361// called.
6362class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6363 public:
6364 MockExpectCTReporter() : num_failures_(0) {}
6365 ~MockExpectCTReporter() override {}
6366
6367 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6368 const GURL& report_uri,
6369 const net::SSLInfo& ssl_info) override {
6370 num_failures_++;
6371 }
6372
6373 uint32_t num_failures() { return num_failures_; }
6374
6375 private:
6376 uint32_t num_failures_;
6377};
6378
6379// A CTVerifier that returns net::OK for every certificate.
6380class MockCTVerifier : public CTVerifier {
6381 public:
6382 MockCTVerifier() {}
6383 ~MockCTVerifier() override {}
6384
6385 int Verify(X509Certificate* cert,
6386 const std::string& stapled_ocsp_response,
6387 const std::string& sct_list_from_tls_extension,
6388 ct::CTVerifyResult* result,
6389 const BoundNetLog& net_log) override {
6390 return net::OK;
6391 }
6392
6393 void SetObserver(Observer* observer) override {}
6394};
6395
6396// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6397// for every certificate.
6398class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6399 public:
6400 MockCTPolicyEnforcer()
6401 : default_result_(
6402 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6403 ~MockCTPolicyEnforcer() override {}
6404
6405 ct::CertPolicyCompliance DoesConformToCertPolicy(
6406 X509Certificate* cert,
6407 const SCTList& verified_scts,
6408 const BoundNetLog& net_log) override {
6409 return default_result_;
6410 }
6411
6412 void set_default_result(ct::CertPolicyCompliance default_result) {
6413 default_result_ = default_result;
6414 }
6415
6416 private:
6417 ct::CertPolicyCompliance default_result_;
6418};
6419
6420// Tests that Expect CT headers are processed correctly.
6421TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6422 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6423 https_test_server.SetSSLConfig(
6424 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6425 https_test_server.ServeFilesFromSourceDirectory(
6426 base::FilePath(kTestFilePath));
6427 ASSERT_TRUE(https_test_server.Start());
6428
6429 MockExpectCTReporter reporter;
6430 TransportSecurityState transport_security_state;
6431 transport_security_state.enable_static_expect_ct_ = true;
6432 transport_security_state.SetExpectCTReporter(&reporter);
6433
6434 // Set up a MockCertVerifier to accept the certificate that the server sends.
6435 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6436 ASSERT_TRUE(cert);
6437 MockCertVerifier cert_verifier;
6438 CertVerifyResult verify_result;
6439 verify_result.verified_cert = cert;
6440 verify_result.is_issued_by_known_root = true;
6441 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6442
6443 // Set up a MockCTVerifier and MockCTPolicyEnforcer to trigger an Expect CT
6444 // violation.
6445 MockCTVerifier ct_verifier;
6446 MockCTPolicyEnforcer ct_policy_enforcer;
6447 ct_policy_enforcer.set_default_result(
6448 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6449
6450 TestNetworkDelegate network_delegate;
6451 // Use a MockHostResolver (which by default maps all hosts to
6452 // 127.0.0.1) so that the request can be sent to a site on the Expect
6453 // CT preload list.
6454 MockHostResolver host_resolver;
6455 TestURLRequestContext context(true);
6456 context.set_host_resolver(&host_resolver);
6457 context.set_transport_security_state(&transport_security_state);
6458 context.set_network_delegate(&network_delegate);
6459 context.set_cert_verifier(&cert_verifier);
6460 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206461 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476462 context.Init();
6463
6464 // Now send a request to trigger the violation.
6465 TestDelegate d;
6466 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6467 GURL::Replacements replace_host;
6468 replace_host.SetHostStr(kExpectCTStaticHostname);
6469 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366470 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476471 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6472 violating_request->Start();
6473 base::RunLoop().Run();
6474
6475 EXPECT_EQ(1u, reporter.num_failures());
6476}
6477
tommycli59a63432015-11-06 00:10:556478#endif // !defined(OS_IOS)
6479
[email protected]316c1e5e2012-09-12 15:17:446480TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556481 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446482
6483 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366484 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556485 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366486 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196487 req->Start();
[email protected]255620da2013-08-19 13:14:296488 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446489
6490 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196491 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446492 EXPECT_EQ("text/html", mime_type);
6493
6494 std::string charset;
[email protected]f7022f32014-08-21 16:32:196495 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446496 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196497 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446498}
6499
[email protected]02494ec2014-05-07 15:05:296500TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346501 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346502 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346503 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026504 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346505
6506 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506507 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346508}
6509
[email protected]02494ec2014-05-07 15:05:296510#if !defined(DISABLE_FILE_SUPPORT)
6511TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6512 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6513 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456514 FileProtocolHandler file_protocol_handler(
6515 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296516 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6517
6518 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506519 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296520}
6521
[email protected]588614c22013-08-16 00:09:026522TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556523 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446524
6525 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366526 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556527 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366528 &d));
[email protected]f7022f32014-08-21 16:32:196529 req->Start();
[email protected]255620da2013-08-19 13:14:296530 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446531
mmenkefe5d0b112016-09-06 20:46:586532 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6533 EXPECT_THAT(req->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]316c1e5e2012-09-12 15:17:446534}
[email protected]02494ec2014-05-07 15:05:296535#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446536
[email protected]588614c22013-08-16 00:09:026537TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556538 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026539
6540 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366541 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556542 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366543 &d));
[email protected]f7022f32014-08-21 16:32:196544 req->Start();
fdoray5eeb7642016-06-22 16:11:286545 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026546
mmenkefe5d0b112016-09-06 20:46:586547 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6548 EXPECT_THAT(req->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]588614c22013-08-16 00:09:026549}
6550
[email protected]316c1e5e2012-09-12 15:17:446551TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556552 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446553
6554 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366555 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556556 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366557 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196558 req->Start();
[email protected]255620da2013-08-19 13:14:296559 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446560
mmenkefe5d0b112016-09-06 20:46:586561 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6562 EXPECT_THAT(req->status().error(), IsError(ERR_INVALID_URL));
[email protected]316c1e5e2012-09-12 15:17:446563}
6564
[email protected]e50efea2014-03-24 18:41:006565// Make sure redirects are cached, despite not reading their bodies.
6566TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556567 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006568 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556569 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006570
6571 {
6572 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366573 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366574 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196575 req->Start();
[email protected]e50efea2014-03-24 18:41:006576 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:586577 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006578 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556579 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006580 }
6581
6582 {
6583 TestDelegate d;
6584 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366585 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366586 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196587 req->Start();
[email protected]e50efea2014-03-24 18:41:006588 base::RunLoop().Run();
6589
6590 EXPECT_EQ(1, d.received_redirect_count());
6591 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196592 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006593
[email protected]f7022f32014-08-21 16:32:196594 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006595 base::RunLoop().Run();
6596 EXPECT_EQ(1, d.received_redirect_count());
6597 EXPECT_EQ(1, d.response_started_count());
mmenkefe5d0b112016-09-06 20:46:586598 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556599 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006600 }
6601}
6602
6603// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6604// when the headers are read, since the body won't have been read.
6605TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556606 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006607 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556608 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006609
6610 {
6611 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556612 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006613 default_network_delegate_.set_redirect_on_headers_received_url(
6614 redirect_to_url);
6615
6616 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366617 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366618 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196619 req->Start();
[email protected]e50efea2014-03-24 18:41:006620 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:586621 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006622 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196623 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006624 }
6625
6626 {
6627 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366628 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366629 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196630 req->Start();
[email protected]e50efea2014-03-24 18:41:006631 base::RunLoop().Run();
6632
mmenkefe5d0b112016-09-06 20:46:586633 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]f7022f32014-08-21 16:32:196634 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006635 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196636 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006637 }
6638}
6639
[email protected]5f714132014-03-26 10:41:166640// Tests that redirection to an unsafe URL is allowed when it has been marked as
6641// safe.
6642TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556643 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166644
6645 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6646 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6647 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6648
6649 TestDelegate d;
6650 {
danakj8522a25b2016-04-16 00:17:366651 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556652 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166653
[email protected]f7022f32014-08-21 16:32:196654 r->Start();
[email protected]5f714132014-03-26 10:41:166655 base::RunLoop().Run();
6656
mmenkefe5d0b112016-09-06 20:46:586657 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6658
[email protected]f7022f32014-08-21 16:32:196659 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:586660 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196661 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166662 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6663 }
6664}
6665
6666// Tests that a redirect to a different unsafe URL is blocked, even after adding
6667// some other URL to the whitelist.
6668TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556669 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166670
6671 GURL unsafe_url("data:text/html,something");
6672 GURL different_unsafe_url("data:text/html,something-else");
6673 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6674 default_network_delegate_.set_allowed_unsafe_redirect_url(
6675 different_unsafe_url);
6676
6677 TestDelegate d;
6678 {
danakj8522a25b2016-04-16 00:17:366679 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556680 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166681
[email protected]f7022f32014-08-21 16:32:196682 r->Start();
[email protected]5f714132014-03-26 10:41:166683 base::RunLoop().Run();
6684
mmenkefe5d0b112016-09-06 20:46:586685 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6686 EXPECT_THAT(r->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]5f714132014-03-26 10:41:166687 }
6688}
6689
[email protected]5f714132014-03-26 10:41:166690// Redirects from an URL with fragment to an unsafe URL with fragment should
6691// be allowed, and the reference fragment of the target URL should be preserved.
6692TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556693 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166694
tommycli59a63432015-11-06 00:10:556695 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166696 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6697 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6698
6699 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6700 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6701
6702 TestDelegate d;
6703 {
danakj8522a25b2016-04-16 00:17:366704 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366705 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166706
[email protected]f7022f32014-08-21 16:32:196707 r->Start();
[email protected]5f714132014-03-26 10:41:166708 base::RunLoop().Run();
6709
[email protected]f7022f32014-08-21 16:32:196710 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:586711 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6712 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196713 EXPECT_EQ(original_url, r->original_url());
6714 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166715 }
6716}
6717
6718// When a delegate has specified a safe redirect URL, but it does not match the
6719// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146720TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556721 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166722
tommycli59a63432015-11-06 00:10:556723 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166724 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556725 GURL redirect_url(http_test_server()->GetURL("/target"));
6726 GURL expected_redirect_url(
6727 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166728
6729 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6730 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6731
6732 TestDelegate d;
6733 {
danakj8522a25b2016-04-16 00:17:366734 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366735 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166736
[email protected]f7022f32014-08-21 16:32:196737 r->Start();
[email protected]5f714132014-03-26 10:41:166738 base::RunLoop().Run();
6739
[email protected]f7022f32014-08-21 16:32:196740 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:586741 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6742 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196743 EXPECT_EQ(original_url, r->original_url());
6744 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166745 }
6746}
6747
[email protected]f878230e2014-04-03 15:36:146748// When a delegate has specified a safe redirect URL, assume that the redirect
6749// URL should not be changed. In particular, the reference fragment should not
6750// be modified.
6751TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556752 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146753
tommycli59a63432015-11-06 00:10:556754 GURL original_url(
6755 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146756 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6757
6758 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6759 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6760
6761 TestDelegate d;
6762 {
danakj8522a25b2016-04-16 00:17:366763 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366764 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146765
[email protected]f7022f32014-08-21 16:32:196766 r->Start();
[email protected]f878230e2014-04-03 15:36:146767 base::RunLoop().Run();
6768
[email protected]f7022f32014-08-21 16:32:196769 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:586770 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6771 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196772 EXPECT_EQ(original_url, r->original_url());
6773 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146774 }
6775}
6776
6777// When a URLRequestRedirectJob is created, the redirection must be followed and
6778// the reference fragment of the target URL must not be modified.
6779TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556780 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146781
tommycli59a63432015-11-06 00:10:556782 GURL original_url(
6783 http_test_server()->GetURL("/original#should-not-be-appended"));
6784 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146785
6786 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366787 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366788 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146789
danakj8522a25b2016-04-16 00:17:366790 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196791 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426792 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6793 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146794
[email protected]f7022f32014-08-21 16:32:196795 r->Start();
[email protected]f878230e2014-04-03 15:36:146796 base::RunLoop().Run();
6797
mmenkefe5d0b112016-09-06 20:46:586798 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6799 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196800 EXPECT_EQ(original_url, r->original_url());
6801 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146802}
6803
lizeb5120f6dc2016-02-19 09:29:446804TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6805 ASSERT_TRUE(http_test_server()->Start());
6806
6807 const std::string referrer("foobar://totally.legit.referrer");
6808 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366809 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446810 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6811 req->SetReferrer(referrer);
6812 req->Start();
6813 base::RunLoop().Run();
6814
6815 EXPECT_EQ(std::string("None"), d.data_received());
6816}
6817
[email protected]316c1e5e2012-09-12 15:17:446818TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556819 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446820
6821 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366822 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556823 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196824 req->SetReferrer("http://user:[email protected]/");
6825 req->Start();
[email protected]255620da2013-08-19 13:14:296826 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446827
6828 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6829}
6830
[email protected]99ecf6e2013-04-10 22:46:136831TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556832 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136833
6834 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366835 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556836 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196837 req->SetReferrer("http://foo.com/test#fragment");
6838 req->Start();
[email protected]255620da2013-08-19 13:14:296839 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136840
6841 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6842}
6843
6844TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556845 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136846
6847 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366848 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556849 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196850 req->SetReferrer("http://foo.com/test#fragment");
6851 req->SetReferrer("");
6852 req->Start();
[email protected]255620da2013-08-19 13:14:296853 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136854
6855 EXPECT_EQ(std::string("None"), d.data_received());
6856}
6857
[email protected]316c1e5e2012-09-12 15:17:446858TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556859 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446860
6861 TestDelegate d;
6862 {
6863 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366864 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556865 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6866 &d));
[email protected]f7022f32014-08-21 16:32:196867 req->Start();
[email protected]255620da2013-08-19 13:14:296868 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446869
6870 EXPECT_EQ(1, d.response_started_count());
6871 EXPECT_EQ(0, d.bytes_received());
6872 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:586873 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446874 }
6875}
6876
6877TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556878 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446879
6880 TestDelegate d;
6881 {
6882 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556883 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366884 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366885 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046886
[email protected]f7022f32014-08-21 16:32:196887 req->Start();
[email protected]255620da2013-08-19 13:14:296888 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446889
6890 EXPECT_EQ(1, d.received_redirect_count());
6891
[email protected]f7022f32014-08-21 16:32:196892 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296893 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446894
6895 EXPECT_EQ(1, d.response_started_count());
6896 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:586897 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446898
[email protected]6cdfd7f2013-02-08 20:40:156899 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446900 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476901 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446902 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6903
6904 std::string contents;
[email protected]82f84b92013-08-30 18:23:506905 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446906 EXPECT_EQ(contents, d.data_received());
6907 }
6908}
6909
[email protected]79e1fd62013-06-20 06:50:046910TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556911 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046912
6913 TestDelegate d;
6914 {
6915 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556916 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366917 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366918 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046919
6920 EXPECT_FALSE(d.have_full_request_headers());
6921
[email protected]f7022f32014-08-21 16:32:196922 req->Start();
[email protected]255620da2013-08-19 13:14:296923 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046924
6925 EXPECT_EQ(1, d.received_redirect_count());
6926 EXPECT_TRUE(d.have_full_request_headers());
6927 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6928 d.ClearFullRequestHeaders();
6929
[email protected]f7022f32014-08-21 16:32:196930 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296931 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046932
tommycli59a63432015-11-06 00:10:556933 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046934 EXPECT_EQ(1, d.response_started_count());
6935 EXPECT_TRUE(d.have_full_request_headers());
6936 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6937 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:586938 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046939
6940 base::FilePath path;
6941 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476942 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046943 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]79e1fd62013-06-20 06:50:046947 EXPECT_EQ(contents, d.data_received());
6948 }
6949}
6950
[email protected]316c1e5e2012-09-12 15:17:446951TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556952 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446953
6954 TestDelegate d;
6955 {
6956 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366957 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556958 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6959 &d));
[email protected]f7022f32014-08-21 16:32:196960 req->Start();
[email protected]255620da2013-08-19 13:14:296961 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446962
6963 EXPECT_EQ(1, d.received_redirect_count());
6964
[email protected]f7022f32014-08-21 16:32:196965 req->Cancel();
[email protected]255620da2013-08-19 13:14:296966 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446967
6968 EXPECT_EQ(1, d.response_started_count());
6969 EXPECT_EQ(0, d.bytes_received());
6970 EXPECT_FALSE(d.received_data_before_response());
mmenkefe5d0b112016-09-06 20:46:586971 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446972 }
6973}
6974
6975TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556976 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446977
[email protected]3b23a222013-05-15 21:33:256978 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446979 {
6980 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366981 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556982 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6983 &d));
[email protected]316c1e5e2012-09-12 15:17:446984 HttpRequestHeaders headers;
6985 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196986 req->SetExtraRequestHeaders(headers);
6987 req->Start();
[email protected]255620da2013-08-19 13:14:296988 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256989
6990 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196991 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256992 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446993 }
6994
[email protected]3b23a222013-05-15 21:33:256995 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446996 {
6997 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366998 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556999 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7000 &d));
[email protected]316c1e5e2012-09-12 15:17:447001 HttpRequestHeaders headers;
7002 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197003 req->SetExtraRequestHeaders(headers);
7004 req->Start();
[email protected]255620da2013-08-19 13:14:297005 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447006
[email protected]f7022f32014-08-21 16:32:197007 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257008
7009 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197010 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257011 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447012 }
7013
[email protected]3b23a222013-05-15 21:33:257014 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447015 {
7016 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367017 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557018 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7019 &d));
[email protected]316c1e5e2012-09-12 15:17:447020 HttpRequestHeaders headers;
7021 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197022 req->SetExtraRequestHeaders(headers);
7023 req->Start();
[email protected]255620da2013-08-19 13:14:297024 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447025
[email protected]f7022f32014-08-21 16:32:197026 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257027
7028 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197029 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257030 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447031 }
7032}
7033
7034TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557035 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447036
7037 // populate the cache
7038 {
7039 TestDelegate d;
7040 d.set_credentials(AuthCredentials(kUser, kSecret));
7041
danakj8522a25b2016-04-16 00:17:367042 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557043 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197044 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447045
[email protected]255620da2013-08-19 13:14:297046 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447047
7048 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7049 }
7050
7051 // repeat request with end-to-end validation. since auth-basic results in a
7052 // cachable page, we expect this test to result in a 304. in which case, the
7053 // response should be fetched from the cache.
7054 {
7055 TestDelegate d;
7056 d.set_credentials(AuthCredentials(kUser, kSecret));
7057
danakj8522a25b2016-04-16 00:17:367058 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557059 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197060 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7061 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447062
[email protected]255620da2013-08-19 13:14:297063 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447064
7065 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7066
7067 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197068 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447069 }
7070}
7071
7072// Check that Set-Cookie headers in 401 responses are respected.
7073// http://crbug.com/6450
7074TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557075 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447076
7077 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557078 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447079
7080 // Request a page that will give a 401 containing a Set-Cookie header.
7081 // Verify that when the transaction is restarted, it includes the new cookie.
7082 {
[email protected]ceefd7fd2012-11-29 00:36:247083 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447084 TestURLRequestContext context(true);
7085 context.set_network_delegate(&network_delegate);
7086 context.Init();
7087
7088 TestDelegate d;
7089 d.set_credentials(AuthCredentials(kUser, kSecret));
7090
danakj8522a25b2016-04-16 00:17:367091 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367092 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197093 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447094
[email protected]255620da2013-08-19 13:14:297095 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447096
7097 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7098
7099 // Make sure we sent the cookie in the restarted transaction.
7100 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7101 != std::string::npos);
7102 }
7103
7104 // Same test as above, except this time the restart is initiated earlier
7105 // (without user intervention since identity is embedded in the URL).
7106 {
[email protected]ceefd7fd2012-11-29 00:36:247107 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447108 TestURLRequestContext context(true);
7109 context.set_network_delegate(&network_delegate);
7110 context.Init();
7111
7112 TestDelegate d;
7113
7114 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187115 replacements.SetUsernameStr("user2");
7116 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447117 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7118
danakj8522a25b2016-04-16 00:17:367119 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367120 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197121 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447122
[email protected]255620da2013-08-19 13:14:297123 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447124
7125 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7126
7127 // Make sure we sent the cookie in the restarted transaction.
7128 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7129 != std::string::npos);
7130 }
7131}
7132
[email protected]58e32bb2013-01-21 18:23:257133// Tests that load timing works as expected with auth and the cache.
7134TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557135 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257136
7137 // populate the cache
7138 {
7139 TestDelegate d;
7140 d.set_credentials(AuthCredentials(kUser, kSecret));
7141
danakj8522a25b2016-04-16 00:17:367142 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557143 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197144 r->Start();
[email protected]58e32bb2013-01-21 18:23:257145
[email protected]255620da2013-08-19 13:14:297146 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257147
7148 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7149
7150 LoadTimingInfo load_timing_info_before_auth;
7151 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7152 &load_timing_info_before_auth));
7153 TestLoadTimingNotReused(load_timing_info_before_auth,
7154 CONNECT_TIMING_HAS_DNS_TIMES);
7155
7156 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197157 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257158 // The test server does not support keep alive sockets, so the second
7159 // request with auth should use a new socket.
7160 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7161 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7162 load_timing_info.socket_log_id);
7163 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7164 load_timing_info.connect_timing.connect_start);
7165 }
7166
[email protected]3b23a222013-05-15 21:33:257167 // Repeat request with end-to-end validation. Since auth-basic results in a
7168 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257169 // response should be fetched from the cache.
7170 {
7171 TestDelegate d;
7172 d.set_credentials(AuthCredentials(kUser, kSecret));
7173
danakj8522a25b2016-04-16 00:17:367174 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557175 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197176 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7177 r->Start();
[email protected]58e32bb2013-01-21 18:23:257178
[email protected]255620da2013-08-19 13:14:297179 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257180
7181 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7182
7183 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197184 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257185
[email protected]3b23a222013-05-15 21:33:257186 // Since there was a request that went over the wire, the load timing
7187 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257188 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197189 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257190 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257191 }
7192}
7193
[email protected]316c1e5e2012-09-12 15:17:447194// In this test, we do a POST which the server will 302 redirect.
7195// The subsequent transaction should use GET, and should not send the
7196// Content-Type header.
7197// http://code.google.com/p/chromium/issues/detail?id=843
7198TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557199 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447200
7201 const char kData[] = "hello world";
7202
7203 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367204 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557205 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7206 &d));
[email protected]f7022f32014-08-21 16:32:197207 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077208 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447209
7210 // Set headers (some of which are specific to the POST).
7211 HttpRequestHeaders headers;
7212 headers.AddHeadersFromString(
7213 "Content-Type: multipart/form-data; "
7214 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7215 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7216 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7217 "Accept-Language: en-US,en\r\n"
7218 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7219 "Content-Length: 11\r\n"
7220 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197221 req->SetExtraRequestHeaders(headers);
7222 req->Start();
[email protected]255620da2013-08-19 13:14:297223 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447224
7225 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197226 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447227 EXPECT_EQ("text/html", mime_type);
7228
7229 const std::string& data = d.data_received();
7230
7231 // Check that the post-specific headers were stripped:
7232 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7233 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7234 EXPECT_FALSE(ContainsString(data, "Origin:"));
7235
7236 // These extra request headers should not have been stripped.
7237 EXPECT_TRUE(ContainsString(data, "Accept:"));
7238 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7239 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7240}
7241
jww5fe460ff2015-03-28 00:22:517242// The following tests check that we handle mutating the request for HTTP
7243// redirects as expected.
7244// See https://crbug.com/56373, https://crbug.com/102130, and
7245// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447246
7247TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557248 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447249
tommycli59a63432015-11-06 00:10:557250 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517251 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557252 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447253
7254 HTTPRedirectMethodTest(url, "POST", "GET", true);
7255 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7256 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517257
7258 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7259 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7260 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7261 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7262 std::string());
[email protected]316c1e5e2012-09-12 15:17:447263}
7264
7265TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557266 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447267
tommycli59a63432015-11-06 00:10:557268 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517269 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557270 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447271
7272 HTTPRedirectMethodTest(url, "POST", "GET", true);
7273 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7274 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517275
7276 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7277 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7278 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7279 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7280 std::string());
[email protected]316c1e5e2012-09-12 15:17:447281}
7282
7283TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557284 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447285
tommycli59a63432015-11-06 00:10:557286 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517287 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557288 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447289
7290 HTTPRedirectMethodTest(url, "POST", "GET", true);
7291 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7292 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517293
7294 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7295 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7296 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7297 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7298 std::string());
[email protected]316c1e5e2012-09-12 15:17:447299}
7300
7301TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557302 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447303
tommycli59a63432015-11-06 00:10:557304 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517305 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557306 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447307
7308 HTTPRedirectMethodTest(url, "POST", "POST", true);
7309 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7310 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517311
7312 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7313 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7314 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7315 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447316}
7317
[email protected]0a17aab32014-04-24 03:32:377318TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557319 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377320
tommycli59a63432015-11-06 00:10:557321 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517322 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557323 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377324
7325 HTTPRedirectMethodTest(url, "POST", "POST", true);
7326 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7327 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517328
7329 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7330 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7331 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7332 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377333}
7334
7335// Make sure that 308 responses without bodies are not treated as redirects.
7336// Certain legacy apis that pre-date the response code expect this behavior
7337// (Like Google Drive).
7338TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557339 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377340
7341 TestDelegate d;
tommycli59a63432015-11-06 00:10:557342 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377343
danakj8522a25b2016-04-16 00:17:367344 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367345 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377346
[email protected]f7022f32014-08-21 16:32:197347 request->Start();
[email protected]0a17aab32014-04-24 03:32:377348 base::RunLoop().Run();
mmenkefe5d0b112016-09-06 20:46:587349 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7350 EXPECT_THAT(request->status().error(), IsOk());
[email protected]0a17aab32014-04-24 03:32:377351 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197352 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377353 EXPECT_EQ("This is not a redirect.", d.data_received());
7354}
7355
[email protected]f878230e2014-04-03 15:36:147356TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557357 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147358
tommycli59a63432015-11-06 00:10:557359 GURL original_url(
7360 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7361 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147362
7363 TestDelegate d;
7364 {
danakj8522a25b2016-04-16 00:17:367365 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367366 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147367
[email protected]f7022f32014-08-21 16:32:197368 r->Start();
[email protected]f878230e2014-04-03 15:36:147369 base::RunLoop().Run();
7370
[email protected]f7022f32014-08-21 16:32:197371 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:587372 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7373 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197374 EXPECT_EQ(original_url, r->original_url());
7375 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147376 }
7377}
7378
[email protected]cba24642014-08-15 20:49:597379TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557380 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597381
tommycli59a63432015-11-06 00:10:557382 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597383 GURL first_party_url("http://example.com");
7384
7385 TestDelegate d;
7386 {
danakj8522a25b2016-04-16 00:17:367387 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367388 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197389 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597390
[email protected]f7022f32014-08-21 16:32:197391 r->Start();
[email protected]cba24642014-08-15 20:49:597392 base::RunLoop().Run();
7393
[email protected]f7022f32014-08-21 16:32:197394 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:587395 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7396 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197397 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597398 }
7399}
7400
7401TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557402 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597403
tommycli59a63432015-11-06 00:10:557404 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597405 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557406 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597407
7408 TestDelegate d;
7409 {
danakj8522a25b2016-04-16 00:17:367410 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367411 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197412 r->set_first_party_for_cookies(original_first_party_url);
7413 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597414 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7415
[email protected]f7022f32014-08-21 16:32:197416 r->Start();
[email protected]cba24642014-08-15 20:49:597417 base::RunLoop().Run();
7418
[email protected]f7022f32014-08-21 16:32:197419 EXPECT_EQ(2U, r->url_chain().size());
mmenkefe5d0b112016-09-06 20:46:587420 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7421 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197422 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597423 }
7424}
7425
[email protected]316c1e5e2012-09-12 15:17:447426TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557427 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447428
7429 const char kData[] = "hello world";
7430
7431 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367432 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557433 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197434 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077435 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447436 HttpRequestHeaders headers;
7437 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517438 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197439 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447440
danakj8522a25b2016-04-16 00:17:367441 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557442 req.get(), &default_network_delegate_,
7443 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427444 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7445 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447446
[email protected]f7022f32014-08-21 16:32:197447 req->Start();
[email protected]255620da2013-08-19 13:14:297448 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197449 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447450}
7451
7452TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557453 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447454
7455 const char kData[] = "hello world";
7456
7457 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367458 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557459 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197460 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077461 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447462 HttpRequestHeaders headers;
7463 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517464 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197465 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447466
danakj8522a25b2016-04-16 00:17:367467 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557468 req.get(), &default_network_delegate_,
7469 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097470 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427471 "Very Good Reason"));
7472 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447473
[email protected]f7022f32014-08-21 16:32:197474 req->Start();
[email protected]255620da2013-08-19 13:14:297475 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197476 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447477 EXPECT_EQ(kData, d.data_received());
7478}
7479
7480// Check that default A-L header is sent.
7481TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557482 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447483
[email protected]8790210c2013-12-02 05:29:537484 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247485 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447486 TestURLRequestContext context(true);
7487 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437488 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447489 context.Init();
7490
7491 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367492 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557493 http_test_server()->GetURL("/echoheader?Accept-Language"),
7494 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197495 req->Start();
[email protected]255620da2013-08-19 13:14:297496 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447497 EXPECT_EQ("en", d.data_received());
7498}
7499
7500// Check that an empty A-L header is not sent. http://crbug.com/77365.
7501TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557502 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447503
[email protected]8790210c2013-12-02 05:29:537504 std::string empty_string; // Avoid most vexing parse on line below.
7505 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247506 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447507 TestURLRequestContext context(true);
7508 context.set_network_delegate(&network_delegate);
7509 context.Init();
7510 // We override the language after initialization because empty entries
7511 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437512 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447513
7514 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367515 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557516 http_test_server()->GetURL("/echoheader?Accept-Language"),
7517 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197518 req->Start();
[email protected]255620da2013-08-19 13:14:297519 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447520 EXPECT_EQ("None", d.data_received());
7521}
7522
7523// Check that if request overrides the A-L header, the default is not appended.
7524// See http://crbug.com/20894
7525TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557526 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447527
7528 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367529 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557530 http_test_server()->GetURL("/echoheader?Accept-Language"),
7531 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447532 HttpRequestHeaders headers;
7533 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197534 req->SetExtraRequestHeaders(headers);
7535 req->Start();
[email protected]255620da2013-08-19 13:14:297536 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447537 EXPECT_EQ(std::string("ru"), d.data_received());
7538}
7539
7540// Check that default A-E header is sent.
7541TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557542 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447543
7544 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367545 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557546 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7547 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447548 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197549 req->SetExtraRequestHeaders(headers);
7550 req->Start();
[email protected]255620da2013-08-19 13:14:297551 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447552 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7553}
7554
7555// Check that if request overrides the A-E header, the default is not appended.
7556// See http://crbug.com/47381
7557TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557558 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447559
7560 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367561 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557562 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7563 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447564 HttpRequestHeaders headers;
7565 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197566 req->SetExtraRequestHeaders(headers);
7567 req->Start();
[email protected]255620da2013-08-19 13:14:297568 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447569 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7570 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7571}
7572
[email protected]84f05432013-03-15 01:00:127573// Check that setting the A-C header sends the proper header.
7574TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557575 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447576
7577 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367578 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557579 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7580 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447581 HttpRequestHeaders headers;
7582 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197583 req->SetExtraRequestHeaders(headers);
7584 req->Start();
[email protected]255620da2013-08-19 13:14:297585 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447586 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7587}
7588
7589// Check that default User-Agent header is sent.
7590TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557591 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447592
7593 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367594 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557595 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7596 &d));
[email protected]f7022f32014-08-21 16:32:197597 req->Start();
[email protected]255620da2013-08-19 13:14:297598 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197599 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377600 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447601}
7602
7603// Check that if request overrides the User-Agent header,
7604// the default is not appended.
marqf14fff8d2015-12-02 15:52:297605// TODO(crbug.com/564656) This test is flaky on iOS.
7606#if defined(OS_IOS)
7607#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7608#else
7609#define MAYBE_OverrideUserAgent OverrideUserAgent
7610#endif
7611TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
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?User-Agent"), DEFAULT_PRIORITY,
7617 &d));
[email protected]316c1e5e2012-09-12 15:17:447618 HttpRequestHeaders headers;
7619 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[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]cd6f2522014-01-16 18:27:357623 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447624}
7625
[email protected]ee4c30d2012-11-07 15:08:437626// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7627// User-Agent header to be sent but does not send the Accept-Language and
7628// Accept-Charset headers.
7629TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557630 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437631
[email protected]ceefd7fd2012-11-29 00:36:247632 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437633 TestURLRequestContext context(true);
7634 context.set_network_delegate(&network_delegate);
7635 context.Init();
7636 // We override the HttpUserAgentSettings after initialization because empty
7637 // entries get overridden by Init().
7638 context.set_http_user_agent_settings(NULL);
7639
7640 struct {
7641 const char* request;
7642 const char* expected_response;
tommycli59a63432015-11-06 00:10:557643 } tests[] = {{"/echoheader?Accept-Language", "None"},
7644 {"/echoheader?Accept-Charset", "None"},
7645 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437646
viettrungluue4a8b882014-10-16 06:17:387647 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437648 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367649 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557650 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197651 req->Start();
[email protected]255620da2013-08-19 13:14:297652 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437653 EXPECT_EQ(tests[i].expected_response, d.data_received())
7654 << " Request = \"" << tests[i].request << "\"";
7655 }
7656}
7657
[email protected]5033ab82013-03-22 20:17:467658// Make sure that URLRequest passes on its priority updates to
7659// newly-created jobs after the first one.
7660TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557661 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467662
7663 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367664 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557665 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197666 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467667
danakj8522a25b2016-04-16 00:17:367668 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557669 req.get(), &default_network_delegate_,
7670 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427671 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7672 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467673
[email protected]f7022f32014-08-21 16:32:197674 req->SetPriority(LOW);
7675 req->Start();
7676 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467677
mmenkeed0498b2015-12-08 23:20:427678 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367679 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427680 req.get(), &default_network_delegate_, &job_priority));
7681 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467682
7683 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297684 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427685 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467686}
7687
[email protected]80abdad2014-03-15 00:20:547688// Check that creating a network request while entering/exiting suspend mode
7689// fails as it should. This is the only case where an HttpTransactionFactory
7690// does not return an HttpTransaction.
7691TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7692 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367693 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177694 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547695 network_layer->OnSuspend();
7696
dchengc7eeda422015-12-26 03:56:487697 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427698 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547699
7700 TestURLRequestContext context(true);
7701 context.set_http_transaction_factory(&http_cache);
7702 context.Init();
7703
7704 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367705 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367706 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197707 req->Start();
[email protected]80abdad2014-03-15 00:20:547708 base::RunLoop().Run();
7709
7710 EXPECT_TRUE(d.request_failed());
mmenkefe5d0b112016-09-06 20:46:587711 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7712 EXPECT_THAT(req->status().error(), IsError(ERR_NETWORK_IO_SUSPENDED));
[email protected]80abdad2014-03-15 00:20:547713}
7714
mmenke2281f3762015-11-02 20:38:177715namespace {
[email protected]80abdad2014-03-15 00:20:547716
mmenke2281f3762015-11-02 20:38:177717// HttpTransactionFactory that synchronously fails to create transactions.
7718class FailingHttpTransactionFactory : public HttpTransactionFactory {
7719 public:
7720 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7721 : network_session_(network_session) {}
7722
7723 ~FailingHttpTransactionFactory() override {}
7724
7725 // HttpTransactionFactory methods:
7726 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367727 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177728 return ERR_FAILED;
7729 }
7730
7731 HttpCache* GetCache() override { return nullptr; }
7732
7733 HttpNetworkSession* GetSession() override { return network_session_; }
7734
7735 private:
7736 HttpNetworkSession* network_session_;
7737
7738 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7739};
7740
7741} // namespace
7742
7743// Check that when a request that fails to create an HttpTransaction can be
7744// cancelled while the failure notification is pending, and doesn't send two
7745// failure notifications.
7746//
7747// This currently only happens when in suspend mode and there's no cache, but
7748// just use a special HttpTransactionFactory, to avoid depending on those
7749// behaviors.
7750TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7751 FailingHttpTransactionFactory http_transaction_factory(
7752 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547753 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177754 context.set_http_transaction_factory(&http_transaction_factory);
7755 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547756 context.Init();
7757
7758 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367759 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367760 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177761 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7762 // try to create an HttpNetworkTransaction synchronously on start).
7763 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197764 req->Start();
mmenke2281f3762015-11-02 20:38:177765 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547766 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177767 // Run pending error task, if there is one.
7768 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547769
7770 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177771 EXPECT_EQ(1, d.response_started_count());
mmenkefe5d0b112016-09-06 20:46:587772 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
mmenke2281f3762015-11-02 20:38:177773
7774 // NetworkDelegate should see the cancellation, but not the error.
7775 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7776 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547777}
7778
ttuttlec0c828492015-05-15 01:25:557779TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557780 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557781
7782 TestDelegate d;
tommycli59a63432015-11-06 00:10:557783 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367784 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557785 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7786
7787 req->Start();
7788 base::RunLoop().Run();
7789
7790 EXPECT_TRUE(req->response_info().network_accessed);
7791}
7792
7793TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557794 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557795
7796 // Populate the cache.
7797 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367798 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557799 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557800 req->Start();
7801 base::RunLoop().Run();
7802
mmenkefe5d0b112016-09-06 20:46:587803 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
ttuttlec0c828492015-05-15 01:25:557804 EXPECT_TRUE(req->response_info().network_accessed);
7805 EXPECT_FALSE(req->response_info().was_cached);
7806
tommycli59a63432015-11-06 00:10:557807 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557808 DEFAULT_PRIORITY, &d);
7809 req->Start();
7810 base::RunLoop().Run();
7811
mmenkefe5d0b112016-09-06 20:46:587812 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
ttuttlec0c828492015-05-15 01:25:557813 EXPECT_FALSE(req->response_info().network_accessed);
7814 EXPECT_TRUE(req->response_info().was_cached);
7815}
7816
7817TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557818 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557819
7820 TestDelegate d;
tommycli59a63432015-11-06 00:10:557821 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367822 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557823 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7824 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7825
7826 req->Start();
7827 base::RunLoop().Run();
7828
7829 EXPECT_FALSE(req->response_info().network_accessed);
7830}
7831
ricea3a1c71f2016-06-17 10:05:267832TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
7833 ASSERT_TRUE(http_test_server()->Start());
7834
7835 TestDelegate d;
7836 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7837 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
7838 req->Start();
7839 base::RunLoop().Run();
7840
7841 EXPECT_EQ(5, req->GetRawBodyBytes());
7842}
7843
7844TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
7845 ASSERT_TRUE(http_test_server()->Start());
7846
7847 TestDelegate d;
7848 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7849 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
7850 req->Start();
7851 base::RunLoop().Run();
7852
7853 EXPECT_EQ(30, req->GetRawBodyBytes());
7854}
7855
bengr1bf8e942014-11-07 01:36:507856class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7857 public:
7858 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7859 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7860 // tests into the factory tests.
7861 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7862 }
7863
7864 void SetUpFactory() override {
7865 interceptor_ = new MockURLRequestInterceptor();
7866 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:367867 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:507868 }
7869
7870 MockURLRequestInterceptor* interceptor() const {
7871 return interceptor_;
7872 }
7873
7874 private:
7875 MockURLRequestInterceptor* interceptor_;
7876};
7877
7878TEST_F(URLRequestInterceptorTestHTTP,
7879 NetworkDelegateNotificationOnRedirectIntercept) {
7880 interceptor()->set_intercept_redirect(true);
7881 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7882 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7883
tommycli59a63432015-11-06 00:10:557884 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507885
7886 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367887 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557888 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507889 req->Start();
7890 base::RunLoop().Run();
7891
7892 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7893 // Check we got one good response
mmenkefe5d0b112016-09-06 20:46:587894 EXPECT_TRUE(req->status().is_success());
7895 if (req->status().is_success())
bengr1bf8e942014-11-07 01:36:507896 EXPECT_EQ(200, req->response_headers()->response_code());
7897
7898 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7899 EXPECT_EQ(1, d.response_started_count());
7900 EXPECT_EQ(0, d.received_redirect_count());
7901
7902 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007903 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507904 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7905}
7906
7907TEST_F(URLRequestInterceptorTestHTTP,
7908 NetworkDelegateNotificationOnErrorIntercept) {
7909 // Intercept that error and respond with an OK response.
7910 interceptor()->set_intercept_final_response(true);
7911 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7912 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7913 default_network_delegate()->set_can_be_intercepted_on_error(true);
7914
tommycli59a63432015-11-06 00:10:557915 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507916
7917 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367918 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557919 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367920 &d));
bengr1bf8e942014-11-07 01:36:507921 req->set_method("GET");
7922 req->Start();
7923 base::RunLoop().Run();
7924
7925 EXPECT_TRUE(interceptor()->did_intercept_final());
7926
7927 // Check we received one good response.
mmenkefe5d0b112016-09-06 20:46:587928 EXPECT_TRUE(req->status().is_success());
7929 if (req->status().is_success())
bengr1bf8e942014-11-07 01:36:507930 EXPECT_EQ(200, req->response_headers()->response_code());
7931 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7932 EXPECT_EQ(1, d.response_started_count());
7933 EXPECT_EQ(0, d.received_redirect_count());
7934
7935 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007936 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507937 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7938}
7939
7940TEST_F(URLRequestInterceptorTestHTTP,
7941 NetworkDelegateNotificationOnResponseIntercept) {
7942 // Intercept that error and respond with an OK response.
7943 interceptor()->set_intercept_final_response(true);
7944
7945 // Intercept with a real URLRequestHttpJob.
7946 interceptor()->set_use_url_request_http_job(true);
7947
tommycli59a63432015-11-06 00:10:557948 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507949
7950 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367951 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557952 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507953 req->set_method("GET");
7954 req->Start();
7955 base::RunLoop().Run();
7956
7957 EXPECT_TRUE(interceptor()->did_intercept_final());
7958
7959 // Check we received one good response.
mmenkefe5d0b112016-09-06 20:46:587960 EXPECT_TRUE(req->status().is_success());
7961 if (req->status().is_success())
bengr1bf8e942014-11-07 01:36:507962 EXPECT_EQ(200, req->response_headers()->response_code());
7963 EXPECT_EQ("hello", d.data_received());
7964 EXPECT_EQ(1, d.response_started_count());
7965 EXPECT_EQ(0, d.received_redirect_count());
7966
7967 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007968 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507969 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7970}
7971
mkwst0c5eab872014-11-21 14:18:547972class URLRequestTestReferrerPolicy : public URLRequestTest {
7973 public:
7974 URLRequestTestReferrerPolicy() {}
7975
tommycli59a63432015-11-06 00:10:557976 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7977 origin_server_.reset(new EmbeddedTestServer(type));
7978 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7979 origin_server_->AddDefaultHandlers(
7980 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7981 } else {
7982 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7983 }
mkwst0c5eab872014-11-21 14:18:547984 ASSERT_TRUE(origin_server_->Start());
7985 }
7986
tommycli59a63432015-11-06 00:10:557987 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7988 net::EmbeddedTestServer::Type dest_type) {
7989 origin_server_.reset(new EmbeddedTestServer(origin_type));
7990 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7991 origin_server_->AddDefaultHandlers(
7992 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7993 } else {
7994 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7995 }
mkwst0c5eab872014-11-21 14:18:547996 ASSERT_TRUE(origin_server_->Start());
7997
tommycli59a63432015-11-06 00:10:557998 destination_server_.reset(new EmbeddedTestServer(dest_type));
7999 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8000 destination_server_->AddDefaultHandlers(
8001 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8002 } else {
8003 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8004 }
mkwst0c5eab872014-11-21 14:18:548005 ASSERT_TRUE(destination_server_->Start());
8006 }
8007
8008 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8009 const GURL& referrer,
8010 const GURL& expected) {
8011 // Create and execute the request: we'll only have a |destination_server_|
8012 // if the origins are meant to be distinct. Otherwise, we'll use the
8013 // |origin_server_| for both endpoints.
8014 GURL destination_url =
tommycli59a63432015-11-06 00:10:558015 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8016 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548017 GURL origin_url =
tommycli59a63432015-11-06 00:10:558018 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548019
8020 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368021 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368022 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548023 req->set_referrer_policy(policy);
8024 req->SetReferrer(referrer.spec());
8025 req->Start();
8026 base::RunLoop().Run();
8027
8028 EXPECT_EQ(1, d.response_started_count());
8029 EXPECT_EQ(1, d.received_redirect_count());
8030 EXPECT_EQ(destination_url, req->url());
mmenkefe5d0b112016-09-06 20:46:588031 EXPECT_TRUE(req->status().is_success());
mkwst0c5eab872014-11-21 14:18:548032 EXPECT_EQ(200, req->response_headers()->response_code());
8033
8034 EXPECT_EQ(expected.spec(), req->referrer());
8035 if (expected.is_empty())
8036 EXPECT_EQ("None", d.data_received());
8037 else
8038 EXPECT_EQ(expected.spec(), d.data_received());
8039 }
8040
tommycli59a63432015-11-06 00:10:558041 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548042
8043 private:
danakj8522a25b2016-04-16 00:17:368044 std::unique_ptr<EmbeddedTestServer> origin_server_;
8045 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548046};
8047
8048TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558049 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548050
8051 VerifyReferrerAfterRedirect(
8052 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558053 origin_server()->GetURL("/path/to/file.html"),
8054 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548055
8056 VerifyReferrerAfterRedirect(
8057 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558058 origin_server()->GetURL("/path/to/file.html"),
8059 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548060
8061 VerifyReferrerAfterRedirect(
8062 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558063 origin_server()->GetURL("/path/to/file.html"),
8064 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548065
8066 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558067 origin_server()->GetURL("/path/to/file.html"),
8068 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548069}
8070
tommycli59a63432015-11-06 00:10:558071TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8072 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8073 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548074
8075 VerifyReferrerAfterRedirect(
8076 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558077 origin_server()->GetURL("/path/to/file.html"),
8078 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548079
8080 VerifyReferrerAfterRedirect(
8081 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558082 origin_server()->GetURL("/path/to/file.html"),
8083 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548084
8085 VerifyReferrerAfterRedirect(
8086 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558087 origin_server()->GetURL("/path/to/file.html"),
8088 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548089
8090 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558091 origin_server()->GetURL("/path/to/file.html"),
8092 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548093}
8094
8095TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558096 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548097
8098 VerifyReferrerAfterRedirect(
8099 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558100 origin_server()->GetURL("/path/to/file.html"),
8101 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548102
8103 VerifyReferrerAfterRedirect(
8104 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558105 origin_server()->GetURL("/path/to/file.html"),
8106 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548107
8108 VerifyReferrerAfterRedirect(
8109 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558110 origin_server()->GetURL("/path/to/file.html"),
8111 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548112
8113 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558114 origin_server()->GetURL("/path/to/file.html"),
8115 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548116}
8117
tommycli59a63432015-11-06 00:10:558118TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8119 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8120 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548121
8122 VerifyReferrerAfterRedirect(
8123 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558124 origin_server()->GetURL("/path/to/file.html"),
8125 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548126
8127 VerifyReferrerAfterRedirect(
8128 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558129 origin_server()->GetURL("/path/to/file.html"),
8130 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548131
8132 VerifyReferrerAfterRedirect(
8133 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558134 origin_server()->GetURL("/path/to/file.html"),
8135 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548136
8137 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558138 origin_server()->GetURL("/path/to/file.html"),
8139 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548140}
8141
tommycli59a63432015-11-06 00:10:558142TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8143 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8144 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548145
8146 VerifyReferrerAfterRedirect(
8147 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558148 origin_server()->GetURL("/path/to/file.html"),
8149 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548150
8151 VerifyReferrerAfterRedirect(
8152 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558153 origin_server()->GetURL("/path/to/file.html"),
8154 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548155
8156 VerifyReferrerAfterRedirect(
8157 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558158 origin_server()->GetURL("/path/to/file.html"),
8159 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548160
8161 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558162 origin_server()->GetURL("/path/to/file.html"),
8163 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548164}
8165
tommycli59a63432015-11-06 00:10:558166TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8167 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8168 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548169
8170 VerifyReferrerAfterRedirect(
8171 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558172 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548173
8174 VerifyReferrerAfterRedirect(
8175 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558176 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548177
8178 VerifyReferrerAfterRedirect(
8179 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558180 origin_server()->GetURL("/path/to/file.html"),
8181 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548182
8183 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558184 origin_server()->GetURL("/path/to/file.html"),
8185 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548186}
8187
[email protected]73e0bba2009-02-19 22:57:098188class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508189 public:
[email protected]ef2bf422012-05-11 03:27:098190 HTTPSRequestTest() : default_context_(true) {
8191 default_context_.set_network_delegate(&default_network_delegate_);
8192 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508193 }
dcheng67be2b1f2014-10-27 21:47:298194 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508195
8196 protected:
[email protected]ceefd7fd2012-11-29 00:36:248197 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098198 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468199};
8200
[email protected]c044616e2013-02-20 02:01:268201TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558202 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8203 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228204 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118205 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468206
[email protected]ea224582008-12-07 20:25:468207 TestDelegate d;
8208 {
danakj8522a25b2016-04-16 00:17:368209 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558210 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198211 r->Start();
8212 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468213
[email protected]255620da2013-08-19 13:14:298214 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468215
8216 EXPECT_EQ(1, d.response_started_count());
8217 EXPECT_FALSE(d.received_data_before_response());
8218 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198219 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198220 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198221 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198222 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198223 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468224 }
[email protected]ea224582008-12-07 20:25:468225}
8226
[email protected]5774ada2010-07-15 06:30:548227TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558228 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8229 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8230 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228231 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118232 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338233
8234 bool err_allowed = true;
8235 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8236 TestDelegate d;
8237 {
8238 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368239 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558240 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338241
[email protected]f7022f32014-08-21 16:32:198242 r->Start();
8243 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338244
[email protected]255620da2013-08-19 13:14:298245 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338246
8247 EXPECT_EQ(1, d.response_started_count());
8248 EXPECT_FALSE(d.received_data_before_response());
8249 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178250 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338251 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198252 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178253 } else {
[email protected]bacff652009-03-31 17:50:338254 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178255 }
[email protected]bacff652009-03-31 17:50:338256 }
8257 }
8258}
8259
[email protected]5774ada2010-07-15 06:30:548260TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558261 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8262 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8263 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228264 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118265 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338266
8267 // Iterate from false to true, just so that we do the opposite of the
8268 // previous test in order to increase test coverage.
8269 bool err_allowed = false;
8270 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8271 TestDelegate d;
8272 {
8273 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368274 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558275 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338276
[email protected]f7022f32014-08-21 16:32:198277 r->Start();
8278 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338279
[email protected]255620da2013-08-19 13:14:298280 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338281
8282 EXPECT_EQ(1, d.response_started_count());
8283 EXPECT_FALSE(d.received_data_before_response());
8284 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178285 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338286 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198287 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178288 } else {
[email protected]bacff652009-03-31 17:50:338289 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178290 }
[email protected]bacff652009-03-31 17:50:338291 }
8292 }
8293}
[email protected]73e0bba2009-02-19 22:57:098294
tommycli59a63432015-11-06 00:10:558295// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8296// security state. (see http://crbug.com/550977).
8297#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448298// This tests that a load of www.google.com with a certificate error sets
8299// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8300// the interstitial to be fatal.
8301TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558302 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8303 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8304 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448305 ASSERT_TRUE(test_server.Start());
8306
8307 // We require that the URL be www.google.com in order to pick up the
8308 // preloaded HSTS entries in the TransportSecurityState. This means that we
8309 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248310 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448311
8312 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248313 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448314 TestURLRequestContext context(true);
8315 context.set_network_delegate(&network_delegate);
8316 context.set_host_resolver(&host_resolver);
8317 TransportSecurityState transport_security_state;
8318 context.set_transport_security_state(&transport_security_state);
8319 context.Init();
8320
8321 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368322 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198323 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368324 test_server.host_port_pair().port())),
8325 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448326
[email protected]f7022f32014-08-21 16:32:198327 r->Start();
8328 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448329
[email protected]255620da2013-08-19 13:14:298330 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448331
8332 EXPECT_EQ(1, d.response_started_count());
8333 EXPECT_FALSE(d.received_data_before_response());
8334 EXPECT_TRUE(d.have_certificate_errors());
8335 EXPECT_TRUE(d.certificate_errors_are_fatal());
8336}
8337
8338// This tests that cached HTTPS page loads do not cause any updates to the
8339// TransportSecurityState.
8340TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8341 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8342 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558343 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8344 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8345 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448346 ASSERT_TRUE(test_server.Start());
8347
[email protected]9e6968d2014-05-07 21:46:268348 // We require that the URL be www.google.com in order to pick up the static
8349 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8350 // that we have to use a MockHostResolver in order to direct www.google.com to
8351 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448352
8353 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248354 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448355 TestURLRequestContext context(true);
8356 context.set_network_delegate(&network_delegate);
8357 context.set_host_resolver(&host_resolver);
8358 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268359
martijnc0d6b622015-06-30 19:14:408360 TransportSecurityState::STSState static_sts_state;
8361 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268362 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408363 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448364 context.set_transport_security_state(&transport_security_state);
8365 context.Init();
8366
martijnc0d6b622015-06-30 19:14:408367 TransportSecurityState::STSState dynamic_sts_state;
8368 TransportSecurityState::PKPState dynamic_pkp_state;
8369 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8370 &dynamic_sts_state));
8371 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8372 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268373
[email protected]316c1e5e2012-09-12 15:17:448374 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368375 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198376 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368377 test_server.host_port_pair().port())),
8378 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448379
[email protected]f7022f32014-08-21 16:32:198380 r->Start();
8381 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448382
[email protected]255620da2013-08-19 13:14:298383 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448384
8385 EXPECT_EQ(1, d.response_started_count());
8386 EXPECT_FALSE(d.received_data_before_response());
8387 EXPECT_TRUE(d.have_certificate_errors());
8388 EXPECT_TRUE(d.certificate_errors_are_fatal());
8389
[email protected]9e6968d2014-05-07 21:46:268390 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408391 TransportSecurityState::STSState new_static_sts_state;
8392 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268393 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408394 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8395 TransportSecurityState::STSState new_dynamic_sts_state;
8396 TransportSecurityState::PKPState new_dynamic_pkp_state;
8397 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8398 "www.google.com", &new_dynamic_sts_state));
8399 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8400 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268401
martijnc0d6b622015-06-30 19:14:408402 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8403 EXPECT_EQ(new_static_sts_state.include_subdomains,
8404 static_sts_state.include_subdomains);
8405 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8406 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488407 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8408 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8409 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448410}
8411
[email protected]8ccc69f2012-11-28 19:52:148412// Make sure HSTS preserves a POST request's method and body.
8413TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8414 static const char kData[] = "hello world";
8415
tommycli59a63432015-11-06 00:10:558416 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8417 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228418 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148419 ASSERT_TRUE(test_server.Start());
8420
8421
8422 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8423 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558424 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228425 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148426 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148427
8428 // Force https for www.somewhere.com.
8429 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208430 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8431 bool include_subdomains = false;
8432 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8433 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148434
8435 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8436
8437 TestURLRequestContext context(true);
8438 context.set_host_resolver(&host_resolver);
8439 context.set_transport_security_state(&transport_security_state);
8440 context.set_network_delegate(&network_delegate);
8441 context.Init();
8442
8443 TestDelegate d;
8444 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8445 // cause a certificate error. Ignore the error.
8446 d.set_allow_certificate_errors(true);
8447
danakj8522a25b2016-04-16 00:17:368448 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198449 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368450 test_server.host_port_pair().port())),
8451 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198452 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078453 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148454
[email protected]f7022f32014-08-21 16:32:198455 req->Start();
[email protected]255620da2013-08-19 13:14:298456 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148457
[email protected]f7022f32014-08-21 16:32:198458 EXPECT_EQ("https", req->url().scheme());
8459 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148460 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408461
8462 LoadTimingInfo load_timing_info;
8463 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8464 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8465 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148466}
8467
rob4e0be1f2014-09-11 23:40:228468// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8469TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8470 static const char kOriginHeaderValue[] = "http://www.example.com";
8471
tommycli59a63432015-11-06 00:10:558472 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8473 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228474 ASSERT_TRUE(test_server.Start());
8475
8476 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8477 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558478 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8479 // default.
rob4e0be1f2014-09-11 23:40:228480 MockHostResolver host_resolver;
8481
8482 TransportSecurityState transport_security_state;
8483 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8484 bool include_subdomains = false;
8485 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8486
8487 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8488
8489 MockCertVerifier cert_verifier;
8490 cert_verifier.set_default_result(OK);
8491
8492 TestURLRequestContext context(true);
8493 context.set_host_resolver(&host_resolver);
8494 context.set_transport_security_state(&transport_security_state);
8495 context.set_network_delegate(&network_delegate);
8496 context.set_cert_verifier(&cert_verifier);
8497 context.Init();
8498
8499 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8500 test_server.host_port_pair().port()));
8501 url::Replacements<char> replacements;
8502 const char kNewScheme[] = "https";
8503 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8504 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8505
8506 TestDelegate d;
8507 // Quit on redirect to allow response header inspection upon redirect.
8508 d.set_quit_on_redirect(true);
8509
danakj8522a25b2016-04-16 00:17:368510 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368511 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228512 // Set Origin header to simulate a cross-origin request.
8513 HttpRequestHeaders request_headers;
8514 request_headers.SetHeader("Origin", kOriginHeaderValue);
8515 req->SetExtraRequestHeaders(request_headers);
8516
8517 req->Start();
8518 base::RunLoop().Run();
8519
8520 EXPECT_EQ(1, d.received_redirect_count());
8521
8522 const HttpResponseHeaders* headers = req->response_headers();
8523 std::string redirect_location;
8524 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8525 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8526
8527 std::string received_cors_header;
8528 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8529 &received_cors_header));
8530 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8531}
8532
davidbenb4c25b62016-06-24 02:39:278533// Test that DHE-only servers fail with the expected dedicated error code.
8534TEST_F(HTTPSRequestTest, DHE) {
8535 SpawnedTestServer::SSLOptions ssl_options;
8536 ssl_options.key_exchanges =
8537 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
8538 SpawnedTestServer test_server(
8539 SpawnedTestServer::TYPE_HTTPS, ssl_options,
8540 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8541 ASSERT_TRUE(test_server.Start());
8542
8543 TestDelegate d;
8544 {
8545 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8546 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
8547
8548 r->Start();
8549 EXPECT_TRUE(r->is_pending());
8550
8551 base::RunLoop().Run();
8552
8553 EXPECT_EQ(1, d.response_started_count());
mmenkefe5d0b112016-09-06 20:46:588554 EXPECT_FALSE(r->status().is_success());
8555 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8556 EXPECT_THAT(r->status().error(), IsError(ERR_SSL_OBSOLETE_CIPHER));
davidbenb4c25b62016-06-24 02:39:278557 }
8558}
8559
[email protected]316c1e5e2012-09-12 15:17:448560namespace {
8561
8562class SSLClientAuthTestDelegate : public TestDelegate {
8563 public:
8564 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8565 }
dchengb03027d2014-10-21 12:00:208566 void OnCertificateRequested(URLRequest* request,
8567 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448568 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178569 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448570 }
8571 int on_certificate_requested_count() {
8572 return on_certificate_requested_count_;
8573 }
8574 private:
8575 int on_certificate_requested_count_;
8576};
8577
8578} // namespace
8579
8580// TODO(davidben): Test the rest of the code. Specifically,
8581// - Filtering which certificates to select.
8582// - Sending a certificate back.
8583// - Getting a certificate request in an SSL renegotiation sending the
8584// HTTP request.
8585TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558586 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8587 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128588 ssl_config.client_cert_type =
8589 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558590 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8591 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228592 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448593 ASSERT_TRUE(test_server.Start());
8594
8595 SSLClientAuthTestDelegate d;
8596 {
danakj8522a25b2016-04-16 00:17:368597 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558598 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448599
[email protected]f7022f32014-08-21 16:32:198600 r->Start();
8601 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448602
[email protected]255620da2013-08-19 13:14:298603 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448604
8605 EXPECT_EQ(1, d.on_certificate_requested_count());
8606 EXPECT_FALSE(d.received_data_before_response());
8607 EXPECT_EQ(0, d.bytes_received());
8608
8609 // Send no certificate.
8610 // TODO(davidben): Get temporary client cert import (with keys) working on
8611 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548612 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448613
[email protected]255620da2013-08-19 13:14:298614 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448615
8616 EXPECT_EQ(1, d.response_started_count());
8617 EXPECT_FALSE(d.received_data_before_response());
8618 EXPECT_NE(0, d.bytes_received());
8619 }
8620}
8621
8622TEST_F(HTTPSRequestTest, ResumeTest) {
8623 // Test that we attempt a session resume when making two connections to the
8624 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228625 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448626 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228627 SpawnedTestServer test_server(
8628 SpawnedTestServer::TYPE_HTTPS,
8629 ssl_options,
8630 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448631 ASSERT_TRUE(test_server.Start());
8632
8633 SSLClientSocket::ClearSessionCache();
8634
8635 {
8636 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368637 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368638 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448639
[email protected]f7022f32014-08-21 16:32:198640 r->Start();
8641 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448642
[email protected]255620da2013-08-19 13:14:298643 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448644
8645 EXPECT_EQ(1, d.response_started_count());
8646 }
8647
8648 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8649 CloseAllConnections();
8650
8651 {
8652 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368653 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368654 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448655
[email protected]f7022f32014-08-21 16:32:198656 r->Start();
8657 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448658
[email protected]255620da2013-08-19 13:14:298659 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448660
8661 // The response will look like;
8662 // insert abc
8663 // lookup abc
8664 // insert xyz
8665 //
8666 // With a newline at the end which makes the split think that there are
8667 // four lines.
8668
8669 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298670 std::vector<std::string> lines = base::SplitString(
8671 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448672 ASSERT_EQ(4u, lines.size()) << d.data_received();
8673
8674 std::string session_id;
8675
8676 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298677 std::vector<std::string> parts = base::SplitString(
8678 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448679 ASSERT_EQ(2u, parts.size());
8680 if (i == 0) {
8681 EXPECT_EQ("insert", parts[0]);
8682 session_id = parts[1];
8683 } else {
8684 EXPECT_EQ("lookup", parts[0]);
8685 EXPECT_EQ(session_id, parts[1]);
8686 }
8687 }
8688 }
8689}
8690
Adam Langley32352ad2014-10-14 22:31:008691// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8692// the result of fetching "ssl-session-cache" from the test server, indicates
8693// that exactly two different sessions were inserted, with no lookups etc.
8694static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298695 std::vector<std::string> lines = base::SplitString(
8696 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008697 ASSERT_EQ(3u, lines.size()) << session_info;
8698
8699 std::string session_id;
8700 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298701 std::vector<std::string> parts = base::SplitString(
8702 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008703 ASSERT_EQ(2u, parts.size());
8704 EXPECT_EQ("insert", parts[0]);
8705 if (i == 0) {
8706 session_id = parts[1];
8707 } else {
8708 EXPECT_NE(session_id, parts[1]);
8709 }
8710 }
8711}
8712
[email protected]316c1e5e2012-09-12 15:17:448713TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8714 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8715 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228716 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448717 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228718 SpawnedTestServer test_server(
8719 SpawnedTestServer::TYPE_HTTPS,
8720 ssl_options,
8721 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448722 ASSERT_TRUE(test_server.Start());
8723
8724 SSLClientSocket::ClearSessionCache();
8725
8726 {
8727 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368728 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368729 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448730
[email protected]f7022f32014-08-21 16:32:198731 r->Start();
8732 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448733
[email protected]255620da2013-08-19 13:14:298734 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448735
8736 EXPECT_EQ(1, d.response_started_count());
8737 }
8738
8739 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8740 HttpNetworkSession::Params params;
8741 params.host_resolver = default_context_.host_resolver();
8742 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118743 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:208744 params.cert_transparency_verifier =
8745 default_context_.cert_transparency_verifier();
8746 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:448747 params.proxy_service = default_context_.proxy_service();
8748 params.ssl_config_service = default_context_.ssl_config_service();
8749 params.http_auth_handler_factory =
8750 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:448751 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448752
mmenkee65e7af2015-10-13 17:16:428753 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:368754 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428755 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448756
8757 default_context_.set_http_transaction_factory(cache.get());
8758
8759 {
8760 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368761 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368762 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448763
[email protected]f7022f32014-08-21 16:32:198764 r->Start();
8765 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448766
[email protected]255620da2013-08-19 13:14:298767 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448768
8769 // The response will look like;
8770 // insert abc
8771 // insert xyz
8772 //
8773 // With a newline at the end which makes the split think that there are
8774 // three lines.
8775
8776 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008777 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448778 }
8779}
8780
[email protected]48d2b7c52014-06-27 01:16:558781class HTTPSFallbackTest : public testing::Test {
8782 public:
Adam Langley32352ad2014-10-14 22:31:008783 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298784 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558785
8786 protected:
8787 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8788 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008789 context_.Init();
8790 delegate_.set_allow_certificate_errors(true);
8791
[email protected]48d2b7c52014-06-27 01:16:558792 SpawnedTestServer test_server(
8793 SpawnedTestServer::TYPE_HTTPS,
8794 ssl_options,
8795 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8796 ASSERT_TRUE(test_server.Start());
8797
tommycli59a63432015-11-06 00:10:558798 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8799 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558800 request_->Start();
8801
8802 base::RunLoop().Run();
8803 }
8804
8805 void ExpectConnection(int version) {
8806 EXPECT_EQ(1, delegate_.response_started_count());
8807 EXPECT_NE(0, delegate_.bytes_received());
8808 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8809 request_->ssl_info().connection_status));
8810 EXPECT_TRUE(request_->ssl_info().connection_status &
8811 SSL_CONNECTION_VERSION_FALLBACK);
8812 }
8813
8814 void ExpectFailure(int error) {
8815 EXPECT_EQ(1, delegate_.response_started_count());
mmenkefe5d0b112016-09-06 20:46:588816 EXPECT_FALSE(request_->status().is_success());
8817 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8818 EXPECT_EQ(error, request_->status().error());
[email protected]48d2b7c52014-06-27 01:16:558819 }
8820
8821 private:
8822 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:478823 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:368824 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:558825};
8826
davidbenb127ca82015-06-15 19:05:428827// Tests the TLS 1.0 fallback doesn't happen.
8828TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558829 SpawnedTestServer::SSLOptions ssl_options(
8830 SpawnedTestServer::SSLOptions::CERT_OK);
8831 ssl_options.tls_intolerant =
8832 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8833
8834 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558835 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:428836}
8837
davidben5a312152016-06-27 22:11:478838// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:558839TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:428840 SpawnedTestServer::SSLOptions ssl_options(
8841 SpawnedTestServer::SSLOptions::CERT_OK);
8842 ssl_options.tls_intolerant =
8843 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8844
8845 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:558846 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8847}
8848
[email protected]a8fed1742013-12-27 02:14:248849class HTTPSSessionTest : public testing::Test {
8850 public:
8851 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598852 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248853
8854 default_context_.set_network_delegate(&default_network_delegate_);
8855 default_context_.set_cert_verifier(&cert_verifier_);
8856 default_context_.Init();
8857 }
dcheng67be2b1f2014-10-27 21:47:298858 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248859
8860 protected:
8861 MockCertVerifier cert_verifier_;
8862 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8863 TestURLRequestContext default_context_;
8864};
8865
8866// Tests that session resumption is not attempted if an invalid certificate
8867// is presented.
8868TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8869 SpawnedTestServer::SSLOptions ssl_options;
8870 ssl_options.record_resume = true;
8871 SpawnedTestServer test_server(
8872 SpawnedTestServer::TYPE_HTTPS,
8873 ssl_options,
8874 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8875 ASSERT_TRUE(test_server.Start());
8876
8877 SSLClientSocket::ClearSessionCache();
8878
8879 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598880 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248881 {
8882 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368883 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368884 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248885
[email protected]f7022f32014-08-21 16:32:198886 r->Start();
8887 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248888
8889 base::RunLoop().Run();
8890
8891 EXPECT_EQ(1, d.response_started_count());
8892 }
8893
8894 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8895 CloseAllConnections();
8896
8897 // Now change the certificate to be acceptable (so that the response is
8898 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598899 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248900 {
8901 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368902 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368903 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248904
[email protected]f7022f32014-08-21 16:32:198905 r->Start();
8906 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248907
8908 base::RunLoop().Run();
8909
8910 // The response will look like;
8911 // insert abc
8912 // insert xyz
8913 //
8914 // With a newline at the end which makes the split think that there are
8915 // three lines.
8916 //
8917 // If a session was presented (eg: a bug), then the response would look
8918 // like;
8919 // insert abc
8920 // lookup abc
8921 // insert xyz
8922
8923 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008924 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248925 }
8926}
8927
[email protected]dffe8242012-03-20 15:14:278928// This the fingerprint of the "Testing CA" certificate used by the testserver.
8929// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268930static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278931 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8932 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8933
[email protected]51523f52013-07-31 21:57:288934// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8935// testserver.
8936static const SHA256HashValue kOCSPTestCertSPKI = { {
8937 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8938 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8939 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8940 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8941} };
8942
[email protected]dffe8242012-03-20 15:14:278943// This is the policy OID contained in the certificates that testserver
8944// generates.
8945static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8946
8947class HTTPSOCSPTest : public HTTPSRequestTest {
8948 public:
8949 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098950 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088951 ev_test_policy_(
8952 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8953 kOCSPTestCertFingerprint,
8954 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028955 }
8956
dcheng67be2b1f2014-10-27 21:47:298957 void SetUp() override {
rsleevid6de8302016-06-21 01:33:208958 context_.SetCTPolicyEnforcer(
8959 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
8960 SetupContext();
[email protected]ef2bf422012-05-11 03:27:098961 context_.Init();
[email protected]dffe8242012-03-20 15:14:278962
[email protected]cba24642014-08-15 20:49:598963 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208964 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428965 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508966 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278967
svaldez2135be52016-04-20 16:34:538968#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:098969 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278970 EnsureNSSHttpIOInit();
8971#endif
8972 }
8973
dadrian612337a2016-07-20 22:36:588974 void DoConnectionWithDelegate(
8975 const SpawnedTestServer::SSLOptions& ssl_options,
8976 TestDelegate* delegate,
8977 SSLInfo* out_ssl_info) {
8978 // Always overwrite |out_ssl_info|.
8979 out_ssl_info->Reset();
8980
[email protected]ce7d0cbc2013-05-03 18:57:228981 SpawnedTestServer test_server(
8982 SpawnedTestServer::TYPE_HTTPS,
8983 ssl_options,
8984 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278985 ASSERT_TRUE(test_server.Start());
8986
dadrian612337a2016-07-20 22:36:588987 delegate->set_allow_certificate_errors(true);
8988 std::unique_ptr<URLRequest> r(context_.CreateRequest(
8989 test_server.GetURL("/"), DEFAULT_PRIORITY, delegate));
[email protected]f7022f32014-08-21 16:32:198990 r->Start();
[email protected]dffe8242012-03-20 15:14:278991
[email protected]255620da2013-08-19 13:14:298992 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:588993 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:278994
dadrian612337a2016-07-20 22:36:588995 *out_ssl_info = r->ssl_info();
8996 }
8997
8998 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
8999 CertStatus* out_cert_status) {
9000 // Always overwrite |out_cert_status|.
9001 *out_cert_status = 0;
9002
9003 TestDelegate d;
9004 SSLInfo ssl_info;
9005 ASSERT_NO_FATAL_FAILURE(
9006 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
9007
9008 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:279009 }
9010
dcheng67be2b1f2014-10-27 21:47:299011 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:539012#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:279013 ShutdownNSSHttpIO();
9014#endif
9015 }
9016
[email protected]a13234c2012-03-20 21:45:029017 protected:
rsleevid6de8302016-06-21 01:33:209018 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9019 public:
9020 AllowAnyCertCTPolicyEnforcer() = default;
9021 ~AllowAnyCertCTPolicyEnforcer() override = default;
9022
9023 ct::CertPolicyCompliance DoesConformToCertPolicy(
9024 X509Certificate* cert,
9025 const SCTList& verified_scts,
9026 const BoundNetLog& net_log) override {
9027 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9028 }
9029
9030 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9031 X509Certificate* cert,
9032 const ct::EVCertsWhitelist* ev_whitelist,
9033 const SCTList& verified_scts,
9034 const BoundNetLog& net_log) override {
9035 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9036 }
9037 };
[email protected]a13234c2012-03-20 21:45:029038 // SetupContext configures the URLRequestContext that will be used for making
9039 // connetions to testserver. This can be overridden in test subclasses for
9040 // different behaviour.
rsleevid6de8302016-06-21 01:33:209041 virtual void SetupContext() {
9042 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149043 true /* check for EV */, true /* online revocation checking */,
9044 false /* require rev. checking for local
9045 anchors */,
9046 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029047 }
9048
danakj8522a25b2016-04-16 00:17:369049 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099050 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369051 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279052};
9053
[email protected]a13234c2012-03-20 21:45:029054static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:019055#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029056 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9057 // have that ability on other platforms.
9058 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9059#else
9060 return 0;
9061#endif
9062}
9063
[email protected]3a86a712013-07-30 07:16:209064// SystemSupportsHardFailRevocationChecking returns true iff the current
9065// operating system supports revocation checking and can distinguish between
9066// situations where a given certificate lacks any revocation information (eg:
9067// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9068// revocation information cannot be obtained (eg: the CRL was unreachable).
9069// If it does not, then tests which rely on 'hard fail' behaviour should be
9070// skipped.
9071static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539072#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209073 return true;
9074#else
9075 return false;
9076#endif
9077}
9078
[email protected]a13234c2012-03-20 21:45:029079// SystemUsesChromiumEVMetadata returns true iff the current operating system
9080// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9081// several tests are effected because our testing EV certificate won't be
9082// recognised as EV.
9083static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329084#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579085 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9086 return false;
[email protected]e1b2d732014-03-28 16:20:329087#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9088 // On OS X and Android, we use the system to tell us whether a certificate is
9089 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019090 return false;
9091#else
9092 return true;
9093#endif
9094}
9095
[email protected]b6f2de32012-08-17 04:35:089096static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339097#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029098 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9099 return false;
9100#else
9101 return true;
9102#endif
9103}
9104
davidbend1fb2f12014-11-08 02:51:009105static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339106#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039107 return true;
mathpc992e602015-10-21 20:34:039108#else
9109 return false;
9110#endif
davidbend1fb2f12014-11-08 02:51:009111}
9112
[email protected]dffe8242012-03-20 15:14:279113TEST_F(HTTPSOCSPTest, Valid) {
9114 if (!SystemSupportsOCSP()) {
9115 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9116 return;
9117 }
9118
[email protected]ce7d0cbc2013-05-03 18:57:229119 SpawnedTestServer::SSLOptions ssl_options(
9120 SpawnedTestServer::SSLOptions::CERT_AUTO);
9121 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279122
[email protected]924e9f92012-12-16 22:00:539123 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129124 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279125
9126 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9127
[email protected]a13234c2012-03-20 21:45:029128 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9129 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279130
9131 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9132}
9133
9134TEST_F(HTTPSOCSPTest, Revoked) {
9135 if (!SystemSupportsOCSP()) {
9136 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9137 return;
9138 }
9139
[email protected]ce7d0cbc2013-05-03 18:57:229140 SpawnedTestServer::SSLOptions ssl_options(
9141 SpawnedTestServer::SSLOptions::CERT_AUTO);
9142 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279143
9144 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129145 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279146
[email protected]a592c0432012-12-01 18:10:299147#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279148 // Doesn't pass on OS X yet for reasons that need to be investigated.
9149 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9150#endif
9151 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9152 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9153}
9154
9155TEST_F(HTTPSOCSPTest, Invalid) {
9156 if (!SystemSupportsOCSP()) {
9157 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9158 return;
9159 }
9160
[email protected]ce7d0cbc2013-05-03 18:57:229161 SpawnedTestServer::SSLOptions ssl_options(
9162 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589163 ssl_options.ocsp_status =
9164 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:279165
[email protected]924e9f92012-12-16 22:00:539166 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129167 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279168
[email protected]a13234c2012-03-20 21:45:029169 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279170 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279171
9172 // Without a positive OCSP response, we shouldn't show the EV status.
9173 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9174 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9175}
[email protected]a13234c2012-03-20 21:45:029176
davidbend1fb2f12014-11-08 02:51:009177TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039178 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009179 LOG(WARNING)
9180 << "Skipping test because system doesn't support OCSP stapling";
9181 return;
9182 }
9183
9184 SpawnedTestServer::SSLOptions ssl_options(
9185 SpawnedTestServer::SSLOptions::CERT_AUTO);
9186 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9187 ssl_options.staple_ocsp_response = true;
9188 ssl_options.ocsp_server_unavailable = true;
9189
9190 CertStatus cert_status;
9191 DoConnection(ssl_options, &cert_status);
9192
9193 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9194
9195 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9196 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9197
9198 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9199}
9200
davidben6c3191b2014-11-21 22:38:049201// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489202#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049203#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9204#else
9205#define MAYBE_RevokedStapled RevokedStapled
9206#endif
9207TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039208 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009209 LOG(WARNING)
9210 << "Skipping test because system doesn't support OCSP stapling";
9211 return;
9212 }
9213
9214 SpawnedTestServer::SSLOptions ssl_options(
9215 SpawnedTestServer::SSLOptions::CERT_AUTO);
9216 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9217 ssl_options.staple_ocsp_response = true;
9218 ssl_options.ocsp_server_unavailable = true;
9219
9220 CertStatus cert_status;
9221 DoConnection(ssl_options, &cert_status);
9222
9223 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9224 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9225 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9226}
9227
dadriand476e652016-07-26 21:33:249228TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
9229 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9230 https_test_server.SetSSLConfig(
9231 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9232 https_test_server.ServeFilesFromSourceDirectory(
9233 base::FilePath(kTestFilePath));
9234 ASSERT_TRUE(https_test_server.Start());
9235
9236 // Set up a MockCertVerifier to accept the certificate that the server sends,
9237 // but not provide any OCSP information.
9238 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9239 ASSERT_TRUE(cert);
9240 MockCertVerifier cert_verifier;
9241 CertVerifyResult verify_result;
9242 verify_result.verified_cert = cert;
9243 verify_result.is_issued_by_known_root = true;
9244 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9245 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9246
9247 // Catch the Expect-Staple report.
9248 TransportSecurityState transport_security_state;
9249 MockCertificateReportSender mock_report_sender;
9250 transport_security_state.SetReportSender(&mock_report_sender);
9251
9252 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9253 // that the request can be sent to a site on the Expect-Staple preload list.
9254 MockHostResolver host_resolver;
9255 TestNetworkDelegate network_delegate;
9256 TestURLRequestContext context(true);
9257 context.set_host_resolver(&host_resolver);
9258 context.set_transport_security_state(&transport_security_state);
9259 context.set_network_delegate(&network_delegate);
9260 context.set_cert_verifier(&cert_verifier);
9261 context.Init();
9262
9263 // Now send a request to trigger the violation.
9264 TestDelegate d;
9265 GURL url = https_test_server.GetURL("/");
9266 GURL::Replacements replace_host;
9267 replace_host.SetHostStr(kExpectStapleStaticHostname);
9268 url = url.ReplaceComponents(replace_host);
9269 std::unique_ptr<URLRequest> violating_request(
9270 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9271 violating_request->Start();
9272 base::RunLoop().Run();
9273
9274 // Confirm a report was sent.
9275 EXPECT_FALSE(mock_report_sender.latest_report().empty());
9276 EXPECT_EQ(GURL(kExpectStapleReportURI),
9277 mock_report_sender.latest_report_uri());
9278}
9279
9280TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
9281 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9282 https_test_server.SetSSLConfig(
9283 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9284 https_test_server.ServeFilesFromSourceDirectory(
9285 base::FilePath(kTestFilePath));
9286 ASSERT_TRUE(https_test_server.Start());
9287
9288 // Set up a MockCertVerifier to accept the certificate that the server sends,
9289 // and provide GOOD revocation status.
9290 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9291 ASSERT_TRUE(cert);
9292 MockCertVerifier cert_verifier;
9293 CertVerifyResult verify_result;
9294 verify_result.verified_cert = cert;
9295 verify_result.is_issued_by_known_root = true;
9296 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
9297 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
9298 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9299
9300 // Catch the Expect-Staple report.
9301 TransportSecurityState transport_security_state;
9302 MockCertificateReportSender mock_report_sender;
9303 transport_security_state.SetReportSender(&mock_report_sender);
9304
9305 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9306 // that the request can be sent to a site on the Expect-Staple preload list.
9307 MockHostResolver host_resolver;
9308 TestNetworkDelegate network_delegate;
9309 TestURLRequestContext context(true);
9310 context.set_host_resolver(&host_resolver);
9311 context.set_transport_security_state(&transport_security_state);
9312 context.set_network_delegate(&network_delegate);
9313 context.set_cert_verifier(&cert_verifier);
9314 context.Init();
9315
9316 // This request should not not trigger an Expect-Staple violation.
9317 TestDelegate d;
9318 GURL url = https_test_server.GetURL("/");
9319 GURL::Replacements replace_host;
9320 replace_host.SetHostStr(kExpectStapleStaticHostname);
9321 url = url.ReplaceComponents(replace_host);
9322 std::unique_ptr<URLRequest> ok_request(
9323 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9324 ok_request->Start();
9325 base::RunLoop().Run();
9326
9327 // Check that no report was sent.
9328 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9329 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9330}
9331
dadrian612337a2016-07-20 22:36:589332static const struct OCSPVerifyTestData {
9333 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
9334 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
9335 OCSPVerifyResult::ResponseStatus response_status;
9336 bool has_revocation_status;
9337 OCSPRevocationStatus cert_status;
9338} kOCSPVerifyData[] = {
9339
9340 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9341 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9342 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9343 OCSPVerifyResult::PROVIDED,
9344 true,
9345 OCSPRevocationStatus::GOOD},
9346
9347 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9348 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9349 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9350 OCSPVerifyResult::INVALID_DATE,
9351 false,
9352 OCSPRevocationStatus::UNKNOWN},
9353
9354 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9355 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9356 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9357 OCSPVerifyResult::INVALID_DATE,
9358 false,
9359 OCSPRevocationStatus::UNKNOWN},
9360
9361 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9362 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9363 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9364 OCSPVerifyResult::INVALID_DATE,
9365 false,
9366 OCSPRevocationStatus::UNKNOWN},
9367
9368 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9369 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9370 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9371 OCSPVerifyResult::INVALID_DATE,
9372 false,
9373 OCSPRevocationStatus::UNKNOWN},
9374
9375 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
9376 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9377 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9378 OCSPVerifyResult::ERROR_RESPONSE,
9379 false,
9380 OCSPRevocationStatus::UNKNOWN},
9381
9382 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
9383 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9384 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9385 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
9386 false,
9387 OCSPRevocationStatus::UNKNOWN},
9388
9389 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
9390 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9391 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9392 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
9393 false,
9394 OCSPRevocationStatus::UNKNOWN},
9395
9396 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9397 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9398 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9399 OCSPVerifyResult::INVALID_DATE,
9400 false,
9401 OCSPRevocationStatus::UNKNOWN},
9402
9403 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9404 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9405 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9406 OCSPVerifyResult::PROVIDED,
9407 true,
9408 OCSPRevocationStatus::UNKNOWN},
9409
9410 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9411 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9412 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9413 OCSPVerifyResult::INVALID_DATE,
9414 false,
9415 OCSPRevocationStatus::UNKNOWN},
9416
9417 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9418 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9419 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9420 OCSPVerifyResult::INVALID_DATE,
9421 false,
9422 OCSPRevocationStatus::UNKNOWN},
9423
9424 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9425 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9426 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
9427 OCSPVerifyResult::BAD_PRODUCED_AT,
9428 false,
9429 OCSPRevocationStatus::UNKNOWN},
9430
9431 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9432 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9433 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9434 OCSPVerifyResult::BAD_PRODUCED_AT,
9435 false,
9436 OCSPRevocationStatus::UNKNOWN},
9437
9438 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9439 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9440 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9441 OCSPVerifyResult::BAD_PRODUCED_AT,
9442 false,
9443 OCSPRevocationStatus::UNKNOWN},
9444
9445 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9446 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9447 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9448 OCSPVerifyResult::PROVIDED,
9449 true,
9450 OCSPRevocationStatus::REVOKED},
9451
9452 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9453 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9454 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9455 OCSPVerifyResult::INVALID_DATE,
9456 false,
9457 OCSPRevocationStatus::UNKNOWN},
9458
9459 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9460 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9461 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9462 OCSPVerifyResult::INVALID_DATE,
9463 false,
9464 OCSPRevocationStatus::UNKNOWN},
9465
9466 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9467 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9468 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9469 OCSPVerifyResult::PROVIDED,
9470 true,
9471 OCSPRevocationStatus::GOOD},
9472
9473 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9474 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9475 {SpawnedTestServer::SSLOptions::OCSP_OK,
9476 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9477 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9478 OCSPVerifyResult::PROVIDED,
9479 true,
9480 OCSPRevocationStatus::GOOD},
9481
9482 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9483 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9484 {SpawnedTestServer::SSLOptions::OCSP_OK,
9485 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9486 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9487 OCSPVerifyResult::PROVIDED,
9488 true,
9489 OCSPRevocationStatus::GOOD},
9490
9491 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9492 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9493 {SpawnedTestServer::SSLOptions::OCSP_OK,
9494 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9495 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9496 OCSPVerifyResult::PROVIDED,
9497 true,
9498 OCSPRevocationStatus::GOOD},
9499
9500 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9501 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9502 {SpawnedTestServer::SSLOptions::OCSP_OK,
9503 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9504 {SpawnedTestServer::SSLOptions::OCSP_OK,
9505 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9506 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9507 OCSPVerifyResult::INVALID_DATE,
9508 false,
9509 OCSPRevocationStatus::UNKNOWN},
9510
9511 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9512 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9513 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9514 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9515 {SpawnedTestServer::SSLOptions::OCSP_OK,
9516 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9517 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9518 OCSPVerifyResult::PROVIDED,
9519 true,
9520 OCSPRevocationStatus::REVOKED},
9521
9522 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9523 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9524 {SpawnedTestServer::SSLOptions::OCSP_OK,
9525 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9526 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9527 OCSPVerifyResult::PROVIDED,
9528 true,
9529 OCSPRevocationStatus::UNKNOWN},
9530
9531 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9532 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9533 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9534 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9535 {SpawnedTestServer::SSLOptions::OCSP_OK,
9536 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9537 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9538 OCSPVerifyResult::PROVIDED,
9539 true,
9540 OCSPRevocationStatus::UNKNOWN},
9541
9542 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9543 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9544 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9545 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9546 false,
9547 OCSPRevocationStatus::UNKNOWN},
9548
9549 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9550 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9551 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9552 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9553 false,
9554 OCSPRevocationStatus::UNKNOWN},
9555
9556};
9557
9558class HTTPSOCSPVerifyTest
9559 : public HTTPSOCSPTest,
9560 public testing::WithParamInterface<OCSPVerifyTestData> {};
9561
9562TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
9563 SpawnedTestServer::SSLOptions ssl_options(
9564 SpawnedTestServer::SSLOptions::CERT_AUTO);
9565 OCSPVerifyTestData test = GetParam();
9566
9567 ssl_options.ocsp_responses = test.ocsp_responses;
9568 ssl_options.ocsp_produced = test.ocsp_produced;
9569 ssl_options.staple_ocsp_response = true;
9570
9571 SSLInfo ssl_info;
9572 OCSPErrorTestDelegate delegate;
9573 ASSERT_NO_FATAL_FAILURE(
9574 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
9575
9576 // The SSLInfo must be extracted from |delegate| on error, due to how
9577 // URLRequest caches certificate errors.
9578 if (delegate.have_certificate_errors()) {
9579 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
9580 ssl_info = delegate.ssl_info();
9581 }
9582
9583 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
9584
9585 if (test.has_revocation_status)
9586 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
9587}
9588
9589INSTANTIATE_TEST_CASE_P(OCSPVerify,
9590 HTTPSOCSPVerifyTest,
9591 testing::ValuesIn(kOCSPVerifyData));
9592
[email protected]3a86a712013-07-30 07:16:209593class HTTPSHardFailTest : public HTTPSOCSPTest {
9594 protected:
rsleevid6de8302016-06-21 01:33:209595 void SetupContext() override {
9596 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149597 false /* check for EV */, false /* online revocation checking */,
9598 true /* require rev. checking for local
9599 anchors */,
9600 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209601 }
9602};
9603
[email protected]3a86a712013-07-30 07:16:209604TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9605 if (!SystemSupportsOCSP()) {
9606 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9607 return;
9608 }
9609
9610 if (!SystemSupportsHardFailRevocationChecking()) {
9611 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9612 << "revocation checking";
9613 return;
9614 }
9615
9616 SpawnedTestServer::SSLOptions ssl_options(
9617 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589618 ssl_options.ocsp_status =
9619 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:209620
9621 CertStatus cert_status;
9622 DoConnection(ssl_options, &cert_status);
9623
9624 EXPECT_EQ(CERT_STATUS_REVOKED,
9625 cert_status & CERT_STATUS_REVOKED);
9626
9627 // Without a positive OCSP response, we shouldn't show the EV status.
9628 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9629}
9630
[email protected]a13234c2012-03-20 21:45:029631class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9632 protected:
rsleevid6de8302016-06-21 01:33:209633 void SetupContext() override {
9634 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149635 true /* check for EV */, false /* online revocation checking */,
9636 false /* require rev. checking for local
9637 anchors */,
9638 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029639 }
9640};
9641
9642TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9643 if (!SystemSupportsOCSP()) {
9644 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9645 return;
9646 }
9647
[email protected]ce7d0cbc2013-05-03 18:57:229648 SpawnedTestServer::SSLOptions ssl_options(
9649 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589650 ssl_options.ocsp_status =
9651 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029652 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9653
[email protected]924e9f92012-12-16 22:00:539654 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129655 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029656
9657 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9658 cert_status & CERT_STATUS_ALL_ERRORS);
9659
9660 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089661 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9662 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029663}
9664
[email protected]be0fff62013-08-29 23:37:489665TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9666 if (!SystemSupportsOCSP()) {
9667 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9668 return;
9669 }
9670
9671 SpawnedTestServer::SSLOptions ssl_options(
9672 SpawnedTestServer::SSLOptions::CERT_AUTO);
9673 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9674 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9675
9676 CertStatus cert_status;
9677 DoConnection(ssl_options, &cert_status);
9678
9679 // Currently only works for Windows. When using NSS or OS X, it's not
9680 // possible to determine whether the check failed because of actual
9681 // revocation or because there was an OCSP failure.
9682#if defined(OS_WIN)
9683 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9684#else
9685 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9686#endif
9687
9688 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9689 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9690 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9691}
9692
[email protected]a13234c2012-03-20 21:45:029693TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9694 if (!SystemSupportsOCSP()) {
9695 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9696 return;
9697 }
9698
[email protected]ce7d0cbc2013-05-03 18:57:229699 SpawnedTestServer::SSLOptions ssl_options(
9700 SpawnedTestServer::SSLOptions::CERT_AUTO);
9701 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029702 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9703
9704 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129705 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029706
9707 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9708
9709 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9710 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089711 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9712 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029713}
9714
9715TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9716 if (!SystemSupportsOCSP()) {
9717 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9718 return;
9719 }
9720
[email protected]ce7d0cbc2013-05-03 18:57:229721 SpawnedTestServer::SSLOptions ssl_options(
9722 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589723 ssl_options.ocsp_status =
9724 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029725 SSLConfigService::SetCRLSet(
9726 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9727
9728 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129729 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029730
9731 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9732 cert_status & CERT_STATUS_ALL_ERRORS);
9733
9734 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089735 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9736 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029737}
9738
[email protected]51523f52013-07-31 21:57:289739TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9740 if (!SystemSupportsOCSP()) {
9741 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9742 return;
9743 }
9744
9745 SpawnedTestServer::SSLOptions ssl_options(
9746 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589747 ssl_options.ocsp_status =
9748 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:289749 SSLConfigService::SetCRLSet(
9750 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9751 false, &kOCSPTestCertSPKI, "")));
9752
9753 CertStatus cert_status;
9754 DoConnection(ssl_options, &cert_status);
9755
9756 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9757 // revocation check for EV.
9758 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9759 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9760 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9761 EXPECT_FALSE(
9762 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9763}
9764
9765TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9766 if (!SystemSupportsOCSP()) {
9767 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9768 return;
9769 }
9770
[email protected]ce7d0cbc2013-05-03 18:57:229771 SpawnedTestServer::SSLOptions ssl_options(
9772 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589773 ssl_options.ocsp_status =
9774 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029775 SSLConfigService::SetCRLSet(
9776 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9777
[email protected]51523f52013-07-31 21:57:289778 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129779 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029780
[email protected]51523f52013-07-31 21:57:289781 // Even with a fresh CRLSet, we should still do online revocation checks when
9782 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9783 // test.
9784 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9785 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029786
[email protected]51523f52013-07-31 21:57:289787 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029788 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289789 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029790}
9791
[email protected]b6f2de32012-08-17 04:35:089792TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9793 // Test that when EV verification is requested, but online revocation
9794 // checking is disabled, and the leaf certificate is not in fact EV, that
9795 // no revocation checking actually happens.
9796 if (!SystemSupportsOCSP()) {
9797 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9798 return;
9799 }
9800
9801 // Unmark the certificate's OID as EV, which should disable revocation
9802 // checking (as per the user preference)
9803 ev_test_policy_.reset();
9804
[email protected]ce7d0cbc2013-05-03 18:57:229805 SpawnedTestServer::SSLOptions ssl_options(
9806 SpawnedTestServer::SSLOptions::CERT_AUTO);
9807 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089808 SSLConfigService::SetCRLSet(
9809 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9810
9811 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129812 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089813
9814 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9815
9816 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9817 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9818}
9819
[email protected]a13234c2012-03-20 21:45:029820class HTTPSCRLSetTest : public HTTPSOCSPTest {
9821 protected:
rsleevid6de8302016-06-21 01:33:209822 void SetupContext() override {
9823 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149824 false /* check for EV */, false /* online revocation checking */,
9825 false /* require rev. checking for local
9826 anchors */,
9827 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029828 }
9829};
9830
9831TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229832 SpawnedTestServer::SSLOptions ssl_options(
9833 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589834 ssl_options.ocsp_status =
9835 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029836 SSLConfigService::SetCRLSet(
9837 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9838
[email protected]924e9f92012-12-16 22:00:539839 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129840 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029841
9842 // If we're not trying EV verification then, even if the CRLSet has expired,
9843 // we don't fall back to online revocation checks.
9844 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9845 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9846 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9847}
[email protected]51523f52013-07-31 21:57:289848
9849TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309850#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289851 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9852 return;
9853#endif
9854
9855 SpawnedTestServer::SSLOptions ssl_options(
9856 SpawnedTestServer::SSLOptions::CERT_AUTO);
9857 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9858 ssl_options.cert_serial = 10;
9859 SSLConfigService::SetCRLSet(
9860 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9861 false, &kOCSPTestCertSPKI, "\x0a")));
9862
9863 CertStatus cert_status = 0;
9864 DoConnection(ssl_options, &cert_status);
9865
9866 // If the certificate is recorded as revoked in the CRLSet, that should be
9867 // reflected without online revocation checking.
9868 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9869 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9870 EXPECT_FALSE(
9871 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9872}
[email protected]316c1e5e2012-09-12 15:17:449873#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279874
mmenke9f2ec60c2015-06-01 20:59:479875#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9876// These tests aren't passing on Android. Either the RemoteTestServer isn't
9877// starting up successfully, or it can't access the test files.
9878// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319879class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119880 public:
[email protected]d9fca99a2012-02-24 16:16:209881 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479882 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559883 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9884 SpawnedTestServer::kLocalhost,
9885 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479886 // Can't use |default_context_|'s HostResolver to set up the
9887 // FTPTransactionFactory because it hasn't been created yet.
9888 default_context_.set_host_resolver(&host_resolver_);
9889 }
9890
9891 // URLRequestTest interface:
9892 void SetUpFactory() override {
9893 // Add FTP support to the default URLRequestContext.
9894 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209895 "ftp",
danakj8522a25b2016-04-16 00:17:369896 base::WrapUnique(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479897 }
9898
9899 std::string GetTestFileContents() {
9900 base::FilePath path;
9901 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9902 path = path.Append(kTestFilePath);
9903 path = path.AppendASCII(kFtpTestFile);
9904 std::string contents;
9905 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9906 return contents;
[email protected]95409e12010-08-17 20:07:119907 }
9908
[email protected]b89ca032009-08-31 21:41:319909 protected:
mmenke9f2ec60c2015-06-01 20:59:479910 MockHostResolver host_resolver_;
9911 FtpNetworkLayer ftp_transaction_factory_;
9912
tommycli59a63432015-11-06 00:10:559913 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319914};
9915
[email protected]d2a133182012-08-05 16:44:089916// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099917TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089918 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089919
9920 TestDelegate d;
9921 {
danakj8522a25b2016-04-16 00:17:369922 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:369923 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199924 r->Start();
9925 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089926
[email protected]255620da2013-08-19 13:14:299927 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089928
[email protected]f7022f32014-08-21 16:32:199929 EXPECT_FALSE(r->is_pending());
mmenkefe5d0b112016-09-06 20:46:589930 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9931 EXPECT_THAT(r->status().error(), IsError(ERR_UNSAFE_PORT));
[email protected]d2a133182012-08-05 16:44:089932 }
9933}
9934
mmenke9f2ec60c2015-06-01 20:59:479935TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559936 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119937
[email protected]a25e90e2009-09-09 17:05:379938 TestDelegate d;
9939 {
danakj8522a25b2016-04-16 00:17:369940 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559941 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199942 r->Start();
9943 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379944
[email protected]255620da2013-08-19 13:14:299945 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379946
[email protected]f7022f32014-08-21 16:32:199947 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379948 EXPECT_EQ(1, d.response_started_count());
9949 EXPECT_FALSE(d.received_data_before_response());
9950 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559951 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199952 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559953 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199954 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379955 }
9956}
9957
mmenke9f2ec60c2015-06-01 20:59:479958TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559959 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119960
[email protected]dd265012009-01-08 20:45:279961 TestDelegate d;
9962 {
danakj8522a25b2016-04-16 00:17:369963 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559964 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199965 r->Start();
9966 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279967
[email protected]255620da2013-08-19 13:14:299968 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279969
[email protected]f7022f32014-08-21 16:32:199970 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279971 EXPECT_EQ(1, d.response_started_count());
9972 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479973 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559974 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199975 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559976 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199977 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279978 }
9979}
9980
mmenke9f2ec60c2015-06-01 20:59:479981TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559982 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119983
[email protected]dd265012009-01-08 20:45:279984 TestDelegate d;
9985 {
danakj8522a25b2016-04-16 00:17:369986 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559987 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9988 "chrome"),
9989 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199990 r->Start();
9991 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279992
[email protected]255620da2013-08-19 13:14:299993 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279994
[email protected]f7022f32014-08-21 16:32:199995 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479996 EXPECT_EQ(1, d.response_started_count());
9997 EXPECT_FALSE(d.received_data_before_response());
9998 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559999 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:1910000 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:5510001 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:1910002 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:2510003
10004 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:1910005 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:2510006 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2710007 }
10008}
10009
mmenke9f2ec60c2015-06-01 20:59:4710010TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5510011 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110012
[email protected]dd265012009-01-08 20:45:2710013 TestDelegate d;
10014 {
danakj8522a25b2016-04-16 00:17:3610015 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510016 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10017 "wrong_password"),
davidben151423e2015-03-23 18:48:3610018 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910019 r->Start();
10020 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710021
[email protected]255620da2013-08-19 13:14:2910022 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710023
[email protected]f7022f32014-08-21 16:32:1910024 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710025 EXPECT_EQ(1, d.response_started_count());
10026 EXPECT_FALSE(d.received_data_before_response());
10027 EXPECT_EQ(d.bytes_received(), 0);
10028 }
10029}
10030
mmenke9f2ec60c2015-06-01 20:59:4710031TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5510032 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110033
[email protected]8b8a197d2009-08-26 15:57:5810034 TestDelegate d;
10035 // Set correct login credentials. The delegate will be asked for them when
10036 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810037 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810038 {
danakj8522a25b2016-04-16 00:17:3610039 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510040 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10041 "wrong_password"),
davidben151423e2015-03-23 18:48:3610042 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910043 r->Start();
10044 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810045
[email protected]255620da2013-08-19 13:14:2910046 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810047
[email protected]f7022f32014-08-21 16:32:1910048 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810049 EXPECT_EQ(1, d.response_started_count());
10050 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710051 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810052 }
10053}
10054
mmenke9f2ec60c2015-06-01 20:59:4710055TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5510056 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110057
[email protected]dd265012009-01-08 20:45:2710058 TestDelegate d;
10059 {
danakj8522a25b2016-04-16 00:17:3610060 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510061 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10062 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710063 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910064 r->Start();
10065 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710066
[email protected]255620da2013-08-19 13:14:2910067 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710068
[email protected]f7022f32014-08-21 16:32:1910069 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710070 EXPECT_EQ(1, d.response_started_count());
10071 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710072 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2710073 }
10074}
[email protected]8b8a197d2009-08-26 15:57:5810075
mmenke9f2ec60c2015-06-01 20:59:4710076TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5510077 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110078
[email protected]8b8a197d2009-08-26 15:57:5810079 TestDelegate d;
10080 // Set correct login credentials. The delegate will be asked for them when
10081 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810082 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810083 {
danakj8522a25b2016-04-16 00:17:3610084 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510085 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10086 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710087 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910088 r->Start();
10089 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810090
[email protected]255620da2013-08-19 13:14:2910091 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810092
[email protected]f7022f32014-08-21 16:32:1910093 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810094 EXPECT_EQ(1, d.response_started_count());
10095 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710096 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810097 }
10098}
[email protected]60a3df52009-09-22 16:13:2410099
mmenke9f2ec60c2015-06-01 20:59:4710100TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510101 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110102
danakj8522a25b2016-04-16 00:17:3610103 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410104 {
10105 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610106 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510107 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10108 "chrome"),
10109 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910110 r->Start();
10111 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410112
[email protected]255620da2013-08-19 13:14:2910113 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410114
[email protected]f7022f32014-08-21 16:32:1910115 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410116 EXPECT_EQ(1, d->response_started_count());
10117 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710118 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410119 }
10120
10121 d.reset(new TestDelegate);
10122 {
10123 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610124 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510125 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910126 r->Start();
10127 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410128
[email protected]255620da2013-08-19 13:14:2910129 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410130
[email protected]f7022f32014-08-21 16:32:1910131 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410132 EXPECT_EQ(1, d->response_started_count());
10133 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710134 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410135 }
10136}
10137
mmenke9f2ec60c2015-06-01 20:59:4710138TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510139 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110140
danakj8522a25b2016-04-16 00:17:3610141 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410142 // Set correct login credentials. The delegate will be asked for them when
10143 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810144 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410145 {
danakj8522a25b2016-04-16 00:17:3610146 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510147 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10148 "wrong_password"),
davidben151423e2015-03-23 18:48:3610149 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910150 r->Start();
10151 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410152
[email protected]255620da2013-08-19 13:14:2910153 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410154
[email protected]f7022f32014-08-21 16:32:1910155 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410156 EXPECT_EQ(1, d->response_started_count());
10157 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710158 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410159 }
10160
10161 // Use a new delegate without explicit credentials. The cached ones should be
10162 // used.
10163 d.reset(new TestDelegate);
10164 {
10165 // Don't pass wrong credentials in the URL, they would override valid cached
10166 // ones.
danakj8522a25b2016-04-16 00:17:3610167 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510168 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910169 r->Start();
10170 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410171
[email protected]255620da2013-08-19 13:14:2910172 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410173
[email protected]f7022f32014-08-21 16:32:1910174 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410175 EXPECT_EQ(1, d->response_started_count());
10176 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710177 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410178 }
10179}
ricea3a1c71f2016-06-17 10:05:2610180
10181TEST_F(URLRequestTestFTP, RawBodyBytes) {
10182 ASSERT_TRUE(ftp_test_server_.Start());
10183
10184 TestDelegate d;
10185 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10186 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10187 req->Start();
10188 base::RunLoop().Run();
10189
10190 EXPECT_EQ(6, req->GetRawBodyBytes());
10191}
10192
[email protected]316c1e5e2012-09-12 15:17:4410193#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110194
ttuttlec0c828492015-05-15 01:25:5510195TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10196 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610197 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510198 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10199
10200 EXPECT_FALSE(req->response_info().network_accessed);
10201
10202 req->Start();
10203 base::RunLoop().Run();
10204
10205 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10206 EXPECT_FALSE(req->response_info().network_accessed);
10207}
10208
10209TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10210 MockHostResolver host_resolver;
10211 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10212 TestURLRequestContext context(true);
10213 context.set_network_delegate(&network_delegate);
10214 context.set_host_resolver(&host_resolver);
10215 host_resolver.rules()->AddSimulatedFailure("*");
10216 context.Init();
10217
10218 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610219 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510220 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10221
10222 EXPECT_FALSE(req->response_info().network_accessed);
10223
10224 req->Start();
10225 base::RunLoop().Run();
10226 EXPECT_TRUE(req->response_info().network_accessed);
10227}
10228
mmenkeed0498b2015-12-08 23:20:4210229// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210230// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210231TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210232 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610233 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210234 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10235
danakj8522a25b2016-04-16 00:17:3610236 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210237 req.get(), &default_network_delegate_,
10238 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210239 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10240 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210241
10242 req->Start();
10243 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210244 base::RunLoop().RunUntilIdle();
mmenkefe5d0b112016-09-06 20:46:5810245 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
alexanderkcd904b52015-07-24 18:57:2210246 EXPECT_EQ(0, d.received_redirect_count());
10247}
10248
[email protected]7461a402011-03-24 23:19:5110249} // namespace net