blob: 82b3cc71353a617b527e2dca513578747e9fde19 [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"
vishal.b62985ca92015-04-17 08:45:5181#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4682#include "net/log/test_net_log_entry.h"
83#include "net/log/test_net_log_util.h"
tbansalca83c002016-04-28 20:56:2884#include "net/nqe/external_estimate_provider.h"
[email protected]63de95b2008-12-10 04:11:2785#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1986#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1487#include "net/ssl/channel_id_service.h"
88#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:5789#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:5590#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:1491#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:1192#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3693#include "net/test/embedded_test_server/embedded_test_server.h"
94#include "net/test/embedded_test_server/http_request.h"
95#include "net/test/embedded_test_server/http_response.h"
[email protected]89b32522013-05-07 20:04:2196#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:4397#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:5098#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:3499#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43100#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52101#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50102#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14103#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50104#include "net/url_request/url_request_intercepting_job_factory.h"
105#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49106#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51107#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47108#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44109#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:52110#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15111#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52112
[email protected]02494ec2014-05-07 15:05:29113#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55114#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29115#include "net/url_request/file_protocol_handler.h"
116#include "net/url_request/url_request_file_dir_job.h"
117#endif
118
mmenke9f2ec60c2015-06-01 20:59:47119#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
120#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29121#include "net/url_request/ftp_protocol_handler.h"
122#endif
123
[email protected]dffe8242012-03-20 15:14:27124#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48125#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56126#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27127#endif
128
[email protected]ad65a3e2013-12-25 18:18:01129using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33130using base::Time;
halton.huoe4e45742014-12-08 07:55:46131using std::string;
[email protected]e1acf6f2008-10-27 20:43:33132
[email protected]7461a402011-03-24 23:19:51133namespace net {
134
initial.commit586acc5fe2008-07-26 22:42:52135namespace {
136
[email protected]42cba2fb2013-03-29 19:58:57137const base::string16 kChrome(ASCIIToUTF16("chrome"));
138const base::string16 kSecret(ASCIIToUTF16("secret"));
139const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44140
mmenke9f2ec60c2015-06-01 20:59:47141const base::FilePath::CharType kTestFilePath[] =
142 FILE_PATH_LITERAL("net/data/url_request_unittest");
143
144#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
145// Test file used in most FTP tests.
146const char kFtpTestFile[] = "BullRunSpeech.txt";
147#endif
148
[email protected]2bba3252013-04-08 19:50:59149// Tests load timing information in the case a fresh connection was used, with
150// no proxy.
[email protected]cba24642014-08-15 20:49:59151void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25152 int connect_timing_flags) {
153 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59154 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25155
156 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
157 EXPECT_FALSE(load_timing_info.request_start.is_null());
158
159 EXPECT_LE(load_timing_info.request_start,
160 load_timing_info.connect_timing.connect_start);
161 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
162 connect_timing_flags);
163 EXPECT_LE(load_timing_info.connect_timing.connect_end,
164 load_timing_info.send_start);
165 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
166 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
167
[email protected]58e32bb2013-01-21 18:23:25168 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
169 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
170}
171
[email protected]2bba3252013-04-08 19:50:59172// Same as above, but with proxy times.
173void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59174 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59175 int connect_timing_flags) {
176 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59177 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59178
179 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
180 EXPECT_FALSE(load_timing_info.request_start.is_null());
181
182 EXPECT_LE(load_timing_info.request_start,
183 load_timing_info.proxy_resolve_start);
184 EXPECT_LE(load_timing_info.proxy_resolve_start,
185 load_timing_info.proxy_resolve_end);
186 EXPECT_LE(load_timing_info.proxy_resolve_end,
187 load_timing_info.connect_timing.connect_start);
188 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
189 connect_timing_flags);
190 EXPECT_LE(load_timing_info.connect_timing.connect_end,
191 load_timing_info.send_start);
192 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
193 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
194}
195
196// Same as above, but with a reused socket and proxy times.
197void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59198 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59199 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59200 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59201
202 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
203 EXPECT_FALSE(load_timing_info.request_start.is_null());
204
205 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
206
207 EXPECT_LE(load_timing_info.request_start,
208 load_timing_info.proxy_resolve_start);
209 EXPECT_LE(load_timing_info.proxy_resolve_start,
210 load_timing_info.proxy_resolve_end);
211 EXPECT_LE(load_timing_info.proxy_resolve_end,
212 load_timing_info.send_start);
213 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
214 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
215}
216
xunjielia6888202015-04-14 21:34:25217#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25218// Tests load timing information in the case of a cache hit, when no cache
219// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17220base::StringPiece TestNetResourceProvider(int key) {
221 return "header";
222}
223
224void FillBuffer(char* buffer, size_t len) {
225 static bool called = false;
226 if (!called) {
227 called = true;
228 int seed = static_cast<int>(Time::Now().ToInternalValue());
229 srand(seed);
230 }
231
232 for (size_t i = 0; i < len; i++) {
233 buffer[i] = static_cast<char>(rand());
234 if (!buffer[i])
235 buffer[i] = 'g';
236 }
237}
xunjielia6888202015-04-14 21:34:25238#endif
[email protected]e3a85452013-11-14 01:46:17239
[email protected]3b23a222013-05-15 21:33:25240void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59241 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25242 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59243 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25244
245 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
246 EXPECT_FALSE(load_timing_info.request_start.is_null());
247
248 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
249 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
250 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
251 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
252
253 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
254 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
255}
256
mmenke9f2ec60c2015-06-01 20:59:47257#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25258// Tests load timing in the case that there is no HTTP response. This can be
259// used to test in the case of errors or non-HTTP requests.
260void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59261 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25262 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59263 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25264
265 // Only the request times should be non-null.
266 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
267 EXPECT_FALSE(load_timing_info.request_start.is_null());
268
269 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
270
271 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
272 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
273 EXPECT_TRUE(load_timing_info.send_start.is_null());
274 EXPECT_TRUE(load_timing_info.send_end.is_null());
275 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
276}
xunjielia6888202015-04-14 21:34:25277#endif
[email protected]58e32bb2013-01-21 18:23:25278
mmenkefb18c772015-09-30 22:22:50279// Test power monitor source that can simulate entering suspend mode. Can't use
280// the one in base/ because it insists on bringing its own MessageLoop.
281class TestPowerMonitorSource : public base::PowerMonitorSource {
282 public:
283 TestPowerMonitorSource() {}
284 ~TestPowerMonitorSource() override {}
285
286 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
287
288 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
289
290 bool IsOnBatteryPowerImpl() override { return false; }
291
292 private:
293 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
294};
295
mmenkeed0498b2015-12-08 23:20:42296// Job that allows monitoring of its priority.
297class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
298 public:
299 // The latest priority of the job is always written to |request_priority_|.
300 PriorityMonitoringURLRequestJob(URLRequest* request,
301 NetworkDelegate* network_delegate,
302 RequestPriority* request_priority)
303 : URLRequestTestJob(request, network_delegate),
304 request_priority_(request_priority) {
305 *request_priority_ = DEFAULT_PRIORITY;
306 }
307
308 void SetPriority(RequestPriority priority) override {
309 *request_priority_ = priority;
310 URLRequestTestJob::SetPriority(priority);
311 }
312
313 private:
314 RequestPriority* const request_priority_;
315};
316
[email protected]71c64f62008-11-15 04:36:51317// Do a case-insensitive search through |haystack| for |needle|.
318bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50319 std::string::const_iterator it = std::search(
320 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
321 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51322 return it != haystack.end();
323}
324
danakj8522a25b2016-04-16 00:17:36325std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
326 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28327 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48328 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23329}
330
[email protected]96adadb2010-08-28 01:16:17331// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51332void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17333 // -1 means unknown. 0 means no encryption.
334 EXPECT_GT(ssl_info.security_bits, 0);
335
336 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14337 uint16_t cipher_suite =
338 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29339 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17340}
341
[email protected]79e1fd62013-06-20 06:50:04342void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
343 const GURL& host_url) {
344 std::string sent_value;
345
346 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
347 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
348
349 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
350 EXPECT_EQ("keep-alive", sent_value);
351}
352
[email protected]dc5a5cf2012-09-26 02:49:30353// A network delegate that allows the user to choose a subset of request stages
354// to block in. When blocking, the delegate can do one of the following:
355// * synchronously return a pre-specified error code, or
356// * asynchronously return that value via an automatically called callback,
357// or
358// * block and wait for the user to do a callback.
359// Additionally, the user may also specify a redirect URL -- then each request
360// with the current URL different from the redirect target will be redirected
361// to that target, in the on-before-URL-request stage, independent of whether
362// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12363class BlockingNetworkDelegate : public TestNetworkDelegate {
364 public:
[email protected]dc5a5cf2012-09-26 02:49:30365 // Stages in which the delegate can block.
366 enum Stage {
[email protected]9045b8822012-01-13 20:35:35367 NOT_BLOCKED = 0,
368 ON_BEFORE_URL_REQUEST = 1 << 0,
369 ON_BEFORE_SEND_HEADERS = 1 << 1,
370 ON_HEADERS_RECEIVED = 1 << 2,
371 ON_AUTH_REQUIRED = 1 << 3
372 };
373
[email protected]dc5a5cf2012-09-26 02:49:30374 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59375 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30376 enum BlockMode {
377 SYNCHRONOUS, // No callback, returns specified return values.
378 AUTO_CALLBACK, // |this| posts a task to run the callback using the
379 // specified return codes.
380 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
381 // |auth_retval_| are ignored. In every blocking stage the
382 // message loop is quit.
383 };
384
385 // Creates a delegate which does not block at all.
386 explicit BlockingNetworkDelegate(BlockMode block_mode);
387
388 // For users to trigger a callback returning |response|.
389 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
390 // Only call if |block_mode_| == USER_CALLBACK.
391 void DoCallback(int response);
392 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
393
394 // Setters.
395 void set_retval(int retval) {
396 ASSERT_NE(USER_CALLBACK, block_mode_);
397 ASSERT_NE(ERR_IO_PENDING, retval);
398 ASSERT_NE(OK, retval);
399 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35400 }
401
[email protected]dc5a5cf2012-09-26 02:49:30402 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
403 // |auth_credentials_| will be passed with the response.
404 void set_auth_retval(AuthRequiredResponse auth_retval) {
405 ASSERT_NE(USER_CALLBACK, block_mode_);
406 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
407 auth_retval_ = auth_retval;
408 }
409 void set_auth_credentials(const AuthCredentials& auth_credentials) {
410 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35411 }
412
[email protected]dc5a5cf2012-09-26 02:49:30413 void set_redirect_url(const GURL& url) {
414 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35415 }
416
[email protected]dc5a5cf2012-09-26 02:49:30417 void set_block_on(int block_on) {
418 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35419 }
420
[email protected]dc5a5cf2012-09-26 02:49:30421 // Allows the user to check in which state did we block.
422 Stage stage_blocked_for_callback() const {
423 EXPECT_EQ(USER_CALLBACK, block_mode_);
424 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35425 }
426
427 private:
[email protected]dc5a5cf2012-09-26 02:49:30428 void RunCallback(int response, const CompletionCallback& callback);
429 void RunAuthCallback(AuthRequiredResponse response,
430 const AuthCallback& callback);
431
[email protected]9045b8822012-01-13 20:35:35432 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20433 int OnBeforeURLRequest(URLRequest* request,
434 const CompletionCallback& callback,
435 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35436
ryansturm2343cb62016-06-15 01:09:00437 int OnBeforeStartTransaction(URLRequest* request,
438 const CompletionCallback& callback,
439 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35440
dchengb03027d2014-10-21 12:00:20441 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35442 URLRequest* request,
443 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32444 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16445 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13446 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35447
dchengb03027d2014-10-21 12:00:20448 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35449 URLRequest* request,
450 const AuthChallengeInfo& auth_info,
451 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13452 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35453
[email protected]dc5a5cf2012-09-26 02:49:30454 // Resets the callbacks and |stage_blocked_for_callback_|.
455 void Reset();
[email protected]9045b8822012-01-13 20:35:35456
[email protected]dc5a5cf2012-09-26 02:49:30457 // Checks whether we should block in |stage|. If yes, returns an error code
458 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
459 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
460
461 // Configuration parameters, can be adjusted by public methods:
462 const BlockMode block_mode_;
463
464 // Values returned on blocking stages when mode is SYNCHRONOUS or
465 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
466 int retval_; // To be returned in non-auth stages.
467 AuthRequiredResponse auth_retval_;
468
[email protected]5f714132014-03-26 10:41:16469 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30470 int block_on_; // Bit mask: in which stages to block.
471
472 // |auth_credentials_| will be copied to |*target_auth_credential_| on
473 // callback.
474 AuthCredentials auth_credentials_;
475 AuthCredentials* target_auth_credentials_;
476
477 // Internal variables, not set by not the user:
478 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
479 // USER_CALLBACK).
480 Stage stage_blocked_for_callback_;
481
482 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35483 CompletionCallback callback_;
484 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30485
486 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
487
488 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35489};
490
[email protected]dc5a5cf2012-09-26 02:49:30491BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
492 : block_mode_(block_mode),
493 retval_(OK),
494 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
495 block_on_(0),
496 target_auth_credentials_(NULL),
497 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32498 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30499}
500
501void BlockingNetworkDelegate::DoCallback(int response) {
502 ASSERT_EQ(USER_CALLBACK, block_mode_);
503 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
504 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
505 CompletionCallback callback = callback_;
506 Reset();
507 RunCallback(response, callback);
508}
509
510void BlockingNetworkDelegate::DoAuthCallback(
511 NetworkDelegate::AuthRequiredResponse response) {
512 ASSERT_EQ(USER_CALLBACK, block_mode_);
513 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
514 AuthCallback auth_callback = auth_callback_;
515 Reset();
516 RunAuthCallback(response, auth_callback);
517}
518
519void BlockingNetworkDelegate::RunCallback(int response,
520 const CompletionCallback& callback) {
521 callback.Run(response);
522}
523
524void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
525 const AuthCallback& callback) {
526 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
527 ASSERT_TRUE(target_auth_credentials_ != NULL);
528 *target_auth_credentials_ = auth_credentials_;
529 }
530 callback.Run(response);
531}
532
533int BlockingNetworkDelegate::OnBeforeURLRequest(
534 URLRequest* request,
535 const CompletionCallback& callback,
536 GURL* new_url) {
537 if (redirect_url_ == request->url())
538 return OK; // We've already seen this request and redirected elsewhere.
539
540 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
541
542 if (!redirect_url_.is_empty())
543 *new_url = redirect_url_;
544
545 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
546}
547
ryansturm2343cb62016-06-15 01:09:00548int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30549 URLRequest* request,
550 const CompletionCallback& callback,
551 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00552 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30553
554 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
555}
556
557int BlockingNetworkDelegate::OnHeadersReceived(
558 URLRequest* request,
559 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32560 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16561 scoped_refptr<HttpResponseHeaders>* override_response_headers,
562 GURL* allowed_unsafe_redirect_url) {
563 TestNetworkDelegate::OnHeadersReceived(request,
564 callback,
565 original_response_headers,
566 override_response_headers,
567 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30568
569 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
570}
571
572NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
573 URLRequest* request,
574 const AuthChallengeInfo& auth_info,
575 const AuthCallback& callback,
576 AuthCredentials* credentials) {
577 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
578 credentials);
579 // Check that the user has provided callback for the previous blocked stage.
580 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
581
582 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
583 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
584 }
585
586 target_auth_credentials_ = credentials;
587
588 switch (block_mode_) {
589 case SYNCHRONOUS:
590 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
591 *target_auth_credentials_ = auth_credentials_;
592 return auth_retval_;
593
594 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45595 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30596 FROM_HERE,
597 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
598 weak_factory_.GetWeakPtr(), auth_retval_, callback));
599 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
600
601 case USER_CALLBACK:
602 auth_callback_ = callback;
603 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45604 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17605 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30606 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
607 }
608 NOTREACHED();
609 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
610}
611
612void BlockingNetworkDelegate::Reset() {
613 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
614 stage_blocked_for_callback_ = NOT_BLOCKED;
615 callback_.Reset();
616 auth_callback_.Reset();
617}
618
619int BlockingNetworkDelegate::MaybeBlockStage(
620 BlockingNetworkDelegate::Stage stage,
621 const CompletionCallback& callback) {
622 // Check that the user has provided callback for the previous blocked stage.
623 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
624
625 if ((block_on_ & stage) == 0) {
626 return OK;
627 }
628
629 switch (block_mode_) {
630 case SYNCHRONOUS:
631 EXPECT_NE(OK, retval_);
632 return retval_;
633
634 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45635 base::ThreadTaskRunnerHandle::Get()->PostTask(
636 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
637 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30638 return ERR_IO_PENDING;
639
640 case USER_CALLBACK:
641 callback_ = callback;
642 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45643 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17644 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30645 return ERR_IO_PENDING;
646 }
647 NOTREACHED();
648 return 0;
649}
650
[email protected]d5a4dd62012-05-23 01:41:04651class TestURLRequestContextWithProxy : public TestURLRequestContext {
652 public:
653 // Does not own |delegate|.
654 TestURLRequestContextWithProxy(const std::string& proxy,
655 NetworkDelegate* delegate)
656 : TestURLRequestContext(true) {
657 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
658 set_network_delegate(delegate);
659 Init();
660 }
dchengb03027d2014-10-21 12:00:20661 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04662};
663
stefanocsbd5be5202016-06-10 03:37:55664// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01665// URI and report to be sent.
666class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55667 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01668 public:
669 MockCertificateReportSender() {}
670 ~MockCertificateReportSender() override {}
671
672 void Send(const GURL& report_uri, const std::string& report) override {
673 latest_report_uri_ = report_uri;
674 latest_report_ = report;
675 }
676
estarkf2979122016-04-05 17:04:39677 void SetErrorCallback(
678 const base::Callback<void(const GURL&, int)>& error_callback) override {}
679
estark06e0dac2015-08-07 21:56:01680 const GURL& latest_report_uri() { return latest_report_uri_; }
681 const std::string& latest_report() { return latest_report_; }
682
683 private:
684 GURL latest_report_uri_;
685 std::string latest_report_;
686};
687
estarkcd39c11f2015-10-19 19:46:36688class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
689 public:
690 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34691 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36692};
693
[email protected]d5a4dd62012-05-23 01:41:04694} // namespace
695
[email protected]a592c0432012-12-01 18:10:29696// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48697class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00698 public:
[email protected]ef2bf422012-05-11 03:27:09699 URLRequestTest() : default_context_(true) {
700 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25701 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50702 job_factory_impl_ = new URLRequestJobFactoryImpl();
703 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50704 }
bengr1bf8e942014-11-07 01:36:50705
dcheng67be2b1f2014-10-27 21:47:29706 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18707 // URLRequestJobs may post clean-up tasks on destruction.
708 base::RunLoop().RunUntilIdle();
709 }
[email protected]87a09a92011-07-14 15:50:50710
dcheng2339883c2014-12-23 00:23:05711 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50712 SetUpFactory();
713 default_context_.set_job_factory(job_factory_.get());
714 default_context_.Init();
715 PlatformTest::SetUp();
716 }
717
718 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20719 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36720 "data", base::WrapUnique(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50721#if !defined(DISABLE_FILE_SUPPORT)
722 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36723 "file", base::WrapUnique(new FileProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20724 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50725#endif
726 }
727
728 TestNetworkDelegate* default_network_delegate() {
729 return &default_network_delegate_;
730 }
731
732 const TestURLRequestContext& default_context() const {
733 return default_context_;
734 }
735
736
[email protected]3c5ca8c2011-09-29 01:14:51737 // Adds the TestJobInterceptor to the default context.
738 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23739 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20740 job_factory_impl_->SetProtocolHandler("http", nullptr);
741 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36742 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23743 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51744 }
745
[email protected]87a09a92011-07-14 15:50:50746 protected:
vishal.b62985ca92015-04-17 08:45:51747 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24748 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50749 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36750 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09751 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48752};
753
[email protected]316c1e5e2012-09-12 15:17:44754TEST_F(URLRequestTest, AboutBlankTest) {
755 TestDelegate d;
756 {
danakj8522a25b2016-04-16 00:17:36757 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36758 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44759
[email protected]f7022f32014-08-21 16:32:19760 r->Start();
761 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44762
[email protected]255620da2013-08-19 13:14:29763 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44764
[email protected]f7022f32014-08-21 16:32:19765 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44766 EXPECT_FALSE(d.received_data_before_response());
767 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19768 EXPECT_EQ("", r->GetSocketAddress().host());
769 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04770
771 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19772 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44773 }
774}
775
776TEST_F(URLRequestTest, DataURLImageTest) {
777 TestDelegate d;
778 {
779 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36780 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
781 GURL("data:image/png;base64,"
782 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
783 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
784 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
785 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
786 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
787 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
788 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
789 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
790 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
791 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
792 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
793 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
794 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
795 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
796 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
797 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
798 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
799 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
800 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36801 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44802
[email protected]f7022f32014-08-21 16:32:19803 r->Start();
804 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44805
[email protected]255620da2013-08-19 13:14:29806 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44807
[email protected]f7022f32014-08-21 16:32:19808 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44809 EXPECT_FALSE(d.received_data_before_response());
810 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19811 EXPECT_EQ("", r->GetSocketAddress().host());
812 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04813
814 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19815 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44816 }
817}
818
[email protected]5ecf7cb282014-05-11 01:49:55819#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44820TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15821 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04822
823#if defined(OS_ANDROID)
824 // Android devices are not guaranteed to be able to read /proc/self/exe
825 // Use /etc/hosts instead
826 app_path = base::FilePath("/etc/hosts");
827#else
[email protected]316c1e5e2012-09-12 15:17:44828 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04829#endif // OS_ANDROID
830
[email protected]316c1e5e2012-09-12 15:17:44831 GURL app_url = FilePathToFileURL(app_path);
832
833 TestDelegate d;
834 {
danakj8522a25b2016-04-16 00:17:36835 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36836 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44837
[email protected]f7022f32014-08-21 16:32:19838 r->Start();
839 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44840
[email protected]255620da2013-08-19 13:14:29841 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44842
avibf0746c2015-12-09 19:53:14843 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49844 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44845
[email protected]f7022f32014-08-21 16:32:19846 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44847 EXPECT_EQ(1, d.response_started_count());
848 EXPECT_FALSE(d.received_data_before_response());
849 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19850 EXPECT_EQ("", r->GetSocketAddress().host());
851 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04852
853 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19854 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44855 }
856}
857
[email protected]ba40bb762012-12-17 07:11:04858TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15859 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04860 PathService::Get(base::FILE_EXE, &app_path);
861 GURL app_url = FilePathToFileURL(app_path);
862
863 TestDelegate d;
864 {
danakj8522a25b2016-04-16 00:17:36865 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36866 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04867
[email protected]f7022f32014-08-21 16:32:19868 r->Start();
869 EXPECT_TRUE(r->is_pending());
870 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04871 }
[email protected]79e1fd62013-06-20 06:50:04872 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04873 // destroyed.
[email protected]255620da2013-08-19 13:14:29874 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04875}
876
[email protected]316c1e5e2012-09-12 15:17:44877TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
878 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36879 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44880 FillBuffer(buffer.get(), buffer_size);
881
[email protected]6cdfd7f2013-02-08 20:40:15882 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52883 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44884 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30885 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44886
avibf0746c2015-12-09 19:53:14887 int64_t file_size;
[email protected]56285702013-12-04 18:22:49888 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44889
890 const size_t first_byte_position = 500;
891 const size_t last_byte_position = buffer_size - first_byte_position;
892 const size_t content_length = last_byte_position - first_byte_position + 1;
893 std::string partial_buffer_string(buffer.get() + first_byte_position,
894 buffer.get() + last_byte_position + 1);
895
896 TestDelegate d;
897 {
danakj8522a25b2016-04-16 00:17:36898 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36899 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44900
901 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38902 headers.SetHeader(
903 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59904 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38905 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19906 r->SetExtraRequestHeaders(headers);
907 r->Start();
908 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44909
[email protected]255620da2013-08-19 13:14:29910 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19911 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44912 EXPECT_EQ(1, d.response_started_count());
913 EXPECT_FALSE(d.received_data_before_response());
914 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
915 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
916 EXPECT_TRUE(partial_buffer_string == d.data_received());
917 }
918
[email protected]dd3aa792013-07-16 19:10:23919 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44920}
921
922TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
923 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36924 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44925 FillBuffer(buffer.get(), buffer_size);
926
[email protected]6cdfd7f2013-02-08 20:40:15927 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52928 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44929 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30930 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44931
avibf0746c2015-12-09 19:53:14932 int64_t file_size;
[email protected]56285702013-12-04 18:22:49933 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44934
935 const size_t first_byte_position = 500;
936 const size_t last_byte_position = buffer_size - 1;
937 const size_t content_length = last_byte_position - first_byte_position + 1;
938 std::string partial_buffer_string(buffer.get() + first_byte_position,
939 buffer.get() + last_byte_position + 1);
940
941 TestDelegate d;
942 {
danakj8522a25b2016-04-16 00:17:36943 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36944 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44945
946 HttpRequestHeaders headers;
947 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59948 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38949 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19950 r->SetExtraRequestHeaders(headers);
951 r->Start();
952 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44953
[email protected]255620da2013-08-19 13:14:29954 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19955 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44956 EXPECT_EQ(1, d.response_started_count());
957 EXPECT_FALSE(d.received_data_before_response());
958 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
959 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
960 EXPECT_TRUE(partial_buffer_string == d.data_received());
961 }
962
[email protected]dd3aa792013-07-16 19:10:23963 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44964}
965
966TEST_F(URLRequestTest, FileTestMultipleRanges) {
967 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:36968 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44969 FillBuffer(buffer.get(), buffer_size);
970
[email protected]6cdfd7f2013-02-08 20:40:15971 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52972 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44973 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30974 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44975
avibf0746c2015-12-09 19:53:14976 int64_t file_size;
[email protected]56285702013-12-04 18:22:49977 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44978
979 TestDelegate d;
980 {
danakj8522a25b2016-04-16 00:17:36981 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36982 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44983
984 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38985 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19986 r->SetExtraRequestHeaders(headers);
987 r->Start();
988 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44989
[email protected]255620da2013-08-19 13:14:29990 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44991 EXPECT_TRUE(d.request_failed());
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
[email protected]3ca8b362013-11-11 22:18:07997TEST_F(URLRequestTest, AllowFileURLs) {
998 base::ScopedTempDir temp_dir;
999 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1000 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:521001 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071002 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301003 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591004 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071005
1006 {
1007 TestDelegate d;
1008 TestNetworkDelegate network_delegate;
1009 network_delegate.set_can_access_files(true);
1010 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361011 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361012 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191013 r->Start();
[email protected]3ca8b362013-11-11 22:18:071014 base::RunLoop().Run();
1015 EXPECT_FALSE(d.request_failed());
1016 EXPECT_EQ(test_data, d.data_received());
1017 }
1018
1019 {
1020 TestDelegate d;
1021 TestNetworkDelegate network_delegate;
1022 network_delegate.set_can_access_files(false);
1023 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361024 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361025 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191026 r->Start();
[email protected]3ca8b362013-11-11 22:18:071027 base::RunLoop().Run();
1028 EXPECT_TRUE(d.request_failed());
1029 EXPECT_EQ("", d.data_received());
1030 }
1031}
1032
[email protected]316c1e5e2012-09-12 15:17:441033
1034TEST_F(URLRequestTest, FileDirCancelTest) {
1035 // Put in mock resource provider.
1036 NetModule::SetResourceProvider(TestNetResourceProvider);
1037
1038 TestDelegate d;
1039 {
[email protected]6cdfd7f2013-02-08 20:40:151040 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441041 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1042 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1043 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1044
danakj8522a25b2016-04-16 00:17:361045 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361046 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191047 req->Start();
1048 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441049
1050 d.set_cancel_in_received_data_pending(true);
1051
[email protected]255620da2013-08-19 13:14:291052 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441053 }
1054
1055 // Take out mock resource provider.
1056 NetModule::SetResourceProvider(NULL);
1057}
1058
[email protected]5f9581402013-10-30 13:08:321059TEST_F(URLRequestTest, FileDirOutputSanity) {
1060 // Verify the general sanity of the the output of the file:
1061 // directory lister by checking for the output of a known existing
1062 // file.
1063 const char sentinel_name[] = "filedir-sentinel";
1064
1065 base::FilePath path;
1066 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471067 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321068
1069 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361070 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361071 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191072 req->Start();
[email protected]5f9581402013-10-30 13:08:321073 base::RunLoop().Run();
1074
1075 // Generate entry for the sentinel file.
1076 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581077 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491078 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321079 EXPECT_GT(info.size, 0);
1080 std::string sentinel_output = GetDirectoryListingEntry(
1081 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1082 std::string(sentinel_name),
1083 false /* is_dir */,
1084 info.size,
1085 info.last_modified);
1086
1087 ASSERT_LT(0, d.bytes_received());
1088 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191089 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321090 // Check for the entry generated for the "sentinel" file.
1091 const std::string& data = d.data_received();
1092 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1093}
1094
[email protected]316c1e5e2012-09-12 15:17:441095TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1096 // There is an implicit redirect when loading a file path that matches a
1097 // directory and does not end with a slash. Ensure that following such
1098 // redirects does not crash. See http://crbug.com/18686.
1099
[email protected]6cdfd7f2013-02-08 20:40:151100 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441101 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471102 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441103
1104 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361105 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361106 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191107 req->Start();
[email protected]255620da2013-08-19 13:14:291108 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441109
1110 ASSERT_EQ(1, d.received_redirect_count());
1111 ASSERT_LT(0, d.bytes_received());
1112 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191113 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441114}
1115
1116#if defined(OS_WIN)
1117// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1118TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1119 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361120 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361121 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191122 req->Start();
[email protected]255620da2013-08-19 13:14:291123 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441124
1125 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191126 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441127}
[email protected]5ecf7cb282014-05-11 01:49:551128#endif // defined(OS_WIN)
1129
1130#endif // !defined(DISABLE_FILE_SUPPORT)
1131
1132TEST_F(URLRequestTest, InvalidUrlTest) {
1133 TestDelegate d;
1134 {
danakj8522a25b2016-04-16 00:17:361135 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361136 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551137
[email protected]f7022f32014-08-21 16:32:191138 r->Start();
1139 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551140
1141 base::RunLoop().Run();
1142 EXPECT_TRUE(d.request_failed());
1143 }
1144}
1145
jochen0e3b3a62014-09-16 18:31:231146TEST_F(URLRequestTest, InvalidReferrerTest) {
1147 TestURLRequestContext context;
1148 TestNetworkDelegate network_delegate;
1149 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1150 context.set_network_delegate(&network_delegate);
1151 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361152 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361153 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231154 req->SetReferrer("https://somewhere.com/");
1155
1156 req->Start();
1157 base::RunLoop().Run();
1158 EXPECT_TRUE(d.request_failed());
1159}
1160
[email protected]5ecf7cb282014-05-11 01:49:551161#if defined(OS_WIN)
1162TEST_F(URLRequestTest, ResolveShortcutTest) {
1163 base::FilePath app_path;
1164 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471165 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551166 app_path = app_path.AppendASCII("with-headers.html");
1167
1168 std::wstring lnk_path = app_path.value() + L".lnk";
1169
1170 base::win::ScopedCOMInitializer com_initializer;
1171
1172 // Temporarily create a shortcut for test
1173 {
1174 base::win::ScopedComPtr<IShellLink> shell;
1175 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1176 CLSCTX_INPROC_SERVER)));
1177 base::win::ScopedComPtr<IPersistFile> persist;
1178 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1179 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1180 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1181 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1182 }
1183
1184 TestDelegate d;
1185 {
danakj8522a25b2016-04-16 00:17:361186 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361187 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551188
[email protected]f7022f32014-08-21 16:32:191189 r->Start();
1190 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551191
1192 base::RunLoop().Run();
1193
1194 WIN32_FILE_ATTRIBUTE_DATA data;
1195 GetFileAttributesEx(app_path.value().c_str(),
1196 GetFileExInfoStandard, &data);
1197 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1198 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1199 FILE_ATTRIBUTE_NORMAL, NULL);
1200 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361201 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551202 DWORD read_size;
1203 BOOL result;
1204 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1205 &read_size, NULL);
1206 std::string content(buffer.get(), read_size);
1207 CloseHandle(file);
1208
[email protected]f7022f32014-08-21 16:32:191209 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551210 EXPECT_EQ(1, d.received_redirect_count());
1211 EXPECT_EQ(content, d.data_received());
1212 }
1213
1214 // Clean the shortcut
1215 DeleteFile(lnk_path.c_str());
1216}
1217#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441218
1219// Custom URLRequestJobs for use with interceptor tests
1220class RestartTestJob : public URLRequestTestJob {
1221 public:
1222 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1223 : URLRequestTestJob(request, network_delegate, true) {}
1224 protected:
dchengb03027d2014-10-21 12:00:201225 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441226 private:
dchengb03027d2014-10-21 12:00:201227 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441228};
1229
1230class CancelTestJob : public URLRequestTestJob {
1231 public:
1232 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1233 : URLRequestTestJob(request, network_delegate, true) {}
1234 protected:
dchengb03027d2014-10-21 12:00:201235 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441236 private:
dchengb03027d2014-10-21 12:00:201237 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441238};
1239
1240class CancelThenRestartTestJob : public URLRequestTestJob {
1241 public:
1242 explicit CancelThenRestartTestJob(URLRequest* request,
1243 NetworkDelegate* network_delegate)
1244 : URLRequestTestJob(request, network_delegate, true) {
1245 }
1246 protected:
dchengb03027d2014-10-21 12:00:201247 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441248 request_->Cancel();
1249 this->NotifyRestartRequired();
1250 }
1251 private:
dchengb03027d2014-10-21 12:00:201252 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441253};
1254
bengr1bf8e942014-11-07 01:36:501255// An Interceptor for use with interceptor tests.
1256class MockURLRequestInterceptor : public URLRequestInterceptor {
1257 public:
1258 // Static getters for canned response header and data strings.
1259 static std::string ok_data() {
1260 return URLRequestTestJob::test_data_1();
1261 }
1262
1263 static std::string ok_headers() {
1264 return URLRequestTestJob::test_headers();
1265 }
1266
1267 static std::string redirect_data() {
1268 return std::string();
1269 }
1270
1271 static std::string redirect_headers() {
1272 return URLRequestTestJob::test_redirect_headers();
1273 }
1274
1275 static std::string error_data() {
1276 return std::string("ohhh nooooo mr. bill!");
1277 }
1278
1279 static std::string error_headers() {
1280 return URLRequestTestJob::test_error_headers();
1281 }
1282
1283 MockURLRequestInterceptor()
1284 : intercept_main_request_(false), restart_main_request_(false),
1285 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1286 simulate_main_network_error_(false),
1287 intercept_redirect_(false), cancel_redirect_request_(false),
1288 intercept_final_response_(false), cancel_final_request_(false),
1289 use_url_request_http_job_(false),
1290 did_intercept_main_(false), did_restart_main_(false),
1291 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1292 did_simulate_error_main_(false),
1293 did_intercept_redirect_(false), did_cancel_redirect_(false),
1294 did_intercept_final_(false), did_cancel_final_(false) {
1295 }
1296
1297 ~MockURLRequestInterceptor() override {
1298 }
1299
1300 // URLRequestInterceptor implementation:
1301 URLRequestJob* MaybeInterceptRequest(
1302 URLRequest* request,
1303 NetworkDelegate* network_delegate) const override {
1304 if (restart_main_request_) {
1305 restart_main_request_ = false;
1306 did_restart_main_ = true;
1307 return new RestartTestJob(request, network_delegate);
1308 }
1309 if (cancel_main_request_) {
1310 cancel_main_request_ = false;
1311 did_cancel_main_ = true;
1312 return new CancelTestJob(request, network_delegate);
1313 }
1314 if (cancel_then_restart_main_request_) {
1315 cancel_then_restart_main_request_ = false;
1316 did_cancel_then_restart_main_ = true;
1317 return new CancelThenRestartTestJob(request, network_delegate);
1318 }
1319 if (simulate_main_network_error_) {
1320 simulate_main_network_error_ = false;
1321 did_simulate_error_main_ = true;
1322 if (use_url_request_http_job_) {
1323 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1324 }
1325 // This job will result in error since the requested URL is not one of the
1326 // URLs supported by these tests.
1327 return new URLRequestTestJob(request, network_delegate, true);
1328 }
1329 if (!intercept_main_request_)
1330 return nullptr;
1331 intercept_main_request_ = false;
1332 did_intercept_main_ = true;
1333 URLRequestTestJob* job = new URLRequestTestJob(request,
1334 network_delegate,
1335 main_headers_,
1336 main_data_,
1337 true);
1338 job->set_load_timing_info(main_request_load_timing_info_);
1339 return job;
1340 }
1341
1342 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1343 NetworkDelegate* network_delegate,
1344 const GURL& location) const override {
1345 if (cancel_redirect_request_) {
1346 cancel_redirect_request_ = false;
1347 did_cancel_redirect_ = true;
1348 return new CancelTestJob(request, network_delegate);
1349 }
1350 if (!intercept_redirect_)
1351 return nullptr;
1352 intercept_redirect_ = false;
1353 did_intercept_redirect_ = true;
1354 if (use_url_request_http_job_) {
1355 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1356 }
1357 return new URLRequestTestJob(request,
1358 network_delegate,
1359 redirect_headers_,
1360 redirect_data_,
1361 true);
1362 }
1363
1364 URLRequestJob* MaybeInterceptResponse(
1365 URLRequest* request,
1366 NetworkDelegate* network_delegate) const override {
1367 if (cancel_final_request_) {
1368 cancel_final_request_ = false;
1369 did_cancel_final_ = true;
1370 return new CancelTestJob(request, network_delegate);
1371 }
1372 if (!intercept_final_response_)
1373 return nullptr;
1374 intercept_final_response_ = false;
1375 did_intercept_final_ = true;
1376 if (use_url_request_http_job_) {
1377 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1378 }
1379 return new URLRequestTestJob(request,
1380 network_delegate,
1381 final_headers_,
1382 final_data_,
1383 true);
1384 }
1385
1386 void set_intercept_main_request(bool intercept_main_request) {
1387 intercept_main_request_ = intercept_main_request;
1388 }
1389
1390 void set_main_headers(const std::string& main_headers) {
1391 main_headers_ = main_headers;
1392 }
1393
1394 void set_main_data(const std::string& main_data) {
1395 main_data_ = main_data;
1396 }
1397
1398 void set_main_request_load_timing_info(
1399 const LoadTimingInfo& main_request_load_timing_info) {
1400 main_request_load_timing_info_ = main_request_load_timing_info;
1401 }
1402
1403 void set_restart_main_request(bool restart_main_request) {
1404 restart_main_request_ = restart_main_request;
1405 }
1406
1407 void set_cancel_main_request(bool cancel_main_request) {
1408 cancel_main_request_ = cancel_main_request;
1409 }
1410
1411 void set_cancel_then_restart_main_request(
1412 bool cancel_then_restart_main_request) {
1413 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1414 }
1415
1416 void set_simulate_main_network_error(bool simulate_main_network_error) {
1417 simulate_main_network_error_ = simulate_main_network_error;
1418 }
1419
1420 void set_intercept_redirect(bool intercept_redirect) {
1421 intercept_redirect_ = intercept_redirect;
1422 }
1423
1424 void set_redirect_headers(const std::string& redirect_headers) {
1425 redirect_headers_ = redirect_headers;
1426 }
1427
1428 void set_redirect_data(const std::string& redirect_data) {
1429 redirect_data_ = redirect_data;
1430 }
1431
1432 void set_cancel_redirect_request(bool cancel_redirect_request) {
1433 cancel_redirect_request_ = cancel_redirect_request;
1434 }
1435
1436 void set_intercept_final_response(bool intercept_final_response) {
1437 intercept_final_response_ = intercept_final_response;
1438 }
1439
1440 void set_final_headers(const std::string& final_headers) {
1441 final_headers_ = final_headers;
1442 }
1443
1444 void set_final_data(const std::string& final_data) {
1445 final_data_ = final_data;
1446 }
1447
1448 void set_cancel_final_request(bool cancel_final_request) {
1449 cancel_final_request_ = cancel_final_request;
1450 }
1451
1452 void set_use_url_request_http_job(bool use_url_request_http_job) {
1453 use_url_request_http_job_ = use_url_request_http_job;
1454 }
1455
1456 bool did_intercept_main() const {
1457 return did_intercept_main_;
1458 }
1459
1460 bool did_restart_main() const {
1461 return did_restart_main_;
1462 }
1463
1464 bool did_cancel_main() const {
1465 return did_cancel_main_;
1466 }
1467
1468 bool did_cancel_then_restart_main() const {
1469 return did_cancel_then_restart_main_;
1470 }
1471
1472 bool did_simulate_error_main() const {
1473 return did_simulate_error_main_;
1474 }
1475
1476 bool did_intercept_redirect() const {
1477 return did_intercept_redirect_;
1478 }
1479
1480 bool did_cancel_redirect() const {
1481 return did_cancel_redirect_;
1482 }
1483
1484 bool did_intercept_final() const {
1485 return did_intercept_final_;
1486 }
1487
1488 bool did_cancel_final() const {
1489 return did_cancel_final_;
1490 }
1491
1492 private:
1493 // Indicate whether to intercept the main request, and if so specify the
1494 // response to return and the LoadTimingInfo to use.
1495 mutable bool intercept_main_request_;
1496 mutable std::string main_headers_;
1497 mutable std::string main_data_;
1498 mutable LoadTimingInfo main_request_load_timing_info_;
1499
1500 // These indicate actions that can be taken within MaybeInterceptRequest.
1501 mutable bool restart_main_request_;
1502 mutable bool cancel_main_request_;
1503 mutable bool cancel_then_restart_main_request_;
1504 mutable bool simulate_main_network_error_;
1505
1506 // Indicate whether to intercept redirects, and if so specify the response to
1507 // return.
1508 mutable bool intercept_redirect_;
1509 mutable std::string redirect_headers_;
1510 mutable std::string redirect_data_;
1511
1512 // Cancel the request within MaybeInterceptRedirect.
1513 mutable bool cancel_redirect_request_;
1514
1515 // Indicate whether to intercept the final response, and if so specify the
1516 // response to return.
1517 mutable bool intercept_final_response_;
1518 mutable std::string final_headers_;
1519 mutable std::string final_data_;
1520
1521 // Cancel the final request within MaybeInterceptResponse.
1522 mutable bool cancel_final_request_;
1523
1524 // Instruct the interceptor to use a real URLRequestHTTPJob.
1525 mutable bool use_url_request_http_job_;
1526
1527 // These indicate if the interceptor did something or not.
1528 mutable bool did_intercept_main_;
1529 mutable bool did_restart_main_;
1530 mutable bool did_cancel_main_;
1531 mutable bool did_cancel_then_restart_main_;
1532 mutable bool did_simulate_error_main_;
1533 mutable bool did_intercept_redirect_;
1534 mutable bool did_cancel_redirect_;
1535 mutable bool did_intercept_final_;
1536 mutable bool did_cancel_final_;
1537};
1538
1539// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1540class URLRequestInterceptorTest : public URLRequestTest {
1541 public:
1542 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1543 }
1544
1545 ~URLRequestInterceptorTest() override {
1546 // URLRequestJobs may post clean-up tasks on destruction.
1547 base::RunLoop().RunUntilIdle();
1548 }
1549
1550 void SetUpFactory() override {
1551 interceptor_ = new MockURLRequestInterceptor();
1552 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361553 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501554 }
1555
1556 MockURLRequestInterceptor* interceptor() const {
1557 return interceptor_;
1558 }
1559
1560 private:
1561 MockURLRequestInterceptor* interceptor_;
1562};
1563
1564TEST_F(URLRequestInterceptorTest, Intercept) {
1565 // Intercept the main request and respond with a simple response.
1566 interceptor()->set_intercept_main_request(true);
1567 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1568 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591569 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361570 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361571 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501572 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1573 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1574 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1575 req->SetUserData(nullptr, user_data0);
1576 req->SetUserData(&user_data1, user_data1);
1577 req->SetUserData(&user_data2, user_data2);
1578 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191579 req->Start();
[email protected]255620da2013-08-19 13:14:291580 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591581
bengr1bf8e942014-11-07 01:36:501582 // Make sure we can retrieve our specific user data.
1583 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1584 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1585 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591586
bengr1bf8e942014-11-07 01:36:501587 // Check that we got one good response.
1588 EXPECT_TRUE(req->status().is_success());
1589 EXPECT_EQ(200, req->response_headers()->response_code());
1590 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1591 EXPECT_EQ(1, d.response_started_count());
1592 EXPECT_EQ(0, d.received_redirect_count());
1593}
[email protected]2bba3252013-04-08 19:50:591594
bengr1bf8e942014-11-07 01:36:501595TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1596 // Intercept the main request and respond with a redirect.
1597 interceptor()->set_intercept_main_request(true);
1598 interceptor()->set_main_headers(
1599 MockURLRequestInterceptor::redirect_headers());
1600 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1601
1602 // Intercept that redirect and respond with a final OK response.
1603 interceptor()->set_intercept_redirect(true);
1604 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1605 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1606
1607 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361608 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361609 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501610 req->set_method("GET");
1611 req->Start();
1612 base::RunLoop().Run();
1613
1614 // Check that the interceptor got called as expected.
1615 EXPECT_TRUE(interceptor()->did_intercept_main());
1616 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1617
1618 // Check that we got one good response.
1619 EXPECT_TRUE(req->status().is_success());
1620 if (req->status().is_success())
1621 EXPECT_EQ(200, req->response_headers()->response_code());
1622
1623 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1624 EXPECT_EQ(1, d.response_started_count());
1625 EXPECT_EQ(0, d.received_redirect_count());
1626}
1627
1628TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1629 // Intercept the main request to generate a server error response.
1630 interceptor()->set_intercept_main_request(true);
1631 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1632 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1633
1634 // Intercept that error and respond with an OK response.
1635 interceptor()->set_intercept_final_response(true);
1636 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1637 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1638
1639 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361640 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361641 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501642 req->set_method("GET");
1643 req->Start();
1644 base::RunLoop().Run();
1645
1646 // Check that the interceptor got called as expected.
1647 EXPECT_TRUE(interceptor()->did_intercept_main());
1648 EXPECT_TRUE(interceptor()->did_intercept_final());
1649
1650 // Check that we got one good response.
1651 EXPECT_TRUE(req->status().is_success());
1652 EXPECT_EQ(200, req->response_headers()->response_code());
1653 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1654 EXPECT_EQ(1, d.response_started_count());
1655 EXPECT_EQ(0, d.received_redirect_count());
1656}
1657
1658TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1659 // Intercept the main request to simulate a network error.
1660 interceptor()->set_simulate_main_network_error(true);
1661
1662 // Intercept that error and respond with an OK response.
1663 interceptor()->set_intercept_final_response(true);
1664 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1665 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1666
1667 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361668 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361669 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501670 req->set_method("GET");
1671 req->Start();
1672 base::RunLoop().Run();
1673
1674 // Check that the interceptor got called as expected.
1675 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1676 EXPECT_TRUE(interceptor()->did_intercept_final());
1677
1678 // Check that we received one good response.
1679 EXPECT_TRUE(req->status().is_success());
1680 EXPECT_EQ(200, req->response_headers()->response_code());
1681 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1682 EXPECT_EQ(1, d.response_started_count());
1683 EXPECT_EQ(0, d.received_redirect_count());
1684}
1685
1686TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1687 // Restart the main request.
1688 interceptor()->set_restart_main_request(true);
1689
1690 // then intercept the new main request and respond with an OK response
1691 interceptor()->set_intercept_main_request(true);
1692 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1693 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1694
1695 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361696 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361697 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501698 req->set_method("GET");
1699 req->Start();
1700 base::RunLoop().Run();
1701
1702 // Check that the interceptor got called as expected.
1703 EXPECT_TRUE(interceptor()->did_restart_main());
1704 EXPECT_TRUE(interceptor()->did_intercept_main());
1705
1706 // Check that we received one good response.
1707 EXPECT_TRUE(req->status().is_success());
1708 if (req->status().is_success())
1709 EXPECT_EQ(200, req->response_headers()->response_code());
1710
1711 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1712 EXPECT_EQ(1, d.response_started_count());
1713 EXPECT_EQ(0, d.received_redirect_count());
1714}
1715
1716TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1717 // Intercept the main request and cancel from within the restarted job.
1718 interceptor()->set_cancel_main_request(true);
1719
1720 // Set up to intercept the final response and override it with an OK response.
1721 interceptor()->set_intercept_final_response(true);
1722 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1723 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1724
1725 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361726 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361727 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501728 req->set_method("GET");
1729 req->Start();
1730 base::RunLoop().Run();
1731
1732 // Check that the interceptor got called as expected.
1733 EXPECT_TRUE(interceptor()->did_cancel_main());
1734 EXPECT_FALSE(interceptor()->did_intercept_final());
1735
1736 // Check that we see a canceled request.
1737 EXPECT_FALSE(req->status().is_success());
1738 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1739}
1740
1741TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1742 // Intercept the main request and respond with a redirect.
1743 interceptor()->set_intercept_main_request(true);
1744 interceptor()->set_main_headers(
1745 MockURLRequestInterceptor::redirect_headers());
1746 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1747
1748 // Intercept the redirect and cancel from within that job.
1749 interceptor()->set_cancel_redirect_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_intercept_main());
1765 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1766 EXPECT_FALSE(interceptor()->did_intercept_final());
1767
1768 // Check that we see a canceled request.
1769 EXPECT_FALSE(req->status().is_success());
1770 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1771}
1772
1773TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1774 // Intercept the main request to simulate a network error.
1775 interceptor()->set_simulate_main_network_error(true);
1776
1777 // Set up to intercept final the response and cancel from within that job.
1778 interceptor()->set_cancel_final_request(true);
1779
1780 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361781 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361782 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501783 req->set_method("GET");
1784 req->Start();
1785 base::RunLoop().Run();
1786
1787 // Check that the interceptor got called as expected.
1788 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1789 EXPECT_TRUE(interceptor()->did_cancel_final());
1790
1791 // Check that we see a canceled request.
1792 EXPECT_FALSE(req->status().is_success());
1793 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1794}
1795
1796TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1797 // Intercept the main request and cancel then restart from within that job.
1798 interceptor()->set_cancel_then_restart_main_request(true);
1799
1800 // Set up to intercept the final response and override it with an OK response.
1801 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501802 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1803 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501804
1805 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361806 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361807 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501808 req->set_method("GET");
1809 req->Start();
1810 base::RunLoop().Run();
1811
1812 // Check that the interceptor got called as expected.
1813 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1814 EXPECT_FALSE(interceptor()->did_intercept_final());
1815
1816 // Check that we see a canceled request.
1817 EXPECT_FALSE(req->status().is_success());
1818 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591819}
1820
1821// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1822// reused. |connect_time_flags| is used to indicate if there should be dns
1823// or SSL times, and |used_proxy| is used for proxy times.
1824LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1825 int connect_time_flags,
1826 bool used_proxy) {
1827 LoadTimingInfo load_timing;
1828 load_timing.socket_log_id = 1;
1829
1830 if (used_proxy) {
1831 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1832 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1833 }
1834
1835 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1836 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1837 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1838 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1839 }
1840 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1841 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1842 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1843 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1844 }
1845 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1846
1847 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1848 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1849 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1850 return load_timing;
1851}
1852
1853// Same as above, but in the case of a reused socket.
1854LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1855 bool used_proxy) {
1856 LoadTimingInfo load_timing;
1857 load_timing.socket_log_id = 1;
1858 load_timing.socket_reused = true;
1859
1860 if (used_proxy) {
1861 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1862 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1863 }
1864
1865 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1866 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1867 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1868 return load_timing;
1869}
1870
bengr1bf8e942014-11-07 01:36:501871LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1872 const LoadTimingInfo& job_load_timing,
1873 const URLRequestContext& context,
1874 MockURLRequestInterceptor* interceptor) {
1875 interceptor->set_intercept_main_request(true);
1876 interceptor->set_main_request_load_timing_info(job_load_timing);
1877 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361878 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361879 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501880 req->Start();
1881 base::RunLoop().Run();
1882
1883 LoadTimingInfo resulting_load_timing;
1884 req->GetLoadTimingInfo(&resulting_load_timing);
1885
1886 // None of these should be modified by the URLRequest.
1887 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1888 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1889 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1890 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1891 EXPECT_EQ(job_load_timing.receive_headers_end,
1892 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571893 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1894 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501895
1896 return resulting_load_timing;
1897}
1898
[email protected]2bba3252013-04-08 19:50:591899// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501900TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591901 base::TimeTicks now = base::TimeTicks::Now();
1902 LoadTimingInfo job_load_timing =
1903 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1904
[email protected]2ca01e52013-10-31 22:05:191905 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501906 RunURLRequestInterceptorLoadTimingTest(
1907 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591908
1909 // Nothing should have been changed by the URLRequest.
1910 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1911 load_timing_result.proxy_resolve_start);
1912 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1913 load_timing_result.proxy_resolve_end);
1914 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1915 load_timing_result.connect_timing.dns_start);
1916 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1917 load_timing_result.connect_timing.dns_end);
1918 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1919 load_timing_result.connect_timing.connect_start);
1920 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1921 load_timing_result.connect_timing.connect_end);
1922 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1923 load_timing_result.connect_timing.ssl_start);
1924 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1925 load_timing_result.connect_timing.ssl_end);
1926
1927 // Redundant sanity check.
1928 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1929}
1930
1931// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501932TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591933 base::TimeTicks now = base::TimeTicks::Now();
1934 LoadTimingInfo job_load_timing =
1935 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1936
[email protected]2ca01e52013-10-31 22:05:191937 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501938 RunURLRequestInterceptorLoadTimingTest(
1939 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591940
1941 // Nothing should have been changed by the URLRequest.
1942 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1943 load_timing_result.proxy_resolve_start);
1944 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1945 load_timing_result.proxy_resolve_end);
1946 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1947 load_timing_result.connect_timing.dns_start);
1948 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1949 load_timing_result.connect_timing.dns_end);
1950 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1951 load_timing_result.connect_timing.connect_start);
1952 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1953 load_timing_result.connect_timing.connect_end);
1954 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1955 load_timing_result.connect_timing.ssl_start);
1956 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1957 load_timing_result.connect_timing.ssl_end);
1958
1959 // Redundant sanity check.
1960 TestLoadTimingNotReusedWithProxy(load_timing_result,
1961 CONNECT_TIMING_HAS_SSL_TIMES);
1962}
1963
1964// Make sure that URLRequest correctly adjusts proxy times when they're before
1965// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101966// the case of reusing a SPDY session. The connected socket is not considered
1967// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591968//
1969// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501970TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591971 base::TimeTicks now = base::TimeTicks::Now();
1972 LoadTimingInfo job_load_timing =
1973 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1974 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1975 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1976 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1977 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1978 job_load_timing.connect_timing.connect_start =
1979 now - base::TimeDelta::FromDays(2);
1980 job_load_timing.connect_timing.connect_end =
1981 now - base::TimeDelta::FromDays(1);
1982
[email protected]2ca01e52013-10-31 22:05:191983 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501984 RunURLRequestInterceptorLoadTimingTest(
1985 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591986
1987 // Proxy times, connect times, and DNS times should all be replaced with
1988 // request_start.
1989 EXPECT_EQ(load_timing_result.request_start,
1990 load_timing_result.proxy_resolve_start);
1991 EXPECT_EQ(load_timing_result.request_start,
1992 load_timing_result.proxy_resolve_end);
1993 EXPECT_EQ(load_timing_result.request_start,
1994 load_timing_result.connect_timing.dns_start);
1995 EXPECT_EQ(load_timing_result.request_start,
1996 load_timing_result.connect_timing.dns_end);
1997 EXPECT_EQ(load_timing_result.request_start,
1998 load_timing_result.connect_timing.connect_start);
1999 EXPECT_EQ(load_timing_result.request_start,
2000 load_timing_result.connect_timing.connect_end);
2001
2002 // Other times should have been left null.
2003 TestLoadTimingNotReusedWithProxy(load_timing_result,
2004 CONNECT_TIMING_HAS_DNS_TIMES);
2005}
2006
2007// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502008TEST_F(URLRequestInterceptorTest,
2009 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592010 base::TimeTicks now = base::TimeTicks::Now();
2011 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2012 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2013 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2014
[email protected]2ca01e52013-10-31 22:05:192015 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502016 RunURLRequestInterceptorLoadTimingTest(
2017 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592018
2019 // Proxy times and connect times should all be replaced with 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
2025 // Other times should have been left null.
2026 TestLoadTimingReusedWithProxy(load_timing_result);
2027}
2028
2029// Make sure that URLRequest correctly adjusts connect times when they're before
2030// |request_start|, due to reusing a connected socket. The connected socket is
2031// not considered reused in this test (May be a preconnect).
2032//
2033// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502034TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592035 base::TimeTicks now = base::TimeTicks::Now();
2036 LoadTimingInfo job_load_timing =
2037 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2038 job_load_timing.connect_timing.connect_start =
2039 now - base::TimeDelta::FromDays(1);
2040 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2041 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2042 job_load_timing.connect_timing.connect_end =
2043 now - base::TimeDelta::FromDays(4);
2044
[email protected]2ca01e52013-10-31 22:05:192045 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502046 RunURLRequestInterceptorLoadTimingTest(
2047 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592048
2049 // Connect times, and SSL times should be replaced with request_start.
2050 EXPECT_EQ(load_timing_result.request_start,
2051 load_timing_result.connect_timing.connect_start);
2052 EXPECT_EQ(load_timing_result.request_start,
2053 load_timing_result.connect_timing.ssl_start);
2054 EXPECT_EQ(load_timing_result.request_start,
2055 load_timing_result.connect_timing.ssl_end);
2056 EXPECT_EQ(load_timing_result.request_start,
2057 load_timing_result.connect_timing.connect_end);
2058
2059 // Other times should have been left null.
2060 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2061}
2062
2063// Make sure that URLRequest correctly adjusts connect times when they're before
2064// |request_start|, due to reusing a connected socket in the case that there
2065// are also proxy times. The connected socket is not considered reused in this
2066// test (May be a preconnect).
2067//
2068// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502069TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592070 base::TimeTicks now = base::TimeTicks::Now();
2071 LoadTimingInfo job_load_timing =
2072 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2073 job_load_timing.connect_timing.connect_start =
2074 now - base::TimeDelta::FromDays(1);
2075 job_load_timing.connect_timing.connect_end =
2076 now - base::TimeDelta::FromDays(2);
2077
[email protected]2ca01e52013-10-31 22:05:192078 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502079 RunURLRequestInterceptorLoadTimingTest(
2080 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592081
2082 // Connect times should be replaced with proxy_resolve_end.
2083 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2084 load_timing_result.connect_timing.connect_start);
2085 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2086 load_timing_result.connect_timing.connect_end);
2087
2088 // Other times should have been left null.
2089 TestLoadTimingNotReusedWithProxy(load_timing_result,
2090 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2091}
2092
[email protected]316c1e5e2012-09-12 15:17:442093// Check that two different URL requests have different identifiers.
2094TEST_F(URLRequestTest, Identifiers) {
2095 TestDelegate d;
2096 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362097 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362098 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362099 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362100 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442101
mmenke19378d22014-09-09 04:12:592102 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442103}
2104
blundellb8163592f2015-12-16 14:22:422105#if defined(OS_IOS)
2106// TODO(droger): Check that a failure to connect to the proxy is reported to
2107// the network delegate. crbug.com/496743
2108#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2109#else
2110#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2111#endif
2112TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442113 MockHostResolver host_resolver;
2114 host_resolver.rules()->AddSimulatedFailure("*");
2115
[email protected]ceefd7fd2012-11-29 00:36:242116 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442117 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2118
2119 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362120 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362121 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192122 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442123
[email protected]f7022f32014-08-21 16:32:192124 req->Start();
[email protected]255620da2013-08-19 13:14:292125 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442126
2127 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192128 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152129 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192130 EXPECT_TRUE(req->proxy_server().IsEmpty());
2131 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2132 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442133
2134 EXPECT_EQ(1, network_delegate.error_count());
2135 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2136 EXPECT_EQ(1, network_delegate.completed_requests());
2137}
2138
[email protected]cba24642014-08-15 20:49:592139// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442140// content is empty.
2141TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2142 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362143 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362144 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192145 req->Start();
[email protected]255620da2013-08-19 13:14:292146 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442147 EXPECT_EQ("", d.data_received());
2148 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2149}
2150
[email protected]5033ab82013-03-22 20:17:462151// Make sure that SetPriority actually sets the URLRequest's priority
2152// correctly, both before and after start.
2153TEST_F(URLRequestTest, SetPriorityBasic) {
2154 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362155 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362156 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192157 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462158
[email protected]f7022f32014-08-21 16:32:192159 req->SetPriority(LOW);
2160 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462161
[email protected]f7022f32014-08-21 16:32:192162 req->Start();
2163 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462164
[email protected]f7022f32014-08-21 16:32:192165 req->SetPriority(MEDIUM);
2166 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462167}
2168
2169// Make sure that URLRequest calls SetPriority on a job before calling
2170// Start on it.
2171TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2172 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362173 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362174 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192175 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462176
mmenkeed0498b2015-12-08 23:20:422177 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362178 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422179 req.get(), &default_network_delegate_, &job_priority));
2180 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2181 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462182
[email protected]f7022f32014-08-21 16:32:192183 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462184
[email protected]f7022f32014-08-21 16:32:192185 req->Start();
mmenkeed0498b2015-12-08 23:20:422186 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462187}
2188
2189// Make sure that URLRequest passes on its priority updates to its
2190// job.
2191TEST_F(URLRequestTest, SetJobPriority) {
2192 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362193 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362194 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462195
mmenkeed0498b2015-12-08 23:20:422196 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362197 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422198 req.get(), &default_network_delegate_, &job_priority));
2199 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462200
[email protected]f7022f32014-08-21 16:32:192201 req->SetPriority(LOW);
2202 req->Start();
mmenkeed0498b2015-12-08 23:20:422203 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462204
[email protected]f7022f32014-08-21 16:32:192205 req->SetPriority(MEDIUM);
2206 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422207 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462208}
2209
[email protected]bb1c4662013-11-14 00:00:072210// Setting the IGNORE_LIMITS load flag should be okay if the priority
2211// is MAXIMUM_PRIORITY.
2212TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2213 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362214 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362215 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192216 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072217
mmenkeed0498b2015-12-08 23:20:422218 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362219 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422220 req.get(), &default_network_delegate_, &job_priority));
2221 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072222
[email protected]f7022f32014-08-21 16:32:192223 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2224 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072225
[email protected]f7022f32014-08-21 16:32:192226 req->SetPriority(MAXIMUM_PRIORITY);
2227 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072228
[email protected]f7022f32014-08-21 16:32:192229 req->Start();
2230 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422231 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072232}
2233
nick5d570de92015-05-04 20:16:162234namespace {
2235
2236// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552237class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442238 public:
tommycli59a63432015-11-06 00:10:552239 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2240 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272241 }
tommycli59a63432015-11-06 00:10:552242
2243 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2244};
tommyclieae5f75f2015-11-05 19:07:272245
nick5d570de92015-05-04 20:16:162246} // namespace
2247
[email protected]f2f31b32013-01-16 23:24:092248TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442249 LocalHttpTestServer test_server;
2250 ASSERT_TRUE(test_server.Start());
2251
2252 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362253 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502254 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442255
2256 // Set up a cookie.
2257 {
2258 TestNetworkDelegate network_delegate;
2259 context.set_network_delegate(&network_delegate);
2260 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362261 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552262 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362263 &d));
[email protected]f7022f32014-08-21 16:32:192264 req->Start();
[email protected]255620da2013-08-19 13:14:292265 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442266 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2267 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2268 EXPECT_EQ(1, network_delegate.set_cookie_count());
2269 }
2270
2271 // Verify that the cookie is set.
2272 {
2273 TestNetworkDelegate network_delegate;
2274 context.set_network_delegate(&network_delegate);
2275 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362276 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552277 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192278 req->Start();
[email protected]255620da2013-08-19 13:14:292279 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442280
2281 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2282 != std::string::npos);
2283 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2284 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2285 }
2286}
2287
[email protected]f2f31b32013-01-16 23:24:092288TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442289 LocalHttpTestServer test_server;
2290 ASSERT_TRUE(test_server.Start());
2291
2292 // Set up a cookie.
2293 {
2294 TestNetworkDelegate network_delegate;
2295 default_context_.set_network_delegate(&network_delegate);
2296 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362297 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552298 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362299 &d));
[email protected]f7022f32014-08-21 16:32:192300 req->Start();
[email protected]255620da2013-08-19 13:14:292301 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442302 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2303 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2304 }
2305
2306 // Verify that the cookie is set.
2307 {
2308 TestNetworkDelegate network_delegate;
2309 default_context_.set_network_delegate(&network_delegate);
2310 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362311 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552312 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192313 req->Start();
[email protected]255620da2013-08-19 13:14:292314 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442315
2316 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2317 != std::string::npos);
2318 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2319 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2320 }
2321
2322 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2323 {
2324 TestNetworkDelegate network_delegate;
2325 default_context_.set_network_delegate(&network_delegate);
2326 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362327 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552328 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192329 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2330 req->Start();
[email protected]255620da2013-08-19 13:14:292331 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442332
2333 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2334 == std::string::npos);
2335
2336 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2337 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2338 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2339 }
2340}
2341
2342TEST_F(URLRequestTest, DoNotSaveCookies) {
2343 LocalHttpTestServer test_server;
2344 ASSERT_TRUE(test_server.Start());
2345
2346 // Set up a cookie.
2347 {
2348 TestNetworkDelegate network_delegate;
2349 default_context_.set_network_delegate(&network_delegate);
2350 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362351 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552352 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362353 &d));
[email protected]f7022f32014-08-21 16:32:192354 req->Start();
[email protected]255620da2013-08-19 13:14:292355 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442356
2357 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2358 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2359 EXPECT_EQ(1, network_delegate.set_cookie_count());
2360 }
2361
2362 // Try to set-up another cookie and update the previous cookie.
2363 {
2364 TestNetworkDelegate network_delegate;
2365 default_context_.set_network_delegate(&network_delegate);
2366 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362367 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552368 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362369 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192370 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2371 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442372
[email protected]255620da2013-08-19 13:14:292373 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442374
2375 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2376 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2377 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2378 EXPECT_EQ(0, network_delegate.set_cookie_count());
2379 }
2380
2381 // Verify the cookies weren't saved or updated.
2382 {
2383 TestNetworkDelegate network_delegate;
2384 default_context_.set_network_delegate(&network_delegate);
2385 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362386 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552387 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192388 req->Start();
[email protected]255620da2013-08-19 13:14:292389 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442390
2391 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2392 == std::string::npos);
2393 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2394 != std::string::npos);
2395
2396 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2397 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2398 EXPECT_EQ(0, network_delegate.set_cookie_count());
2399 }
2400}
2401
2402TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2403 LocalHttpTestServer test_server;
2404 ASSERT_TRUE(test_server.Start());
2405
2406 // Set up a cookie.
2407 {
2408 TestNetworkDelegate network_delegate;
2409 default_context_.set_network_delegate(&network_delegate);
2410 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362411 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552412 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362413 &d));
[email protected]f7022f32014-08-21 16:32:192414 req->Start();
[email protected]255620da2013-08-19 13:14:292415 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442416
2417 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2418 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2419 }
2420
2421 // Verify that the cookie is set.
2422 {
2423 TestNetworkDelegate network_delegate;
2424 default_context_.set_network_delegate(&network_delegate);
2425 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362426 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552427 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192428 req->Start();
[email protected]255620da2013-08-19 13:14:292429 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442430
2431 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2432 != std::string::npos);
2433
2434 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2435 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2436 }
2437
2438 // Verify that the cookie isn't sent.
2439 {
2440 TestNetworkDelegate network_delegate;
2441 default_context_.set_network_delegate(&network_delegate);
2442 TestDelegate d;
2443 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362444 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552445 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &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_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2450 == std::string::npos);
2451
[email protected]22e045f2013-09-20 03:54:032452 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442453 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2454 }
2455}
2456
marqf14fff8d2015-12-02 15:52:292457// TODO(crbug.com/564656) This test is flaky on iOS.
2458#if defined(OS_IOS)
2459#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2460#else
2461#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2462#endif
[email protected]316c1e5e2012-09-12 15:17:442463TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2464 LocalHttpTestServer test_server;
2465 ASSERT_TRUE(test_server.Start());
2466
2467 // Set up a cookie.
2468 {
2469 TestNetworkDelegate network_delegate;
2470 default_context_.set_network_delegate(&network_delegate);
2471 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362472 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552473 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362474 &d));
[email protected]f7022f32014-08-21 16:32:192475 req->Start();
[email protected]255620da2013-08-19 13:14:292476 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442477
2478 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2479 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2480 }
2481
2482 // Try to set-up another cookie and update the previous cookie.
2483 {
2484 TestNetworkDelegate network_delegate;
2485 default_context_.set_network_delegate(&network_delegate);
2486 TestDelegate d;
2487 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362488 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552489 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362490 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192491 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442492
[email protected]255620da2013-08-19 13:14:292493 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442494
2495 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2496 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2497 }
2498
2499 // Verify the cookies weren't saved or updated.
2500 {
2501 TestNetworkDelegate network_delegate;
2502 default_context_.set_network_delegate(&network_delegate);
2503 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362504 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552505 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192506 req->Start();
[email protected]255620da2013-08-19 13:14:292507 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442508
2509 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2510 == std::string::npos);
2511 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2512 != std::string::npos);
2513
2514 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2515 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2516 }
2517}
2518
2519TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2520 LocalHttpTestServer test_server;
2521 ASSERT_TRUE(test_server.Start());
2522
2523 // Set up an empty cookie.
2524 {
2525 TestNetworkDelegate network_delegate;
2526 default_context_.set_network_delegate(&network_delegate);
2527 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362528 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552529 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192530 req->Start();
[email protected]255620da2013-08-19 13:14:292531 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442532
2533 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2534 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2535 EXPECT_EQ(0, network_delegate.set_cookie_count());
2536 }
2537}
2538
2539TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2540 LocalHttpTestServer test_server;
2541 ASSERT_TRUE(test_server.Start());
2542
2543 // Set up a cookie.
2544 {
2545 TestNetworkDelegate network_delegate;
2546 default_context_.set_network_delegate(&network_delegate);
2547 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362548 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552549 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362550 &d));
[email protected]f7022f32014-08-21 16:32:192551 req->Start();
[email protected]255620da2013-08-19 13:14:292552 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442553
2554 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2555 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2556 }
2557
2558 // Verify that the cookie is set.
2559 {
2560 TestNetworkDelegate network_delegate;
2561 default_context_.set_network_delegate(&network_delegate);
2562 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362563 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552564 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192565 req->Start();
[email protected]255620da2013-08-19 13:14:292566 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442567
2568 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2569 != std::string::npos);
2570
2571 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2572 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2573 }
2574
2575 // Verify that the cookie isn't sent.
2576 {
2577 TestNetworkDelegate network_delegate;
2578 default_context_.set_network_delegate(&network_delegate);
2579 TestDelegate d;
2580 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362581 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552582 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &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_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2587 == std::string::npos);
2588
[email protected]22e045f2013-09-20 03:54:032589 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442590 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2591 }
2592}
2593
2594TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2595 LocalHttpTestServer test_server;
2596 ASSERT_TRUE(test_server.Start());
2597
2598 // Set up a cookie.
2599 {
2600 TestNetworkDelegate network_delegate;
2601 default_context_.set_network_delegate(&network_delegate);
2602 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362603 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552604 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362605 &d));
[email protected]f7022f32014-08-21 16:32:192606 req->Start();
[email protected]255620da2013-08-19 13:14:292607 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442608
2609 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2610 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2611 }
2612
2613 // Try to set-up another cookie and update the previous cookie.
2614 {
2615 TestNetworkDelegate network_delegate;
2616 default_context_.set_network_delegate(&network_delegate);
2617 TestDelegate d;
2618 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362619 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552620 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362621 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192622 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442623
[email protected]255620da2013-08-19 13:14:292624 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442625
2626 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2627 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2628 }
2629
2630 // Verify the cookies weren't saved or updated.
2631 {
2632 TestNetworkDelegate network_delegate;
2633 default_context_.set_network_delegate(&network_delegate);
2634 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362635 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552636 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192637 req->Start();
[email protected]255620da2013-08-19 13:14:292638 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442639
2640 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2641 == std::string::npos);
2642 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2643 != std::string::npos);
2644
2645 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2646 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2647 }
2648}
2649
mkwstc5fa7762016-03-28 09:28:232650TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262651 LocalHttpTestServer test_server;
2652 ASSERT_TRUE(test_server.Start());
2653
mkwst202534e32016-01-15 16:07:152654 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152655 default_context_.set_network_delegate(&network_delegate);
2656
mkwstf71d0bd2016-03-21 14:15:242657 const std::string kHost = "example.test";
2658 const std::string kSubHost = "subdomain.example.test";
2659 const std::string kCrossHost = "cross-origin.test";
2660
2661 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262662 {
mkwst3f3daac2015-02-26 20:15:262663 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362664 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242665 test_server.GetURL(kHost,
2666 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2667 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362668 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262669 req->Start();
2670 base::RunLoop().Run();
2671 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2672 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242673 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262674 }
2675
mkwstf71d0bd2016-03-21 14:15:242676 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262677 {
mkwst3f3daac2015-02-26 20:15:262678 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362679 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242680 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2681 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2682 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262683 req->Start();
2684 base::RunLoop().Run();
2685
mkwstf71d0bd2016-03-21 14:15:242686 EXPECT_NE(std::string::npos,
2687 d.data_received().find("StrictSameSiteCookie=1"));
2688 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262689 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2690 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2691 }
2692
mkwstf71d0bd2016-03-21 14:15:242693 // Verify that both cookies are sent for same-registrable-domain requests.
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, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2698 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2699 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152700 req->Start();
2701 base::RunLoop().Run();
2702
mkwstf71d0bd2016-03-21 14:15:242703 EXPECT_NE(std::string::npos,
2704 d.data_received().find("StrictSameSiteCookie=1"));
2705 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152706 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2707 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2708 }
2709
mkwstf71d0bd2016-03-21 14:15:242710 // Verify that neither cookie is not sent for cross-site requests.
2711 {
2712 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362713 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242714 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2715 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2716 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2717 req->Start();
2718 base::RunLoop().Run();
2719
2720 EXPECT_EQ(std::string::npos,
2721 d.data_received().find("StrictSameSiteCookie=1"));
2722 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2723 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2724 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2725 }
2726
2727 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152728 // method is "safe".
2729 {
2730 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362731 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242732 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2733 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2734 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2735 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152736 req->Start();
2737 base::RunLoop().Run();
2738
mkwstf71d0bd2016-03-21 14:15:242739 EXPECT_EQ(std::string::npos,
2740 d.data_received().find("StrictSameSiteCookie=1"));
2741 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152742 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2743 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2744 }
2745
mkwstf71d0bd2016-03-21 14:15:242746 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152747 // method is unsafe (e.g. POST).
2748 {
2749 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362750 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242751 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2752 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2753 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152754 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262755 req->Start();
2756 base::RunLoop().Run();
2757
mkwstf71d0bd2016-03-21 14:15:242758 EXPECT_EQ(std::string::npos,
2759 d.data_received().find("StrictSameSiteCookie=1"));
2760 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262761 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2762 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2763 }
2764}
2765
estark557a5eb82015-12-01 22:57:102766// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362767TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552768 EmbeddedTestServer http_server;
2769 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362770 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552771 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2772 https_server.AddDefaultHandlers(
2773 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2774 ASSERT_TRUE(http_server.Start());
2775 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362776
estarkb15166b2015-12-18 16:56:382777 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362778 TestURLRequestContext context(true);
2779 context.set_network_delegate(&network_delegate);
2780 context.Init();
2781
estarkb15166b2015-12-18 16:56:382782 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362783 {
2784 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362785 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102786 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362787 DEFAULT_PRIORITY, &d));
2788 req->Start();
2789 base::RunLoop().Run();
2790 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2791 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2792 }
2793
2794 // Verify that the cookie is not set.
2795 {
2796 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362797 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552798 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362799 req->Start();
2800 base::RunLoop().Run();
2801
jww79aceda2015-12-07 01:56:342802 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2803 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362804 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2805 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2806 }
2807}
2808
estarkb15166b2015-12-18 16:56:382809TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552810 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2811 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362812 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552813 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362814
2815 TestNetworkDelegate network_delegate;
2816 TestURLRequestContext context(true);
2817 context.set_network_delegate(&network_delegate);
2818 context.Init();
2819
estarkb15166b2015-12-18 16:56:382820 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362821 {
2822 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362823 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102824 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552825 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362826 req->Start();
2827 base::RunLoop().Run();
2828 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2829 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2830 }
2831
2832 // Verify that the cookie is not set.
2833 {
2834 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362835 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552836 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362837 req->Start();
2838 base::RunLoop().Run();
2839
jww79aceda2015-12-07 01:56:342840 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362841 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2842 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2843 }
2844}
2845
estarkb15166b2015-12-18 16:56:382846TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552847 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2848 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362849 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552850 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362851
estarkb15166b2015-12-18 16:56:382852 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362853 TestURLRequestContext context(true);
2854 context.set_network_delegate(&network_delegate);
2855 context.Init();
2856
estarkb15166b2015-12-18 16:56:382857 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362858 {
2859 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362860 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102861 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552862 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362863 req->Start();
2864 base::RunLoop().Run();
2865 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2866 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2867 }
2868
2869 // Verify that the cookie is set.
2870 {
2871 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362872 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552873 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362874 req->Start();
2875 base::RunLoop().Run();
2876
jww79aceda2015-12-07 01:56:342877 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2878 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2879 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2880 }
2881}
2882
2883// Tests that secure cookies can't be set on non-secure origins if strict secure
2884// cookies are enabled.
2885TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2886 EmbeddedTestServer http_server;
2887 http_server.AddDefaultHandlers(
2888 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2889 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2890 https_server.AddDefaultHandlers(
2891 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2892 ASSERT_TRUE(http_server.Start());
2893 ASSERT_TRUE(https_server.Start());
2894
2895 TestExperimentalFeaturesNetworkDelegate network_delegate;
2896 TestURLRequestContext context(true);
2897 context.set_network_delegate(&network_delegate);
2898 context.Init();
2899
2900 // Try to set a Secure cookie, with experimental features enabled.
2901 {
2902 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362903 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342904 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2905 DEFAULT_PRIORITY, &d));
2906 req->Start();
2907 base::RunLoop().Run();
2908 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2909 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2910 }
2911
2912 // Verify that the cookie is not set.
2913 {
2914 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362915 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342916 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2917 req->Start();
2918 base::RunLoop().Run();
2919
2920 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2921 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2922 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2923 }
2924}
2925
2926// Tests that secure cookies can be set on secure origins even if strict secure
2927// cookies are enabled.
2928TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2929 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2930 https_server.AddDefaultHandlers(
2931 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2932 ASSERT_TRUE(https_server.Start());
2933
2934 TestExperimentalFeaturesNetworkDelegate network_delegate;
2935 TestURLRequestContext context(true);
2936 context.set_network_delegate(&network_delegate);
2937 context.Init();
2938
2939 // Try to set a Secure cookie, with experimental features enabled.
2940 {
2941 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362942 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342943 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2944 DEFAULT_PRIORITY, &d));
2945 req->Start();
2946 base::RunLoop().Run();
2947 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2948 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2949 }
2950
2951 // Verify that the cookie is not set.
2952 {
2953 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362954 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342955 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2956 req->Start();
2957 base::RunLoop().Run();
2958
2959 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362960 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2961 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2962 }
2963}
2964
mmenkefb18c772015-09-30 22:22:502965// Tests that a request is cancelled while entering suspend mode. Uses mocks
2966// rather than a spawned test server because the connection used to talk to
2967// the test server is affected by entering suspend mode on Android.
2968TEST_F(URLRequestTest, CancelOnSuspend) {
2969 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:362970 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:502971
2972 URLRequestFailedJob::AddUrlHandler();
2973
2974 TestDelegate d;
2975 // Request that just hangs.
2976 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:362977 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:502978 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
2979 r->Start();
2980
2981 power_monitor_source->Suspend();
2982 // Wait for the suspend notification to cause the request to fail.
2983 base::RunLoop().Run();
2984 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
2985 EXPECT_TRUE(d.request_failed());
2986 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2987
2988 URLRequestFilter::GetInstance()->ClearHandlers();
2989
2990 // Shouldn't be needed, but just in case.
2991 power_monitor_source->Resume();
2992}
2993
[email protected]5095cd72012-11-01 10:29:162994// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2995// value for the |fixed_date| argument given to the constructor.
2996class FixedDateNetworkDelegate : public TestNetworkDelegate {
2997 public:
2998 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2999 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203000 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163001
[email protected]cba24642014-08-15 20:49:593002 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203003 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593004 URLRequest* request,
3005 const CompletionCallback& callback,
3006 const HttpResponseHeaders* original_response_headers,
3007 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133008 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163009
3010 private:
3011 std::string fixed_date_;
3012
3013 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3014};
3015
3016int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593017 URLRequest* request,
3018 const CompletionCallback& callback,
3019 const HttpResponseHeaders* original_response_headers,
3020 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163021 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593022 HttpResponseHeaders* new_response_headers =
3023 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163024
3025 new_response_headers->RemoveHeader("Date");
3026 new_response_headers->AddHeader("Date: " + fixed_date_);
3027
3028 *override_response_headers = new_response_headers;
3029 return TestNetworkDelegate::OnHeadersReceived(request,
3030 callback,
3031 original_response_headers,
[email protected]5f714132014-03-26 10:41:163032 override_response_headers,
3033 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163034}
3035
3036// Test that cookie expiration times are adjusted for server/client clock
3037// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3038// headers by defaulting to GMT. (crbug.com/135131)
3039TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3040 LocalHttpTestServer test_server;
3041 ASSERT_TRUE(test_server.Start());
3042
3043 // Set up an expired cookie.
3044 {
3045 TestNetworkDelegate network_delegate;
3046 default_context_.set_network_delegate(&network_delegate);
3047 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363048 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193049 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553050 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363051 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193052 req->Start();
[email protected]255620da2013-08-19 13:14:293053 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163054 }
3055 // Verify that the cookie is not set.
3056 {
3057 TestNetworkDelegate network_delegate;
3058 default_context_.set_network_delegate(&network_delegate);
3059 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363060 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553061 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193062 req->Start();
[email protected]255620da2013-08-19 13:14:293063 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163064
3065 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3066 }
3067 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3068 {
3069 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3070 default_context_.set_network_delegate(&network_delegate);
3071 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363072 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193073 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553074 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363075 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193076 req->Start();
[email protected]255620da2013-08-19 13:14:293077 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163078 }
3079 // Verify that the cookie is set.
3080 {
3081 TestNetworkDelegate network_delegate;
3082 default_context_.set_network_delegate(&network_delegate);
3083 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363084 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553085 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193086 req->Start();
[email protected]255620da2013-08-19 13:14:293087 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163088
3089 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3090 }
3091}
3092
3093
[email protected]316c1e5e2012-09-12 15:17:443094// Check that it is impossible to change the referrer in the extra headers of
3095// an URLRequest.
3096TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3097 LocalHttpTestServer test_server;
3098 ASSERT_TRUE(test_server.Start());
3099
3100 // If extra headers contain referer and the request contains a referer,
3101 // only the latter shall be respected.
3102 {
3103 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363104 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553105 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193106 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443107
3108 HttpRequestHeaders headers;
3109 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193110 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443111
[email protected]f7022f32014-08-21 16:32:193112 req->Start();
[email protected]255620da2013-08-19 13:14:293113 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443114
3115 EXPECT_EQ("http://foo.com/", d.data_received());
3116 }
3117
3118 // If extra headers contain a referer but the request does not, no referer
3119 // shall be sent in the header.
3120 {
3121 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363122 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553123 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443124
3125 HttpRequestHeaders headers;
3126 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193127 req->SetExtraRequestHeaders(headers);
3128 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443129
[email protected]f7022f32014-08-21 16:32:193130 req->Start();
[email protected]255620da2013-08-19 13:14:293131 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443132
3133 EXPECT_EQ("None", d.data_received());
3134 }
3135}
3136
[email protected]b89290212009-08-14 22:37:353137class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113138 public:
mmenke9f2ec60c2015-06-01 20:59:473139 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113140
[email protected]b89290212009-08-14 22:37:353141 protected:
[email protected]21184962011-10-26 00:50:303142 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3143 // |request_method| is the method to use for the initial request.
3144 // |redirect_method| is the method that is expected to be used for the second
3145 // request, after redirection.
3146 // If |include_data| is true, data is uploaded with the request. The
3147 // response body is expected to match it exactly, if and only if
3148 // |request_method| == |redirect_method|.
3149 void HTTPRedirectMethodTest(const GURL& redirect_url,
3150 const std::string& request_method,
3151 const std::string& redirect_method,
3152 bool include_data) {
3153 static const char kData[] = "hello world";
3154 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363155 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363156 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193157 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303158 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073159 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303160 HttpRequestHeaders headers;
3161 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513162 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543163 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193164 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303165 }
[email protected]f7022f32014-08-21 16:32:193166 req->Start();
[email protected]255620da2013-08-19 13:14:293167 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193168 EXPECT_EQ(redirect_method, req->method());
3169 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3170 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303171 if (include_data) {
3172 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543173 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3174 HttpRequestHeaders::kContentLength));
3175 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3176 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303177 EXPECT_EQ(kData, d.data_received());
3178 } else {
svaldez5b3a8972015-10-09 23:23:543179 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3180 HttpRequestHeaders::kContentLength));
3181 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3182 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303183 EXPECT_NE(kData, d.data_received());
3184 }
3185 }
3186 if (HasFailure())
3187 LOG(WARNING) << "Request method was: " << request_method;
3188 }
3189
jww5fe460ff2015-03-28 00:22:513190 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3191 // |request_method| is the method to use for the initial request.
3192 // |redirect_method| is the method that is expected to be used for the second
3193 // request, after redirection.
3194 // |origin_value| is the expected value for the Origin header after
3195 // redirection. If empty, expects that there will be no Origin header.
3196 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3197 const std::string& request_method,
3198 const std::string& redirect_method,
3199 const std::string& origin_value) {
3200 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363201 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513202 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3203 req->set_method(request_method);
3204 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3205 redirect_url.GetOrigin().spec(), false);
3206 req->Start();
3207
3208 base::RunLoop().Run();
3209
3210 EXPECT_EQ(redirect_method, req->method());
3211 // Note that there is no check for request success here because, for
3212 // purposes of testing, the request very well may fail. For example, if the
3213 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3214 // origin, there is not an HTTPS server in this unit test framework, so the
3215 // request would fail. However, that's fine, as long as the request headers
3216 // are in order and pass the checks below.
3217 if (origin_value.empty()) {
3218 EXPECT_FALSE(
3219 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3220 } else {
3221 std::string origin_header;
3222 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3223 HttpRequestHeaders::kOrigin, &origin_header));
3224 EXPECT_EQ(origin_value, origin_header);
3225 }
3226 }
3227
[email protected]762d2db2010-01-11 19:03:013228 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013229 const int kMsgSize = 20000; // multiple of 10
3230 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483231 char* uploadBytes = new char[kMsgSize+1];
3232 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013233 char marker = 'a';
3234 for (int idx = 0; idx < kMsgSize/10; idx++) {
3235 memcpy(ptr, "----------", 10);
3236 ptr += 10;
3237 if (idx % 100 == 0) {
3238 ptr--;
3239 *ptr++ = marker;
3240 if (++marker > 'z')
3241 marker = 'a';
3242 }
3243 }
3244 uploadBytes[kMsgSize] = '\0';
3245
[email protected]762d2db2010-01-11 19:03:013246 for (int i = 0; i < kIterations; ++i) {
3247 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363248 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553249 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193250 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013251
mmenkecbc2b712014-10-09 20:29:073252 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013253
[email protected]f7022f32014-08-21 16:32:193254 r->Start();
3255 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013256
[email protected]255620da2013-08-19 13:14:293257 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013258
[email protected]329b68b2012-11-14 17:54:273259 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193260 << "request failed: " << r->status().status()
3261 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013262
3263 EXPECT_FALSE(d.received_data_before_response());
3264 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013265 }
3266 delete[] uploadBytes;
3267 }
3268
[email protected]ede03212012-09-07 12:52:263269 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343270 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363271 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553272 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363273 base::IntToString(num_cookies)),
3274 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343275
[email protected]f7022f32014-08-21 16:32:193276 r->Start();
3277 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343278
[email protected]255620da2013-08-19 13:14:293279 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343280
[email protected]f7022f32014-08-21 16:32:193281 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343282
tommycli59a63432015-11-06 00:10:553283 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193284 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343285
3286 return is_success;
3287 }
3288
tommycli59a63432015-11-06 00:10:553289 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503290
tommycli59a63432015-11-06 00:10:553291 private:
[email protected]1700c6a2012-02-22 18:07:073292 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353293};
3294
tommycli59a63432015-11-06 00:10:553295namespace {
3296
danakj8522a25b2016-04-16 00:17:363297std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553298 const test_server::HttpRequest& request) {
3299 if (request.headers.find("Host") == request.headers.end() ||
3300 request.headers.at("Host") != "www.redirect.com" ||
3301 request.method != test_server::METHOD_CONNECT) {
3302 return nullptr;
3303 }
3304
danakj8522a25b2016-04-16 00:17:363305 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553306 new test_server::BasicHttpResponse);
3307 http_response->set_code(HTTP_FOUND);
3308 http_response->AddCustomHeader("Location",
3309 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483310 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553311}
3312
3313} // namespace
3314
nharperb7441ef2016-01-25 23:54:143315class TestSSLConfigService : public SSLConfigService {
3316 public:
3317 TestSSLConfigService(bool ev_enabled,
3318 bool online_rev_checking,
3319 bool rev_checking_required_local_anchors,
3320 bool token_binding_enabled)
3321 : ev_enabled_(ev_enabled),
3322 online_rev_checking_(online_rev_checking),
3323 rev_checking_required_local_anchors_(
3324 rev_checking_required_local_anchors),
3325 token_binding_enabled_(token_binding_enabled),
3326 min_version_(kDefaultSSLVersionMin),
3327 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
3328
3329 void set_min_version(uint16_t version) { min_version_ = version; }
3330
3331 void set_fallback_min_version(uint16_t version) {
3332 fallback_min_version_ = version;
3333 }
3334
3335 // SSLConfigService:
3336 void GetSSLConfig(SSLConfig* config) override {
3337 *config = SSLConfig();
3338 config->rev_checking_enabled = online_rev_checking_;
3339 config->verify_ev_cert = ev_enabled_;
3340 config->rev_checking_required_local_anchors =
3341 rev_checking_required_local_anchors_;
3342 if (fallback_min_version_) {
3343 config->version_fallback_min = fallback_min_version_;
3344 }
3345 if (min_version_) {
3346 config->version_min = min_version_;
3347 }
3348 if (token_binding_enabled_) {
3349 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3350 }
3351 }
3352
3353 protected:
3354 ~TestSSLConfigService() override {}
3355
3356 private:
3357 const bool ev_enabled_;
3358 const bool online_rev_checking_;
3359 const bool rev_checking_required_local_anchors_;
3360 const bool token_binding_enabled_;
3361 uint16_t min_version_;
3362 uint16_t fallback_min_version_;
3363};
3364
3365// TODO(svaldez): Update tests to use EmbeddedTestServer.
3366#if !defined(OS_IOS)
3367class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3368 public:
3369 void SetUp() override {
3370 default_context_.set_ssl_config_service(
3371 new TestSSLConfigService(false, false, false, true));
3372 channel_id_service_.reset(new ChannelIDService(
3373 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3374 default_context_.set_channel_id_service(channel_id_service_.get());
3375 URLRequestTestHTTP::SetUp();
3376 }
3377
3378 protected:
danakj8522a25b2016-04-16 00:17:363379 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143380};
3381
3382TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3383 SpawnedTestServer::SSLOptions ssl_options;
3384 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3385 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3386 ssl_options,
3387 base::FilePath(kTestFilePath));
3388 ASSERT_TRUE(https_test_server.Start());
3389
3390 TestDelegate d;
3391 {
danakj8522a25b2016-04-16 00:17:363392 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143393 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3394 r->Start();
3395 EXPECT_TRUE(r->is_pending());
3396
3397 base::RunLoop().Run();
3398
3399 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3400
3401 HttpRequestHeaders headers;
3402 std::string token_binding_header, token_binding_message;
3403 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3404 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3405 &token_binding_header));
3406 EXPECT_TRUE(base::Base64UrlDecode(
3407 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3408 &token_binding_message));
nharperd6e65822016-03-30 23:05:483409 std::vector<TokenBinding> token_bindings;
3410 ASSERT_TRUE(
3411 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3412 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143413
3414 EXPECT_GT(d.bytes_received(), 0);
3415 std::string ekm = d.data_received();
3416
nharperd6e65822016-03-30 23:05:483417 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3418 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3419 token_bindings[0].signature, ekm));
nharperb7441ef2016-01-25 23:54:143420 }
3421}
nharperd6e65822016-03-30 23:05:483422
3423TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3424 SpawnedTestServer::SSLOptions ssl_options;
3425 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3426 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3427 ssl_options,
3428 base::FilePath(kTestFilePath));
3429 ASSERT_TRUE(https_test_server.Start());
3430
3431 TestDelegate d;
3432 {
3433 GURL redirect_url =
3434 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363435 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483436 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3437 r->Start();
3438 EXPECT_TRUE(r->is_pending());
3439
3440 base::RunLoop().Run();
3441
3442 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3443
3444 HttpRequestHeaders headers;
3445 std::string token_binding_header, token_binding_message;
3446 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3447 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3448 &token_binding_header));
3449 EXPECT_TRUE(base::Base64UrlDecode(
3450 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3451 &token_binding_message));
3452 std::vector<TokenBinding> token_bindings;
3453 ASSERT_TRUE(
3454 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3455 ASSERT_EQ(2ull, token_bindings.size());
3456
3457 EXPECT_GT(d.bytes_received(), 0);
3458 std::string ekm = d.data_received();
3459
3460 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3461 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3462 token_bindings[0].signature, ekm));
3463 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
3464 EXPECT_TRUE(VerifyEKMSignature(token_bindings[1].ec_point,
3465 token_bindings[1].signature, ekm));
3466 }
3467}
3468
3469// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3470// EmbeddedTestServer once crbug.com/599187 is resolved.
3471#if !defined(OS_ANDROID)
3472TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3473 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3474 SpawnedTestServer::kLocalhost,
3475 base::FilePath());
3476 ASSERT_TRUE(http_server.Start());
3477 SpawnedTestServer::SSLOptions ssl_options;
3478 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3479 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3480 ssl_options,
3481 base::FilePath(kTestFilePath));
3482 ASSERT_TRUE(https_test_server.Start());
3483
3484 TestDelegate d;
3485 {
3486 GURL redirect_url = http_server.GetURL(
3487 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363488 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483489 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3490 r->Start();
3491 EXPECT_TRUE(r->is_pending());
3492
3493 base::RunLoop().Run();
3494
3495 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3496
3497 HttpRequestHeaders headers;
3498 std::string token_binding_header, token_binding_message;
3499 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3500 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3501 &token_binding_header));
3502 EXPECT_TRUE(base::Base64UrlDecode(
3503 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3504 &token_binding_message));
3505 std::vector<TokenBinding> token_bindings;
3506 ASSERT_TRUE(
3507 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3508 ASSERT_EQ(1ull, token_bindings.size());
3509
3510 EXPECT_GT(d.bytes_received(), 0);
3511 std::string ekm = d.data_received();
3512
3513 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3514 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3515 token_bindings[0].signature, ekm));
3516 }
3517}
3518
3519// Test that if a server supporting Token Binding redirects (with
3520// Include-Referer-Token-Binding-ID) to an https url on a server that does not
3521// support Token Binding, then we do not send a Sec-Token-Binding when following
3522// the redirect.
3523TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3524 SpawnedTestServer::SSLOptions ssl_options;
3525 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3526 ssl_options,
3527 base::FilePath(kTestFilePath));
3528 ASSERT_TRUE(https_test_server.Start());
3529 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3530 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3531 ssl_options,
3532 base::FilePath(kTestFilePath));
3533 ASSERT_TRUE(token_binding_test_server.Start());
3534
3535 TestDelegate d;
3536 {
3537 GURL redirect_url = token_binding_test_server.GetURL(
3538 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363539 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483540 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3541 r->Start();
3542 EXPECT_TRUE(r->is_pending());
3543
3544 base::RunLoop().Run();
3545
3546 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3547
3548 HttpRequestHeaders headers;
3549 std::string token_binding_header, token_binding_message;
3550 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3551 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3552 &token_binding_header));
3553 }
3554}
3555#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143556#endif // !defined(OS_IOS)
3557
3558// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113559// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553560// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113561// follow.
[email protected]f2f31b32013-01-16 23:24:093562TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553563 http_test_server()->RegisterRequestHandler(
3564 base::Bind(&HandleRedirectConnect));
3565 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113566
[email protected]ceefd7fd2012-11-29 00:36:243567 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043568 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553569 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503570
[email protected]d1ec59082009-02-11 02:48:153571 TestDelegate d;
3572 {
danakj8522a25b2016-04-16 00:17:363573 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363574 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193575 r->Start();
3576 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153577
[email protected]255620da2013-08-19 13:14:293578 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153579
[email protected]f7022f32014-08-21 16:32:193580 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153581 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193582 EXPECT_TRUE(r->proxy_server().IsEmpty());
3583 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083584 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153585 // We should not have followed the redirect.
3586 EXPECT_EQ(0, d.received_redirect_count());
3587 }
3588}
3589
[email protected]8202d0c2011-02-23 08:31:143590// This is the same as the previous test, but checks that the network delegate
3591// registers the error.
[email protected]c044616e2013-02-20 02:01:263592TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553593 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143594
[email protected]ceefd7fd2012-11-29 00:36:243595 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043596 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553597 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503598
[email protected]8202d0c2011-02-23 08:31:143599 TestDelegate d;
3600 {
danakj8522a25b2016-04-16 00:17:363601 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363602 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193603 r->Start();
3604 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143605
[email protected]255620da2013-08-19 13:14:293606 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143607
[email protected]f7022f32014-08-21 16:32:193608 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153609 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193610 EXPECT_TRUE(r->proxy_server().IsEmpty());
3611 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143612 EXPECT_EQ(1, d.response_started_count());
3613 // We should not have followed the redirect.
3614 EXPECT_EQ(0, d.received_redirect_count());
3615
3616 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053617 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143618 }
3619}
3620
[email protected]dc5a5cf2012-09-26 02:49:303621// Tests that we can block and asynchronously return OK in various stages.
3622TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3623 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3624 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3625 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3626 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3627 };
3628 static const size_t blocking_stages_length = arraysize(blocking_stages);
3629
tommycli59a63432015-11-06 00:10:553630 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303631
3632 TestDelegate d;
3633 BlockingNetworkDelegate network_delegate(
3634 BlockingNetworkDelegate::USER_CALLBACK);
3635 network_delegate.set_block_on(
3636 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3637 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3638 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3639
3640 TestURLRequestContext context(true);
3641 context.set_network_delegate(&network_delegate);
3642 context.Init();
3643
3644 {
danakj8522a25b2016-04-16 00:17:363645 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553646 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303647
[email protected]f7022f32014-08-21 16:32:193648 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303649 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293650 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303651 EXPECT_EQ(blocking_stages[i],
3652 network_delegate.stage_blocked_for_callback());
3653 network_delegate.DoCallback(OK);
3654 }
[email protected]255620da2013-08-19 13:14:293655 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193656 EXPECT_EQ(200, r->GetResponseCode());
3657 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303658 EXPECT_EQ(1, network_delegate.created_requests());
3659 EXPECT_EQ(0, network_delegate.destroyed_requests());
3660 }
3661 EXPECT_EQ(1, network_delegate.destroyed_requests());
3662}
3663
[email protected]4c76d7c2011-04-15 19:14:123664// Tests that the network delegate can block and cancel a request.
3665TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553666 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123667
3668 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303669 BlockingNetworkDelegate network_delegate(
3670 BlockingNetworkDelegate::AUTO_CALLBACK);
3671 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3672 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123673
[email protected]d5a4dd62012-05-23 01:41:043674 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553675 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503676
[email protected]4c76d7c2011-04-15 19:14:123677 {
danakj8522a25b2016-04-16 00:17:363678 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553679 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123680
[email protected]f7022f32014-08-21 16:32:193681 r->Start();
[email protected]255620da2013-08-19 13:14:293682 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123683
[email protected]f7022f32014-08-21 16:32:193684 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153685 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193686 EXPECT_TRUE(r->proxy_server().IsEmpty());
3687 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123688 EXPECT_EQ(1, network_delegate.created_requests());
3689 EXPECT_EQ(0, network_delegate.destroyed_requests());
3690 }
3691 EXPECT_EQ(1, network_delegate.destroyed_requests());
3692}
3693
[email protected]b4438d32012-09-27 06:15:303694// Helper function for NetworkDelegateCancelRequestAsynchronously and
3695// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3696// delegate operating in |block_mode| and a request for |url|. It blocks the
3697// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3698void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3699 BlockingNetworkDelegate::Stage stage,
3700 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363701 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303702 BlockingNetworkDelegate network_delegate(block_mode);
3703 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3704 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363705
[email protected]b4438d32012-09-27 06:15:303706 TestURLRequestContext context(true);
3707 context.set_network_delegate(&network_delegate);
3708 context.Init();
[email protected]3cd384c602011-08-31 16:12:363709
3710 {
danakj8522a25b2016-04-16 00:17:363711 std::unique_ptr<URLRequest> r(
3712 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363713
[email protected]f7022f32014-08-21 16:32:193714 r->Start();
[email protected]255620da2013-08-19 13:14:293715 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363716
[email protected]f7022f32014-08-21 16:32:193717 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153718 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193719 EXPECT_TRUE(r->proxy_server().IsEmpty());
3720 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363721 EXPECT_EQ(1, network_delegate.created_requests());
3722 EXPECT_EQ(0, network_delegate.destroyed_requests());
3723 }
3724 EXPECT_EQ(1, network_delegate.destroyed_requests());
3725}
3726
[email protected]b4438d32012-09-27 06:15:303727// The following 3 tests check that the network delegate can cancel a request
3728// synchronously in various stages of the request.
3729TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553730 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303731 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3732 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553733 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303734}
3735
3736TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553737 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303738 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3739 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553740 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303741}
3742
3743TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553744 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303745 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3746 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553747 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303748}
3749
3750// The following 3 tests check that the network delegate can cancel a request
3751// asynchronously in various stages of the request.
3752TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553753 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303754 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3755 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553756 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303757}
3758
3759TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553760 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303761 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3762 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553763 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303764}
3765
3766TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553767 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303768 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3769 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553770 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303771}
3772
[email protected]4c76d7c2011-04-15 19:14:123773// Tests that the network delegate can block and redirect a request to a new
3774// URL.
3775TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553776 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123777
3778 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303779 BlockingNetworkDelegate network_delegate(
3780 BlockingNetworkDelegate::AUTO_CALLBACK);
3781 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553782 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123783 network_delegate.set_redirect_url(redirect_url);
3784
[email protected]d5a4dd62012-05-23 01:41:043785 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553786 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503787
[email protected]4c76d7c2011-04-15 19:14:123788 {
tommycli59a63432015-11-06 00:10:553789 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363790 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363791 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123792
[email protected]6be6fa92014-08-06 23:44:563793 // Quit after hitting the redirect, so can check the headers.
3794 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193795 r->Start();
[email protected]255620da2013-08-19 13:14:293796 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123797
[email protected]6be6fa92014-08-06 23:44:563798 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193799 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3800 EXPECT_EQ(307, r->GetResponseCode());
3801 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563802 std::string location;
[email protected]f7022f32014-08-21 16:32:193803 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3804 &location));
[email protected]6be6fa92014-08-06 23:44:563805 EXPECT_EQ(redirect_url, GURL(location));
3806
3807 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193808 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563809 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193810 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553811 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093812 // before_send_headers_with_proxy_count only increments for headers sent
3813 // through an untunneled proxy.
3814 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553815 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3816 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273817
[email protected]f7022f32014-08-21 16:32:193818 EXPECT_EQ(0, r->status().error());
3819 EXPECT_EQ(redirect_url, r->url());
3820 EXPECT_EQ(original_url, r->original_url());
3821 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123822 EXPECT_EQ(1, network_delegate.created_requests());
3823 EXPECT_EQ(0, network_delegate.destroyed_requests());
3824 }
3825 EXPECT_EQ(1, network_delegate.destroyed_requests());
3826}
3827
[email protected]b813ed72012-04-05 08:21:363828// Tests that the network delegate can block and redirect a request to a new
3829// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3830TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553831 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363832
3833 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303834 BlockingNetworkDelegate network_delegate(
3835 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553836 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363837 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363838
[email protected]d5a4dd62012-05-23 01:41:043839 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553840 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363841
3842 {
tommycli59a63432015-11-06 00:10:553843 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363844 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363845 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363846
[email protected]6be6fa92014-08-06 23:44:563847 // Quit after hitting the redirect, so can check the headers.
3848 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193849 r->Start();
[email protected]255620da2013-08-19 13:14:293850 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363851
[email protected]6be6fa92014-08-06 23:44:563852 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193853 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3854 EXPECT_EQ(307, r->GetResponseCode());
3855 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563856 std::string location;
[email protected]f7022f32014-08-21 16:32:193857 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3858 &location));
[email protected]6be6fa92014-08-06 23:44:563859 EXPECT_EQ(redirect_url, GURL(location));
3860
3861 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193862 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563863 base::RunLoop().Run();
3864
[email protected]f7022f32014-08-21 16:32:193865 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553866 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093867 // before_send_headers_with_proxy_count only increments for headers sent
3868 // through an untunneled proxy.
3869 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553870 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3871 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193872 EXPECT_EQ(0, r->status().error());
3873 EXPECT_EQ(redirect_url, r->url());
3874 EXPECT_EQ(original_url, r->original_url());
3875 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363876 EXPECT_EQ(1, network_delegate.created_requests());
3877 EXPECT_EQ(0, network_delegate.destroyed_requests());
3878 }
3879 EXPECT_EQ(1, network_delegate.destroyed_requests());
3880}
3881
[email protected]3c5ca8c2011-09-29 01:14:513882// Tests that redirects caused by the network delegate preserve POST data.
3883TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553884 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513885
3886 const char kData[] = "hello world";
3887
3888 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303889 BlockingNetworkDelegate network_delegate(
3890 BlockingNetworkDelegate::AUTO_CALLBACK);
3891 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553892 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513893 network_delegate.set_redirect_url(redirect_url);
3894
[email protected]ef2bf422012-05-11 03:27:093895 TestURLRequestContext context(true);
3896 context.set_network_delegate(&network_delegate);
3897 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513898
3899 {
tommycli59a63432015-11-06 00:10:553900 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363901 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363902 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193903 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073904 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513905 HttpRequestHeaders headers;
3906 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513907 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193908 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563909
3910 // Quit after hitting the redirect, so can check the headers.
3911 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193912 r->Start();
[email protected]255620da2013-08-19 13:14:293913 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513914
[email protected]6be6fa92014-08-06 23:44:563915 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193916 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3917 EXPECT_EQ(307, r->GetResponseCode());
3918 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563919 std::string location;
[email protected]f7022f32014-08-21 16:32:193920 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3921 &location));
[email protected]6be6fa92014-08-06 23:44:563922 EXPECT_EQ(redirect_url, GURL(location));
3923
3924 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193925 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563926 base::RunLoop().Run();
3927
[email protected]f7022f32014-08-21 16:32:193928 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3929 EXPECT_EQ(0, r->status().error());
3930 EXPECT_EQ(redirect_url, r->url());
3931 EXPECT_EQ(original_url, r->original_url());
3932 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513933 EXPECT_EQ(1, network_delegate.created_requests());
3934 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193935 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513936 EXPECT_EQ(kData, d.data_received());
3937 }
3938 EXPECT_EQ(1, network_delegate.destroyed_requests());
3939}
3940
[email protected]5f714132014-03-26 10:41:163941// Tests that the network delegate can block and redirect a request to a new
3942// URL during OnHeadersReceived.
3943TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553944 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163945
3946 TestDelegate d;
3947 BlockingNetworkDelegate network_delegate(
3948 BlockingNetworkDelegate::AUTO_CALLBACK);
3949 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553950 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163951 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3952
3953 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553954 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163955
3956 {
tommycli59a63432015-11-06 00:10:553957 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363958 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363959 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163960
[email protected]f7022f32014-08-21 16:32:193961 r->Start();
[email protected]5f714132014-03-26 10:41:163962 base::RunLoop().Run();
3963
[email protected]f7022f32014-08-21 16:32:193964 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553965 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093966 // before_send_headers_with_proxy_count only increments for headers sent
3967 // through an untunneled proxy.
3968 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553969 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3970 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193971
3972 EXPECT_EQ(OK, r->status().error());
3973 EXPECT_EQ(redirect_url, r->url());
3974 EXPECT_EQ(original_url, r->original_url());
3975 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163976 EXPECT_EQ(2, network_delegate.created_requests());
3977 EXPECT_EQ(0, network_delegate.destroyed_requests());
3978 }
3979 EXPECT_EQ(1, network_delegate.destroyed_requests());
3980}
3981
[email protected]c2911d72011-10-03 22:16:363982// Tests that the network delegate can synchronously complete OnAuthRequired
3983// by taking no action. This indicates that the NetworkDelegate does not want to
3984// handle the challenge, and is passing the buck along to the
3985// URLRequest::Delegate.
3986TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:553987 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:363988
3989 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303990 BlockingNetworkDelegate network_delegate(
3991 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363992
[email protected]ef2bf422012-05-11 03:27:093993 TestURLRequestContext context(true);
3994 context.set_network_delegate(&network_delegate);
3995 context.Init();
[email protected]c2911d72011-10-03 22:16:363996
[email protected]f3cf9802011-10-28 18:44:583997 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363998
3999 {
tommycli59a63432015-11-06 00:10:554000 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364001 std::unique_ptr<URLRequest> r(
4002 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194003 r->Start();
[email protected]79e1fd62013-06-20 06:50:044004
[email protected]255620da2013-08-19 13:14:294005 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044006
[email protected]f7022f32014-08-21 16:32:194007 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4008 EXPECT_EQ(0, r->status().error());
4009 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044010 EXPECT_TRUE(d.auth_required_called());
4011 EXPECT_EQ(1, network_delegate.created_requests());
4012 EXPECT_EQ(0, network_delegate.destroyed_requests());
4013 }
4014 EXPECT_EQ(1, network_delegate.destroyed_requests());
4015}
4016
4017TEST_F(URLRequestTestHTTP,
4018 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554019 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044020
4021 TestDelegate d;
4022 BlockingNetworkDelegate network_delegate(
4023 BlockingNetworkDelegate::SYNCHRONOUS);
4024
4025 TestURLRequestContext context(true);
4026 context.set_network_delegate(&network_delegate);
4027 context.Init();
4028
4029 d.set_credentials(AuthCredentials(kUser, kSecret));
4030
4031 {
tommycli59a63432015-11-06 00:10:554032 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364033 std::unique_ptr<URLRequest> r(
4034 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194035 r->Start();
[email protected]79e1fd62013-06-20 06:50:044036
4037 {
4038 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194039 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044040 EXPECT_FALSE(headers.HasHeader("Authorization"));
4041 }
4042
[email protected]255620da2013-08-19 13:14:294043 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364044
[email protected]f7022f32014-08-21 16:32:194045 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4046 EXPECT_EQ(0, r->status().error());
4047 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364048 EXPECT_TRUE(d.auth_required_called());
4049 EXPECT_EQ(1, network_delegate.created_requests());
4050 EXPECT_EQ(0, network_delegate.destroyed_requests());
4051 }
4052 EXPECT_EQ(1, network_delegate.destroyed_requests());
4053}
4054
4055// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404056// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364057TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554058 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364059
4060 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304061 BlockingNetworkDelegate network_delegate(
4062 BlockingNetworkDelegate::SYNCHRONOUS);
4063 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364064 network_delegate.set_auth_retval(
4065 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4066
[email protected]f3cf9802011-10-28 18:44:584067 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364068
[email protected]ef2bf422012-05-11 03:27:094069 TestURLRequestContext context(true);
4070 context.set_network_delegate(&network_delegate);
4071 context.Init();
[email protected]c2911d72011-10-03 22:16:364072
4073 {
tommycli59a63432015-11-06 00:10:554074 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364075 std::unique_ptr<URLRequest> r(
4076 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194077 r->Start();
[email protected]255620da2013-08-19 13:14:294078 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364079
[email protected]f7022f32014-08-21 16:32:194080 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4081 EXPECT_EQ(0, r->status().error());
4082 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364083 EXPECT_FALSE(d.auth_required_called());
4084 EXPECT_EQ(1, network_delegate.created_requests());
4085 EXPECT_EQ(0, network_delegate.destroyed_requests());
4086 }
4087 EXPECT_EQ(1, network_delegate.destroyed_requests());
4088}
4089
[email protected]79e1fd62013-06-20 06:50:044090// Same as above, but also tests that GetFullRequestHeaders returns the proper
4091// headers (for the first or second request) when called at the proper times.
4092TEST_F(URLRequestTestHTTP,
4093 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554094 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044095
4096 TestDelegate d;
4097 BlockingNetworkDelegate network_delegate(
4098 BlockingNetworkDelegate::SYNCHRONOUS);
4099 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4100 network_delegate.set_auth_retval(
4101 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4102
4103 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4104
4105 TestURLRequestContext context(true);
4106 context.set_network_delegate(&network_delegate);
4107 context.Init();
4108
4109 {
tommycli59a63432015-11-06 00:10:554110 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364111 std::unique_ptr<URLRequest> r(
4112 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194113 r->Start();
[email protected]255620da2013-08-19 13:14:294114 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044115
[email protected]f7022f32014-08-21 16:32:194116 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4117 EXPECT_EQ(0, r->status().error());
4118 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044119 EXPECT_FALSE(d.auth_required_called());
4120 EXPECT_EQ(1, network_delegate.created_requests());
4121 EXPECT_EQ(0, network_delegate.destroyed_requests());
4122
4123 {
4124 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194125 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044126 EXPECT_TRUE(headers.HasHeader("Authorization"));
4127 }
4128 }
4129 EXPECT_EQ(1, network_delegate.destroyed_requests());
4130}
4131
[email protected]c2911d72011-10-03 22:16:364132// Tests that the network delegate can synchronously complete OnAuthRequired
4133// by cancelling authentication.
4134TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554135 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364136
4137 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304138 BlockingNetworkDelegate network_delegate(
4139 BlockingNetworkDelegate::SYNCHRONOUS);
4140 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364141 network_delegate.set_auth_retval(
4142 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4143
[email protected]ef2bf422012-05-11 03:27:094144 TestURLRequestContext context(true);
4145 context.set_network_delegate(&network_delegate);
4146 context.Init();
[email protected]c2911d72011-10-03 22:16:364147
4148 {
tommycli59a63432015-11-06 00:10:554149 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364150 std::unique_ptr<URLRequest> r(
4151 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194152 r->Start();
[email protected]255620da2013-08-19 13:14:294153 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364154
[email protected]f7022f32014-08-21 16:32:194155 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4156 EXPECT_EQ(OK, r->status().error());
4157 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364158 EXPECT_FALSE(d.auth_required_called());
4159 EXPECT_EQ(1, network_delegate.created_requests());
4160 EXPECT_EQ(0, network_delegate.destroyed_requests());
4161 }
4162 EXPECT_EQ(1, network_delegate.destroyed_requests());
4163}
4164
4165// Tests that the network delegate can asynchronously complete OnAuthRequired
4166// by taking no action. This indicates that the NetworkDelegate does not want
4167// to handle the challenge, and is passing the buck along to the
4168// URLRequest::Delegate.
4169TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554170 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364171
4172 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304173 BlockingNetworkDelegate network_delegate(
4174 BlockingNetworkDelegate::AUTO_CALLBACK);
4175 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364176
[email protected]ef2bf422012-05-11 03:27:094177 TestURLRequestContext context(true);
4178 context.set_network_delegate(&network_delegate);
4179 context.Init();
[email protected]c2911d72011-10-03 22:16:364180
[email protected]f3cf9802011-10-28 18:44:584181 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364182
4183 {
tommycli59a63432015-11-06 00:10:554184 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364185 std::unique_ptr<URLRequest> r(
4186 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194187 r->Start();
[email protected]255620da2013-08-19 13:14:294188 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364189
[email protected]f7022f32014-08-21 16:32:194190 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4191 EXPECT_EQ(0, r->status().error());
4192 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364193 EXPECT_TRUE(d.auth_required_called());
4194 EXPECT_EQ(1, network_delegate.created_requests());
4195 EXPECT_EQ(0, network_delegate.destroyed_requests());
4196 }
4197 EXPECT_EQ(1, network_delegate.destroyed_requests());
4198}
4199
4200// Tests that the network delegate can asynchronously complete OnAuthRequired
4201// by setting credentials.
4202TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554203 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364204
4205 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304206 BlockingNetworkDelegate network_delegate(
4207 BlockingNetworkDelegate::AUTO_CALLBACK);
4208 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364209 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364210 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4211
[email protected]f3cf9802011-10-28 18:44:584212 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364213 network_delegate.set_auth_credentials(auth_credentials);
4214
[email protected]ef2bf422012-05-11 03:27:094215 TestURLRequestContext context(true);
4216 context.set_network_delegate(&network_delegate);
4217 context.Init();
[email protected]c2911d72011-10-03 22:16:364218
4219 {
tommycli59a63432015-11-06 00:10:554220 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364221 std::unique_ptr<URLRequest> r(
4222 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194223 r->Start();
[email protected]255620da2013-08-19 13:14:294224 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364225
[email protected]f7022f32014-08-21 16:32:194226 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4227 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:364228
[email protected]f7022f32014-08-21 16:32:194229 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364230 EXPECT_FALSE(d.auth_required_called());
4231 EXPECT_EQ(1, network_delegate.created_requests());
4232 EXPECT_EQ(0, network_delegate.destroyed_requests());
4233 }
4234 EXPECT_EQ(1, network_delegate.destroyed_requests());
4235}
4236
4237// Tests that the network delegate can asynchronously complete OnAuthRequired
4238// by cancelling authentication.
4239TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554240 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364241
4242 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304243 BlockingNetworkDelegate network_delegate(
4244 BlockingNetworkDelegate::AUTO_CALLBACK);
4245 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364246 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364247 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4248
[email protected]ef2bf422012-05-11 03:27:094249 TestURLRequestContext context(true);
4250 context.set_network_delegate(&network_delegate);
4251 context.Init();
[email protected]c2911d72011-10-03 22:16:364252
4253 {
tommycli59a63432015-11-06 00:10:554254 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364255 std::unique_ptr<URLRequest> r(
4256 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194257 r->Start();
[email protected]255620da2013-08-19 13:14:294258 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364259
[email protected]f7022f32014-08-21 16:32:194260 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4261 EXPECT_EQ(OK, r->status().error());
4262 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364263 EXPECT_FALSE(d.auth_required_called());
4264 EXPECT_EQ(1, network_delegate.created_requests());
4265 EXPECT_EQ(0, network_delegate.destroyed_requests());
4266 }
4267 EXPECT_EQ(1, network_delegate.destroyed_requests());
4268}
4269
[email protected]9045b8822012-01-13 20:35:354270// Tests that we can handle when a network request was canceled while we were
4271// waiting for the network delegate.
4272// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4273TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554274 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354275
4276 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304277 BlockingNetworkDelegate network_delegate(
4278 BlockingNetworkDelegate::USER_CALLBACK);
4279 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354280
[email protected]ef2bf422012-05-11 03:27:094281 TestURLRequestContext context(true);
4282 context.set_network_delegate(&network_delegate);
4283 context.Init();
[email protected]9045b8822012-01-13 20:35:354284
4285 {
danakj8522a25b2016-04-16 00:17:364286 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554287 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354288
[email protected]f7022f32014-08-21 16:32:194289 r->Start();
[email protected]255620da2013-08-19 13:14:294290 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304291 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4292 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354293 EXPECT_EQ(0, network_delegate.completed_requests());
4294 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194295 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354296 // Ensure that network delegate is notified.
4297 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194298 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4299 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354300 EXPECT_EQ(1, network_delegate.created_requests());
4301 EXPECT_EQ(0, network_delegate.destroyed_requests());
4302 }
4303 EXPECT_EQ(1, network_delegate.destroyed_requests());
4304}
4305
4306// Tests that we can handle when a network request was canceled while we were
4307// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004308// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4309// callback.
[email protected]9045b8822012-01-13 20:35:354310TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554311 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354312
4313 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304314 BlockingNetworkDelegate network_delegate(
4315 BlockingNetworkDelegate::USER_CALLBACK);
4316 network_delegate.set_block_on(
4317 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354318
[email protected]ef2bf422012-05-11 03:27:094319 TestURLRequestContext context(true);
4320 context.set_network_delegate(&network_delegate);
4321 context.Init();
[email protected]9045b8822012-01-13 20:35:354322
4323 {
danakj8522a25b2016-04-16 00:17:364324 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554325 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354326
[email protected]f7022f32014-08-21 16:32:194327 r->Start();
[email protected]255620da2013-08-19 13:14:294328 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304329 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4330 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354331 EXPECT_EQ(0, network_delegate.completed_requests());
4332 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194333 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354334 // Ensure that network delegate is notified.
4335 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194336 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4337 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354338 EXPECT_EQ(1, network_delegate.created_requests());
4339 EXPECT_EQ(0, network_delegate.destroyed_requests());
4340 }
4341 EXPECT_EQ(1, network_delegate.destroyed_requests());
4342}
4343
4344// Tests that we can handle when a network request was canceled while we were
4345// waiting for the network delegate.
4346// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4347TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554348 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354349
4350 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304351 BlockingNetworkDelegate network_delegate(
4352 BlockingNetworkDelegate::USER_CALLBACK);
4353 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354354
[email protected]ef2bf422012-05-11 03:27:094355 TestURLRequestContext context(true);
4356 context.set_network_delegate(&network_delegate);
4357 context.Init();
[email protected]9045b8822012-01-13 20:35:354358
4359 {
danakj8522a25b2016-04-16 00:17:364360 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554361 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354362
[email protected]f7022f32014-08-21 16:32:194363 r->Start();
[email protected]255620da2013-08-19 13:14:294364 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304365 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4366 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354367 EXPECT_EQ(0, network_delegate.completed_requests());
4368 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194369 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354370 // Ensure that network delegate is notified.
4371 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194372 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4373 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354374 EXPECT_EQ(1, network_delegate.created_requests());
4375 EXPECT_EQ(0, network_delegate.destroyed_requests());
4376 }
4377 EXPECT_EQ(1, network_delegate.destroyed_requests());
4378}
4379
4380// Tests that we can handle when a network request was canceled while we were
4381// waiting for the network delegate.
4382// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024383TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554384 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354385
4386 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304387 BlockingNetworkDelegate network_delegate(
4388 BlockingNetworkDelegate::USER_CALLBACK);
4389 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354390
[email protected]ef2bf422012-05-11 03:27:094391 TestURLRequestContext context(true);
4392 context.set_network_delegate(&network_delegate);
4393 context.Init();
[email protected]9045b8822012-01-13 20:35:354394
4395 {
danakj8522a25b2016-04-16 00:17:364396 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554397 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354398
[email protected]f7022f32014-08-21 16:32:194399 r->Start();
[email protected]255620da2013-08-19 13:14:294400 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304401 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4402 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354403 EXPECT_EQ(0, network_delegate.completed_requests());
4404 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194405 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354406 // Ensure that network delegate is notified.
4407 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194408 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4409 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354410 EXPECT_EQ(1, network_delegate.created_requests());
4411 EXPECT_EQ(0, network_delegate.destroyed_requests());
4412 }
4413 EXPECT_EQ(1, network_delegate.destroyed_requests());
4414}
4415
tommycli59a63432015-11-06 00:10:554416namespace {
4417
danakj8522a25b2016-04-16 00:17:364418std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554419 const test_server::HttpRequest& request) {
4420 if (request.headers.find("Host") == request.headers.end() ||
4421 request.headers.at("Host") != "www.server-auth.com" ||
4422 request.method != test_server::METHOD_CONNECT) {
4423 return nullptr;
4424 }
4425
danakj8522a25b2016-04-16 00:17:364426 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554427 new test_server::BasicHttpResponse);
4428 http_response->set_code(HTTP_UNAUTHORIZED);
4429 http_response->AddCustomHeader("WWW-Authenticate",
4430 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484431 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554432}
4433
4434} // namespace
4435
4436// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114437// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554438// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354439TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554440 http_test_server()->RegisterRequestHandler(
4441 base::Bind(&HandleServerAuthConnect));
4442 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114443
[email protected]ceefd7fd2012-11-29 00:36:244444 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044445 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554446 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504447
[email protected]dc651782009-02-14 01:45:084448 TestDelegate d;
4449 {
danakj8522a25b2016-04-16 00:17:364450 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364451 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084452
[email protected]f7022f32014-08-21 16:32:194453 r->Start();
4454 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084455
[email protected]255620da2013-08-19 13:14:294456 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084457
[email protected]f7022f32014-08-21 16:32:194458 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154459 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194460 EXPECT_TRUE(r->proxy_server().IsEmpty());
4461 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084462 }
4463}
4464
[email protected]b89290212009-08-14 22:37:354465TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554466 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114467
initial.commit586acc5fe2008-07-26 22:42:524468 TestDelegate d;
4469 {
danakj8522a25b2016-04-16 00:17:364470 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554471 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524472
[email protected]f7022f32014-08-21 16:32:194473 r->Start();
4474 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524475
[email protected]255620da2013-08-19 13:14:294476 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524477
4478 EXPECT_EQ(1, d.response_started_count());
4479 EXPECT_FALSE(d.received_data_before_response());
4480 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554481 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194482 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554483 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194484 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164485
[email protected]9e743cd2010-03-16 07:03:534486 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524487 }
initial.commit586acc5fe2008-07-26 22:42:524488}
4489
[email protected]263163f2012-06-14 22:40:344490// This test has the server send a large number of cookies to the client.
4491// To ensure that no number of cookies causes a crash, a galloping binary
4492// search is used to estimate that maximum number of cookies that are accepted
4493// by the browser. Beyond the maximum number, the request will fail with
4494// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304495#if defined(OS_WIN)
4496// http://crbug.com/177916
4497#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4498#else
4499#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4500#endif // defined(OS_WIN)
4501TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554502 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344503
4504 int lower_bound = 0;
4505 int upper_bound = 1;
4506
4507 // Double the number of cookies until the response header limits are
4508 // exceeded.
4509 while (DoManyCookiesRequest(upper_bound)) {
4510 lower_bound = upper_bound;
4511 upper_bound *= 2;
4512 ASSERT_LT(upper_bound, 1000000);
4513 }
4514
pkasting6b68a162014-12-01 22:10:294515 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344516 if (tolerance < 2)
4517 tolerance = 2;
4518
4519 // Perform a binary search to find the highest possible number of cookies,
4520 // within the desired tolerance.
4521 while (upper_bound - lower_bound >= tolerance) {
4522 int num_cookies = (lower_bound + upper_bound) / 2;
4523
4524 if (DoManyCookiesRequest(num_cookies))
4525 lower_bound = num_cookies;
4526 else
4527 upper_bound = num_cookies;
4528 }
4529 // Success: the test did not crash.
4530}
4531
[email protected]b89290212009-08-14 22:37:354532TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554533 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114534
initial.commit586acc5fe2008-07-26 22:42:524535 TestDelegate d;
4536 {
danakj8522a25b2016-04-16 00:17:364537 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554538 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524539
[email protected]f7022f32014-08-21 16:32:194540 r->Start();
4541 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524542
[email protected]255620da2013-08-19 13:14:294543 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524544
4545 EXPECT_EQ(1, d.response_started_count());
4546 EXPECT_FALSE(d.received_data_before_response());
4547 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554548 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194549 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554550 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194551 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524552 }
[email protected]5d7b373e2009-09-02 07:19:034553}
4554
[email protected]79e1fd62013-06-20 06:50:044555TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554556 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044557
4558 TestDelegate d;
4559 {
tommycli59a63432015-11-06 00:10:554560 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364561 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364562 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044563
4564 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194565 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044566
[email protected]f7022f32014-08-21 16:32:194567 r->Start();
4568 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044569
[email protected]255620da2013-08-19 13:14:294570 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044571
4572 EXPECT_EQ(1, d.response_started_count());
4573 EXPECT_FALSE(d.received_data_before_response());
4574 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554575 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194576 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554577 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194578 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044579
4580 EXPECT_TRUE(d.have_full_request_headers());
4581 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4582 }
4583}
4584
[email protected]58e32bb2013-01-21 18:23:254585TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554586 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254587
4588 TestDelegate d;
4589 {
danakj8522a25b2016-04-16 00:17:364590 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554591 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254592
[email protected]f7022f32014-08-21 16:32:194593 r->Start();
4594 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254595
[email protected]255620da2013-08-19 13:14:294596 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254597
4598 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194599 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254600 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4601
4602 EXPECT_EQ(1, d.response_started_count());
4603 EXPECT_FALSE(d.received_data_before_response());
4604 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554605 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194606 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554607 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194608 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254609 }
4610}
4611
tommycli59a63432015-11-06 00:10:554612// TODO(svaldez): Update tests to use EmbeddedTestServer.
4613#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394614TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554615 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4616 SpawnedTestServer::kLocalhost,
4617 base::FilePath(kTestFilePath));
4618
4619 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394620
4621 // Parameter that specifies the Content-Length field in the response:
4622 // C - Compressed length.
4623 // U - Uncompressed length.
4624 // L - Large length (larger than both C & U).
4625 // M - Medium length (between C & U).
4626 // S - Small length (smaller than both C & U).
4627 const char test_parameters[] = "CULMS";
4628 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4629 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444630 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394631 // S has too little data, but we seem to accept it.
4632 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374633 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394634
4635 for (int i = 0; i < num_tests ; i++) {
4636 TestDelegate d;
4637 {
tommycli59a63432015-11-06 00:10:554638 std::string test_file = base::StringPrintf(
4639 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394640
[email protected]ceefd7fd2012-11-29 00:36:244641 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094642 TestURLRequestContext context(true);
4643 context.set_network_delegate(&network_delegate);
4644 context.Init();
[email protected]87a09a92011-07-14 15:50:504645
danakj8522a25b2016-04-16 00:17:364646 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554647 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194648 r->Start();
4649 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394650
[email protected]255620da2013-08-19 13:14:294651 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394652
4653 EXPECT_EQ(1, d.response_started_count());
4654 EXPECT_FALSE(d.received_data_before_response());
4655 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194656 << " status = " << r->status().status()
4657 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394658 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194659 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394660 << " Parameter = \"" << test_file << "\"";
4661 } else {
[email protected]f7022f32014-08-21 16:32:194662 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4663 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394664 << " Parameter = \"" << test_file << "\"";
4665 }
4666 }
4667 }
4668}
tommycli59a63432015-11-06 00:10:554669#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394670
[email protected]58e32bb2013-01-21 18:23:254671TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554672 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254673
tommycli59a63432015-11-06 00:10:554674 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454675 GURL original_url =
tommycli59a63432015-11-06 00:10:554676 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254677 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364678 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364679 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194680 req->Start();
[email protected]255620da2013-08-19 13:14:294681 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254682
4683 EXPECT_EQ(1, d.response_started_count());
4684 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194685 EXPECT_EQ(destination_url, req->url());
4686 EXPECT_EQ(original_url, req->original_url());
4687 ASSERT_EQ(2U, req->url_chain().size());
4688 EXPECT_EQ(original_url, req->url_chain()[0]);
4689 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254690
4691 LoadTimingInfo load_timing_info_before_redirect;
4692 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4693 &load_timing_info_before_redirect));
4694 TestLoadTimingNotReused(load_timing_info_before_redirect,
4695 CONNECT_TIMING_HAS_DNS_TIMES);
4696
4697 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194698 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254699 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4700
4701 // Check that a new socket was used on redirect, since the server does not
4702 // supposed keep-alive sockets, and that the times before the redirect are
4703 // before the ones recorded for the second request.
4704 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4705 load_timing_info.socket_log_id);
4706 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4707 load_timing_info.connect_timing.connect_start);
4708}
4709
[email protected]8f1ac082011-04-19 21:14:134710TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554711 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134712
tommycli59a63432015-11-06 00:10:554713 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454714 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554715 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4716 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4717 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134718 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364719 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364720 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194721 req->Start();
[email protected]255620da2013-08-19 13:14:294722 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134723
4724 EXPECT_EQ(1, d.response_started_count());
4725 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194726 EXPECT_EQ(destination_url, req->url());
4727 EXPECT_EQ(original_url, req->original_url());
4728 ASSERT_EQ(3U, req->url_chain().size());
4729 EXPECT_EQ(original_url, req->url_chain()[0]);
4730 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4731 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134732}
4733
[email protected]abe1c4a2013-10-25 19:28:514734// First and second pieces of information logged by delegates to URLRequests.
4735const char kFirstDelegateInfo[] = "Wonderful delegate";
4736const char kSecondDelegateInfo[] = "Exciting delegate";
4737
4738// Logs delegate information to a URLRequest. The first string is logged
4739// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4740// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4741// another asynchronous call is used to clear the delegate information
4742// before calling a callback. The object then deletes itself.
4743class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4744 public:
4745 typedef base::Callback<void()> Callback;
4746
4747 // Each time delegate information is added to the URLRequest, the resulting
4748 // load state is checked. The expected load state after each request is
4749 // passed in as an argument.
4750 static void Run(URLRequest* url_request,
4751 LoadState expected_first_load_state,
4752 LoadState expected_second_load_state,
4753 LoadState expected_third_load_state,
4754 const Callback& callback) {
4755 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4756 url_request,
4757 expected_first_load_state,
4758 expected_second_load_state,
4759 expected_third_load_state,
4760 callback);
4761 logger->Start();
4762 }
4763
4764 // Checks that the log entries, starting with log_position, contain the
4765 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4766 // recorded. Returns the index of entry after the expected number of
4767 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464768 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514769 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514770 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4771 if (log_position + 3 >= entries.size()) {
4772 ADD_FAILURE() << "Not enough log entries";
4773 return entries.size();
4774 }
4775 std::string delegate_info;
4776 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4777 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4778 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4779 &delegate_info));
4780 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4781
4782 ++log_position;
4783 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4784 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4785
4786 ++log_position;
4787 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4788 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4789 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4790 &delegate_info));
4791 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4792
4793 ++log_position;
4794 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4795 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4796
4797 return log_position + 1;
4798 }
4799
[email protected]1826a402014-01-08 15:40:484800 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4801 // Returns the position of the end message.
mmenke43758e62015-05-04 21:09:464802 static size_t ExpectBeforeNetworkEvents(const TestNetLogEntry::List& entries,
4803 size_t log_position) {
[email protected]1826a402014-01-08 15:40:484804 log_position =
4805 ExpectLogContainsSomewhereAfter(entries,
4806 log_position,
4807 NetLog::TYPE_URL_REQUEST_DELEGATE,
4808 NetLog::PHASE_BEGIN);
4809 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4810 entries[log_position + 1].type);
4811 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4812 return log_position + 1;
4813 }
4814
[email protected]abe1c4a2013-10-25 19:28:514815 private:
4816 friend class base::RefCounted<AsyncDelegateLogger>;
4817
4818 AsyncDelegateLogger(URLRequest* url_request,
4819 LoadState expected_first_load_state,
4820 LoadState expected_second_load_state,
4821 LoadState expected_third_load_state,
4822 const Callback& callback)
4823 : url_request_(url_request),
4824 expected_first_load_state_(expected_first_load_state),
4825 expected_second_load_state_(expected_second_load_state),
4826 expected_third_load_state_(expected_third_load_state),
4827 callback_(callback) {
4828 }
4829
4830 ~AsyncDelegateLogger() {}
4831
4832 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534833 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514834 LoadStateWithParam load_state = url_request_->GetLoadState();
4835 EXPECT_EQ(expected_first_load_state_, load_state.state);
4836 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454837 base::ThreadTaskRunnerHandle::Get()->PostTask(
4838 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514839 }
4840
4841 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534842 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514843 LoadStateWithParam load_state = url_request_->GetLoadState();
4844 EXPECT_EQ(expected_second_load_state_, load_state.state);
4845 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4846 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4847 } else {
4848 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4849 }
skyostil4891b25b2015-06-11 11:43:454850 base::ThreadTaskRunnerHandle::Get()->PostTask(
4851 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514852 }
4853
4854 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534855 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514856 LoadStateWithParam load_state = url_request_->GetLoadState();
4857 EXPECT_EQ(expected_third_load_state_, load_state.state);
4858 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084859 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514860 callback_.Run();
4861 }
4862
4863 URLRequest* url_request_;
4864 const int expected_first_load_state_;
4865 const int expected_second_load_state_;
4866 const int expected_third_load_state_;
4867 const Callback callback_;
4868
4869 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4870};
4871
4872// NetworkDelegate that logs delegate information before a request is started,
4873// before headers are sent, when headers are read, and when auth information
4874// is requested. Uses AsyncDelegateLogger.
4875class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4876 public:
4877 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204878 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514879
4880 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204881 int OnBeforeURLRequest(URLRequest* request,
4882 const CompletionCallback& callback,
4883 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514884 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4885 return RunCallbackAsynchronously(request, callback);
4886 }
4887
ryansturm2343cb62016-06-15 01:09:004888 int OnBeforeStartTransaction(URLRequest* request,
4889 const CompletionCallback& callback,
4890 HttpRequestHeaders* headers) override {
4891 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514892 return RunCallbackAsynchronously(request, callback);
4893 }
4894
dchengb03027d2014-10-21 12:00:204895 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514896 URLRequest* request,
4897 const CompletionCallback& callback,
4898 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164899 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134900 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164901 TestNetworkDelegate::OnHeadersReceived(request,
4902 callback,
[email protected]abe1c4a2013-10-25 19:28:514903 original_response_headers,
[email protected]5f714132014-03-26 10:41:164904 override_response_headers,
4905 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514906 return RunCallbackAsynchronously(request, callback);
4907 }
4908
dchengb03027d2014-10-21 12:00:204909 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514910 URLRequest* request,
4911 const AuthChallengeInfo& auth_info,
4912 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134913 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514914 AsyncDelegateLogger::Run(
4915 request,
4916 LOAD_STATE_WAITING_FOR_DELEGATE,
4917 LOAD_STATE_WAITING_FOR_DELEGATE,
4918 LOAD_STATE_WAITING_FOR_DELEGATE,
4919 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4920 callback, credentials));
4921 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4922 }
4923
4924 private:
4925 static int RunCallbackAsynchronously(
4926 URLRequest* request,
4927 const CompletionCallback& callback) {
4928 AsyncDelegateLogger::Run(
4929 request,
4930 LOAD_STATE_WAITING_FOR_DELEGATE,
4931 LOAD_STATE_WAITING_FOR_DELEGATE,
4932 LOAD_STATE_WAITING_FOR_DELEGATE,
4933 base::Bind(callback, OK));
4934 return ERR_IO_PENDING;
4935 }
4936
4937 static void SetAuthAndResume(const AuthCallback& callback,
4938 AuthCredentials* credentials) {
4939 *credentials = AuthCredentials(kUser, kSecret);
4940 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4941 }
4942
4943 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4944};
4945
4946// URLRequest::Delegate that logs delegate information when the headers
4947// are received, when each read completes, and during redirects. Uses
4948// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4949//
4950// Inherits from TestDelegate to reuse the TestDelegate code to handle
4951// advancing to the next step in most cases, as well as cancellation.
4952class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4953 public:
4954 enum CancelStage {
4955 NO_CANCEL = 0,
4956 CANCEL_ON_RECEIVED_REDIRECT,
4957 CANCEL_ON_RESPONSE_STARTED,
4958 CANCEL_ON_READ_COMPLETED
4959 };
4960
4961 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4962 : cancel_stage_(cancel_stage) {
4963 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4964 set_cancel_in_received_redirect(true);
4965 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4966 set_cancel_in_response_started(true);
4967 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4968 set_cancel_in_received_data(true);
4969 }
dchengb03027d2014-10-21 12:00:204970 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514971
4972 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204973 void OnReceivedRedirect(URLRequest* request,
4974 const RedirectInfo& redirect_info,
4975 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514976 *defer_redirect = true;
4977 AsyncDelegateLogger::Run(
4978 request,
4979 LOAD_STATE_WAITING_FOR_DELEGATE,
4980 LOAD_STATE_WAITING_FOR_DELEGATE,
4981 LOAD_STATE_WAITING_FOR_DELEGATE,
4982 base::Bind(
4983 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594984 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514985 }
4986
dchengb03027d2014-10-21 12:00:204987 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514988 AsyncDelegateLogger::Run(
4989 request,
4990 LOAD_STATE_WAITING_FOR_DELEGATE,
4991 LOAD_STATE_WAITING_FOR_DELEGATE,
4992 LOAD_STATE_WAITING_FOR_DELEGATE,
4993 base::Bind(
4994 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4995 base::Unretained(this), request));
4996 }
4997
dchengb03027d2014-10-21 12:00:204998 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514999 AsyncDelegateLogger::Run(
5000 request,
5001 LOAD_STATE_IDLE,
5002 LOAD_STATE_IDLE,
5003 LOAD_STATE_IDLE,
5004 base::Bind(
5005 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5006 base::Unretained(this), request, bytes_read));
5007 }
5008
5009 private:
5010 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595011 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515012 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595013 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515014 // FollowDeferredRedirect should not be called after cancellation.
5015 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5016 return;
5017 if (!defer_redirect)
5018 request->FollowDeferredRedirect();
5019 }
5020
5021 void OnResponseStartedLoggingComplete(URLRequest* request) {
5022 // The parent class continues the request.
5023 TestDelegate::OnResponseStarted(request);
5024 }
5025
5026 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5027 // The parent class continues the request.
5028 TestDelegate::OnReadCompleted(request, bytes_read);
5029 }
5030
5031 const CancelStage cancel_stage_;
5032
5033 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5034};
5035
5036// Tests handling of delegate info before a request starts.
5037TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555038 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515039
5040 TestDelegate request_delegate;
5041 TestURLRequestContext context(true);
5042 context.set_network_delegate(NULL);
5043 context.set_net_log(&net_log_);
5044 context.Init();
5045
5046 {
danakj8522a25b2016-04-16 00:17:365047 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555048 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365049 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195050 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515051 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085052 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515053
5054 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195055 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515056 LOAD_STATE_WAITING_FOR_DELEGATE,
5057 LOAD_STATE_WAITING_FOR_DELEGATE,
5058 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195059 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515060
5061 base::RunLoop().Run();
5062
[email protected]f7022f32014-08-21 16:32:195063 EXPECT_EQ(200, r->GetResponseCode());
5064 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515065 }
5066
mmenke43758e62015-05-04 21:09:465067 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515068 net_log_.GetEntries(&entries);
5069 size_t log_position = ExpectLogContainsSomewhereAfter(
5070 entries,
5071 0,
5072 NetLog::TYPE_DELEGATE_INFO,
5073 NetLog::PHASE_BEGIN);
5074
5075 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5076
5077 // Nothing else should add any delegate info to the request.
5078 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5079 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5080}
5081
5082// Tests handling of delegate info from a network delegate.
5083TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555084 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515085
5086 TestDelegate request_delegate;
5087 AsyncLoggingNetworkDelegate network_delegate;
5088 TestURLRequestContext context(true);
5089 context.set_network_delegate(&network_delegate);
5090 context.set_net_log(&net_log_);
5091 context.Init();
5092
5093 {
danakj8522a25b2016-04-16 00:17:365094 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555095 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365096 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195097 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515098 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085099 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515100
[email protected]f7022f32014-08-21 16:32:195101 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515102 base::RunLoop().Run();
5103
[email protected]f7022f32014-08-21 16:32:195104 EXPECT_EQ(200, r->GetResponseCode());
5105 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515106 EXPECT_EQ(1, network_delegate.created_requests());
5107 EXPECT_EQ(0, network_delegate.destroyed_requests());
5108 }
5109 EXPECT_EQ(1, network_delegate.destroyed_requests());
5110
5111 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465112 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515113 net_log_.GetEntries(&entries);
5114 for (size_t i = 0; i < 3; ++i) {
5115 log_position = ExpectLogContainsSomewhereAfter(
5116 entries,
5117 log_position + 1,
5118 NetLog::TYPE_URL_REQUEST_DELEGATE,
5119 NetLog::PHASE_BEGIN);
5120
5121 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5122 log_position + 1);
5123
5124 ASSERT_LT(log_position, entries.size());
5125 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5126 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485127
5128 if (i == 1) {
5129 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5130 entries, log_position + 1);
5131 }
[email protected]abe1c4a2013-10-25 19:28:515132 }
5133
5134 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5135 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5136}
5137
5138// Tests handling of delegate info from a network delegate in the case of an
5139// HTTP redirect.
5140TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555141 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515142
5143 TestDelegate request_delegate;
5144 AsyncLoggingNetworkDelegate network_delegate;
5145 TestURLRequestContext context(true);
5146 context.set_network_delegate(&network_delegate);
5147 context.set_net_log(&net_log_);
5148 context.Init();
5149
5150 {
danakj8522a25b2016-04-16 00:17:365151 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555152 http_test_server()->GetURL("/server-redirect?simple.html"),
5153 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195154 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515155 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085156 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515157
[email protected]f7022f32014-08-21 16:32:195158 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515159 base::RunLoop().Run();
5160
[email protected]f7022f32014-08-21 16:32:195161 EXPECT_EQ(200, r->GetResponseCode());
5162 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515163 EXPECT_EQ(2, network_delegate.created_requests());
5164 EXPECT_EQ(0, network_delegate.destroyed_requests());
5165 }
5166 EXPECT_EQ(1, network_delegate.destroyed_requests());
5167
5168 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465169 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515170 net_log_.GetEntries(&entries);
5171 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005172 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515173 for (size_t i = 0; i < 3; ++i) {
5174 log_position = ExpectLogContainsSomewhereAfter(
5175 entries,
5176 log_position + 1,
5177 NetLog::TYPE_URL_REQUEST_DELEGATE,
5178 NetLog::PHASE_BEGIN);
5179
5180 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5181 log_position + 1);
5182
5183 ASSERT_LT(log_position, entries.size());
5184 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5185 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485186
5187 if (i == 1) {
5188 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5189 entries, log_position + 1);
5190 }
[email protected]abe1c4a2013-10-25 19:28:515191 }
5192
5193 // The URLRequest::Delegate then gets informed about the redirect.
5194 log_position = ExpectLogContainsSomewhereAfter(
5195 entries,
5196 log_position + 1,
5197 NetLog::TYPE_URL_REQUEST_DELEGATE,
5198 NetLog::PHASE_BEGIN);
5199
5200 // The NetworkDelegate logged information in the same three events as before.
5201 for (size_t i = 0; i < 3; ++i) {
5202 log_position = ExpectLogContainsSomewhereAfter(
5203 entries,
5204 log_position + 1,
5205 NetLog::TYPE_URL_REQUEST_DELEGATE,
5206 NetLog::PHASE_BEGIN);
5207
5208 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5209 log_position + 1);
5210
5211 ASSERT_LT(log_position, entries.size());
5212 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5213 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5214 }
5215
5216 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5217 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5218}
5219
5220// Tests handling of delegate info from a network delegate in the case of HTTP
5221// AUTH.
5222TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555223 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515224
5225 TestDelegate request_delegate;
5226 AsyncLoggingNetworkDelegate network_delegate;
5227 TestURLRequestContext context(true);
5228 context.set_network_delegate(&network_delegate);
5229 context.set_net_log(&net_log_);
5230 context.Init();
5231
5232 {
danakj8522a25b2016-04-16 00:17:365233 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555234 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365235 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195236 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515237 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085238 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515239
[email protected]f7022f32014-08-21 16:32:195240 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515241 base::RunLoop().Run();
5242
[email protected]f7022f32014-08-21 16:32:195243 EXPECT_EQ(200, r->GetResponseCode());
5244 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515245 EXPECT_EQ(1, network_delegate.created_requests());
5246 EXPECT_EQ(0, network_delegate.destroyed_requests());
5247 }
5248 EXPECT_EQ(1, network_delegate.destroyed_requests());
5249
5250 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465251 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515252 net_log_.GetEntries(&entries);
5253 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005254 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5255 // in
5256 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515257 for (size_t i = 0; i < 6; ++i) {
5258 log_position = ExpectLogContainsSomewhereAfter(
5259 entries,
5260 log_position + 1,
5261 NetLog::TYPE_URL_REQUEST_DELEGATE,
5262 NetLog::PHASE_BEGIN);
5263
5264 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5265 log_position + 1);
5266
5267 ASSERT_LT(log_position, entries.size());
5268 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5269 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:485270
5271 if (i == 1) {
5272 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5273 entries, log_position + 1);
5274 }
[email protected]abe1c4a2013-10-25 19:28:515275 }
5276
5277 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5278 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5279}
5280
tommycli59a63432015-11-06 00:10:555281// TODO(svaldez): Update tests to use EmbeddedTestServer.
5282#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515283// Tests handling of delegate info from a URLRequest::Delegate.
5284TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555285 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5286 SpawnedTestServer::kLocalhost,
5287 base::FilePath(kTestFilePath));
5288
5289 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515290
5291 AsyncLoggingUrlRequestDelegate request_delegate(
5292 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5293 TestURLRequestContext context(true);
5294 context.set_network_delegate(NULL);
5295 context.set_net_log(&net_log_);
5296 context.Init();
5297
5298 {
5299 // A chunked response with delays between chunks is used to make sure that
5300 // attempts by the URLRequest delegate to log information while reading the
5301 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485302 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515303 // that it occurs.
danakj8522a25b2016-04-16 00:17:365304 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555305 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365306 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195307 LoadStateWithParam load_state = r->GetLoadState();
5308 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515309 base::RunLoop().Run();
5310
[email protected]f7022f32014-08-21 16:32:195311 EXPECT_EQ(200, r->GetResponseCode());
5312 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515313 }
5314
mmenke43758e62015-05-04 21:09:465315 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515316 net_log_.GetEntries(&entries);
5317
[email protected]1826a402014-01-08 15:40:485318 size_t log_position = 0;
5319
5320 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5321 entries, log_position);
5322
[email protected]abe1c4a2013-10-25 19:28:515323 // The delegate info should only have been logged on header complete. Other
5324 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485325 log_position =
5326 ExpectLogContainsSomewhereAfter(entries,
5327 log_position + 1,
5328 NetLog::TYPE_URL_REQUEST_DELEGATE,
5329 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515330
5331 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5332 log_position + 1);
5333
5334 ASSERT_LT(log_position, entries.size());
5335 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5336 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5337
5338 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5339 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5340 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5341 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5342}
tommycli59a63432015-11-06 00:10:555343#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515344
5345// Tests handling of delegate info from a URLRequest::Delegate in the case of
5346// an HTTP redirect.
5347TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555348 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515349
5350 AsyncLoggingUrlRequestDelegate request_delegate(
5351 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5352 TestURLRequestContext context(true);
5353 context.set_network_delegate(NULL);
5354 context.set_net_log(&net_log_);
5355 context.Init();
5356
5357 {
danakj8522a25b2016-04-16 00:17:365358 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555359 http_test_server()->GetURL("/server-redirect?simple.html"),
5360 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195361 LoadStateWithParam load_state = r->GetLoadState();
5362 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515363 base::RunLoop().Run();
5364
[email protected]f7022f32014-08-21 16:32:195365 EXPECT_EQ(200, r->GetResponseCode());
5366 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515367 }
5368
mmenke43758e62015-05-04 21:09:465369 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515370 net_log_.GetEntries(&entries);
5371
5372 // Delegate info should only have been logged in OnReceivedRedirect and
5373 // OnResponseStarted.
5374 size_t log_position = 0;
5375 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485376 if (i == 0) {
5377 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5378 entries, log_position) + 1;
5379 }
5380
[email protected]abe1c4a2013-10-25 19:28:515381 log_position = ExpectLogContainsSomewhereAfter(
5382 entries,
5383 log_position,
5384 NetLog::TYPE_URL_REQUEST_DELEGATE,
5385 NetLog::PHASE_BEGIN);
5386
5387 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5388 log_position + 1);
5389
5390 ASSERT_LT(log_position, entries.size());
5391 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5392 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5393 }
5394
5395 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5396 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5397 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5398 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5399}
5400
5401// Tests handling of delegate info from a URLRequest::Delegate in the case of
5402// an HTTP redirect, with cancellation at various points.
5403TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555404 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515405
5406 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5407 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5408 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5409 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5410 };
5411
5412 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5413 ++test_case) {
5414 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5415 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515416 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515417 context.set_network_delegate(NULL);
5418 context.set_net_log(&net_log);
5419 context.Init();
5420
5421 {
danakj8522a25b2016-04-16 00:17:365422 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555423 http_test_server()->GetURL("/server-redirect?simple.html"),
5424 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195425 LoadStateWithParam load_state = r->GetLoadState();
5426 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515427 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195428 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515429 }
5430
mmenke43758e62015-05-04 21:09:465431 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515432 net_log.GetEntries(&entries);
5433
5434 // Delegate info is always logged in both OnReceivedRedirect and
5435 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5436 // OnResponseStarted delegate call is after cancellation, but logging is
5437 // still currently supported in that call.
5438 size_t log_position = 0;
5439 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485440 if (i == 0) {
5441 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5442 entries, log_position) + 1;
5443 }
5444
[email protected]abe1c4a2013-10-25 19:28:515445 log_position = ExpectLogContainsSomewhereAfter(
5446 entries,
5447 log_position,
5448 NetLog::TYPE_URL_REQUEST_DELEGATE,
5449 NetLog::PHASE_BEGIN);
5450
5451 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5452 log_position + 1);
5453
5454 ASSERT_LT(log_position, entries.size());
5455 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5456 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5457 }
5458
5459 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5460 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5461 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5462 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5463 }
5464}
5465
[email protected]847c0fa92012-11-06 16:37:425466namespace {
5467
5468const char kExtraHeader[] = "Allow-Snafu";
5469const char kExtraValue[] = "fubar";
5470
5471class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205472 void OnReceivedRedirect(URLRequest* request,
5473 const RedirectInfo& redirect_info,
5474 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595475 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425476 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5477 }
5478};
5479
5480} // namespace
5481
5482TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555483 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425484
tommycli59a63432015-11-06 00:10:555485 GURL destination_url =
5486 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5487 GURL original_url =
5488 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425489 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365490 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365491 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195492 req->Start();
[email protected]255620da2013-08-19 13:14:295493 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425494
5495 std::string value;
[email protected]f7022f32014-08-21 16:32:195496 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425497 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5498 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195499 EXPECT_FALSE(req->is_pending());
5500 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425501 EXPECT_EQ(kExtraValue, d.data_received());
5502}
5503
[email protected]251a1b92012-11-13 11:01:095504namespace {
5505
5506const char kExtraHeaderToRemove[] = "To-Be-Removed";
5507
5508class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205509 void OnReceivedRedirect(URLRequest* request,
5510 const RedirectInfo& redirect_info,
5511 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595512 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095513 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5514 }
5515};
5516
5517} // namespace
5518
5519TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555520 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095521
tommycli59a63432015-11-06 00:10:555522 GURL destination_url = http_test_server()->GetURL(
5523 "/echoheader?" + std::string(kExtraHeaderToRemove));
5524 GURL original_url =
5525 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095526 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365527 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365528 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195529 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5530 req->Start();
[email protected]255620da2013-08-19 13:14:295531 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095532
5533 std::string value;
[email protected]f7022f32014-08-21 16:32:195534 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095535 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195536 EXPECT_FALSE(req->is_pending());
5537 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095538 EXPECT_EQ("None", d.data_received());
5539}
5540
[email protected]316c1e5e2012-09-12 15:17:445541TEST_F(URLRequestTestHTTP, CancelTest) {
5542 TestDelegate d;
5543 {
danakj8522a25b2016-04-16 00:17:365544 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365545 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445546
[email protected]f7022f32014-08-21 16:32:195547 r->Start();
5548 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445549
[email protected]f7022f32014-08-21 16:32:195550 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445551
[email protected]255620da2013-08-19 13:14:295552 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445553
5554 // We expect to receive OnResponseStarted even though the request has been
5555 // cancelled.
5556 EXPECT_EQ(1, d.response_started_count());
5557 EXPECT_EQ(0, d.bytes_received());
5558 EXPECT_FALSE(d.received_data_before_response());
5559 }
5560}
5561
5562TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555563 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445564
5565 TestDelegate d;
5566 {
danakj8522a25b2016-04-16 00:17:365567 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555568 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445569
5570 d.set_cancel_in_response_started(true);
5571
[email protected]f7022f32014-08-21 16:32:195572 r->Start();
5573 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445574
[email protected]255620da2013-08-19 13:14:295575 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445576
5577 EXPECT_EQ(1, d.response_started_count());
5578 EXPECT_EQ(0, d.bytes_received());
5579 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195580 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445581 }
5582}
5583
5584TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555585 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445586
5587 TestDelegate d;
5588 {
danakj8522a25b2016-04-16 00:17:365589 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555590 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445591
5592 d.set_cancel_in_received_data(true);
5593
[email protected]f7022f32014-08-21 16:32:195594 r->Start();
5595 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445596
[email protected]255620da2013-08-19 13:14:295597 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445598
5599 EXPECT_EQ(1, d.response_started_count());
5600 // There is no guarantee about how much data was received
5601 // before the cancel was issued. It could have been 0 bytes,
5602 // or it could have been all the bytes.
5603 // EXPECT_EQ(0, d.bytes_received());
5604 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195605 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445606 }
5607}
5608
5609TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555610 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445611
5612 TestDelegate d;
5613 {
danakj8522a25b2016-04-16 00:17:365614 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555615 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445616
[email protected]f7022f32014-08-21 16:32:195617 r->Start();
5618 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445619
5620 // The request will be implicitly canceled when it is destroyed. The
5621 // test delegate must not post a quit message when this happens because
5622 // this test doesn't actually have a message loop. The quit message would
5623 // get put on this thread's message queue and the next test would exit
5624 // early, causing problems.
5625 d.set_quit_on_complete(false);
5626 }
5627 // expect things to just cleanup properly.
5628
kimwjdalsl2bb4ff02015-12-16 22:06:025629 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445630 // message loop
5631 EXPECT_FALSE(d.received_data_before_response());
5632 EXPECT_EQ(0, d.bytes_received());
5633}
5634
5635TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555636 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445637
5638 // populate cache
5639 {
5640 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365641 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555642 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195643 r->Start();
[email protected]255620da2013-08-19 13:14:295644 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195645 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445646 }
5647
5648 // cancel read from cache (see bug 990242)
5649 {
5650 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365651 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555652 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195653 r->Start();
5654 r->Cancel();
[email protected]255620da2013-08-19 13:14:295655 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445656
[email protected]f7022f32014-08-21 16:32:195657 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445658 EXPECT_EQ(1, d.response_started_count());
5659 EXPECT_EQ(0, d.bytes_received());
5660 EXPECT_FALSE(d.received_data_before_response());
5661 }
5662}
5663
5664TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555665 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445666 HTTPUploadDataOperationTest("POST");
5667}
5668
5669TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555670 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445671 HTTPUploadDataOperationTest("PUT");
5672}
5673
5674TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555675 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445676
5677 TestDelegate d;
5678 {
danakj8522a25b2016-04-16 00:17:365679 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555680 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195681 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445682
[email protected]f7022f32014-08-21 16:32:195683 r->Start();
5684 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445685
[email protected]255620da2013-08-19 13:14:295686 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445687
[email protected]329b68b2012-11-14 17:54:275688 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195689 << "request failed: " << r->status().status()
5690 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445691
5692 EXPECT_FALSE(d.received_data_before_response());
5693 EXPECT_TRUE(d.data_received().empty());
5694 }
5695}
5696
5697TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555698 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445699
5700 TestDelegate d;
5701 {
danakj8522a25b2016-04-16 00:17:365702 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555703 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195704 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445705
[email protected]6cdfd7f2013-02-08 20:40:155706 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445707 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025708 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445709
danakj8522a25b2016-04-16 00:17:365710 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445711
[email protected]6cdfd7f2013-02-08 20:40:155712 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445713 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475714 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445715 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
danakj8522a25b2016-04-16 00:17:365716 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
avibf0746c2015-12-09 19:53:145717 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5718 std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365719 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225720 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445721
[email protected]f7022f32014-08-21 16:32:195722 r->Start();
5723 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445724
[email protected]255620da2013-08-19 13:14:295725 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445726
avibf0746c2015-12-09 19:53:145727 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295728 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5729 ASSERT_LE(size64, std::numeric_limits<int>::max());
5730 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365731 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445732
[email protected]7600d0b2013-12-08 21:43:305733 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445734
[email protected]329b68b2012-11-14 17:54:275735 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195736 << "request failed: " << r->status().status()
5737 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445738
5739 EXPECT_FALSE(d.received_data_before_response());
5740
[email protected]329b68b2012-11-14 17:54:275741 EXPECT_EQ(size, d.bytes_received());
5742 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445743 }
5744}
5745
[email protected]999dd8c2013-11-12 06:45:545746TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555747 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545748
5749 TestDelegate d;
5750 {
danakj8522a25b2016-04-16 00:17:365751 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555752 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195753 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545754
danakj8522a25b2016-04-16 00:17:365755 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545756
danakj8522a25b2016-04-16 00:17:365757 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455758 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545759 base::FilePath(FILE_PATH_LITERAL(
5760 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145761 0, std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365762 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225763 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545764
[email protected]f7022f32014-08-21 16:32:195765 r->Start();
5766 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545767
5768 base::RunLoop().Run();
5769
[email protected]999dd8c2013-11-12 06:45:545770 EXPECT_TRUE(d.request_failed());
5771 EXPECT_FALSE(d.received_data_before_response());
5772 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195773 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5774 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545775 }
5776}
5777
mmenke56b0cbb912016-03-28 21:34:535778namespace {
5779
5780// Adds a standard set of data to an upload for chunked upload integration
5781// tests.
5782void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5783 writer->AppendData("a", 1, false);
5784 writer->AppendData("bcd", 3, false);
5785 writer->AppendData("this is a longer chunk than before.", 35, false);
5786 writer->AppendData("\r\n\r\n", 4, false);
5787 writer->AppendData("0", 1, false);
5788 writer->AppendData("2323", 4, true);
5789}
5790
5791// Checks that the upload data added in AddChunksToUpload() was echoed back from
5792// the server.
5793void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5794 // This should match the chunks sent by AddChunksToUpload().
5795 const std::string expected_data =
5796 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5797
5798 ASSERT_EQ(1, d->response_started_count())
5799 << "request failed: " << r->status().status()
5800 << ", os error: " << r->status().error();
5801
5802 EXPECT_FALSE(d->received_data_before_response());
5803
5804 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5805 EXPECT_EQ(expected_data, d->data_received());
5806}
5807
5808} // namespace
5809
[email protected]316c1e5e2012-09-12 15:17:445810TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555811 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445812
5813 TestDelegate d;
5814 {
danakj8522a25b2016-04-16 00:17:365815 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555816 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365817 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535818 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365819 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535820 upload_data_stream->CreateWriter();
5821 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195822 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535823 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195824 r->Start();
5825 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445826
[email protected]255620da2013-08-19 13:14:295827 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445828
[email protected]f7022f32014-08-21 16:32:195829 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445830 }
5831}
5832
[email protected]329b68b2012-11-14 17:54:275833TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555834 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275835
5836 TestDelegate d;
5837 {
danakj8522a25b2016-04-16 00:17:365838 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555839 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365840 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535841 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365842 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535843 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365844 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195845 r->set_method("POST");
5846 r->Start();
5847 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535848 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295849 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275850
[email protected]f7022f32014-08-21 16:32:195851 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275852 }
5853}
5854
[email protected]316c1e5e2012-09-12 15:17:445855TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555856 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445857
5858 TestDelegate d;
5859 {
danakj8522a25b2016-04-16 00:17:365860 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555861 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365862 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535863 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365864 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535865 upload_data_stream->CreateWriter();
5866 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195867 r->set_method("POST");
5868 r->Start();
5869 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445870
[email protected]255620da2013-08-19 13:14:295871 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535872 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295873 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445874
[email protected]f7022f32014-08-21 16:32:195875 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445876 }
5877}
5878
5879TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555880 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445881
5882 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365883 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555884 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195885 req->Start();
[email protected]255620da2013-08-19 13:14:295886 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445887
[email protected]f7022f32014-08-21 16:32:195888 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445889
5890 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195891 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445892
5893 std::string header;
5894 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5895 EXPECT_EQ("private", header);
5896
5897 header.clear();
5898 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5899 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5900
5901 // The response has two "X-Multiple-Entries" headers.
5902 // This verfies our output has them concatenated together.
5903 header.clear();
5904 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5905 EXPECT_EQ("a, b", header);
5906}
5907
tommycli59a63432015-11-06 00:10:555908// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5909// security state. (see http://crbug.com/550977).
5910#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465911TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555912 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5913 https_test_server.SetSSLConfig(
5914 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5915 https_test_server.ServeFilesFromSourceDirectory(
5916 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465917 ASSERT_TRUE(https_test_server.Start());
5918
tommycli59a63432015-11-06 00:10:555919 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465920 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365921 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555922 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195923 request->Start();
[email protected]255620da2013-08-19 13:14:295924 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465925
5926 TransportSecurityState* security_state =
5927 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405928 TransportSecurityState::STSState sts_state;
5929 TransportSecurityState::PKPState pkp_state;
5930 EXPECT_TRUE(
5931 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5932 EXPECT_FALSE(
5933 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5934 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5935 sts_state.upgrade_mode);
5936 EXPECT_TRUE(sts_state.include_subdomains);
5937 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035938#if defined(OS_ANDROID)
5939 // Android's CertVerifyProc does not (yet) handle pins.
5940#else
martijnc0d6b622015-06-30 19:14:405941 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035942#endif
[email protected]37fd55fb2013-06-29 13:13:275943}
5944
estarka5da76702015-04-09 04:00:165945TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555946 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5947 https_test_server.ServeFilesFromSourceDirectory(
5948 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165949 ASSERT_TRUE(https_test_server.Start());
5950 // Make sure this test fails if the test server is changed to not
5951 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555952 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5953 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165954
5955 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365956 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555957 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165958 request->Start();
5959 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165960 TransportSecurityState* security_state =
5961 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405962 TransportSecurityState::STSState sts_state;
5963 EXPECT_FALSE(
5964 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165965}
5966
mathpc992e602015-10-21 20:34:035967// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5968// reject HPKP headers, and a test setting only HPKP headers will fail (no
5969// PKPState present because header rejected).
5970#if defined(OS_ANDROID)
5971#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5972#define MAYBE_ProcessPKPAndSendReport DISABLED_ProcessPKPAndSendReport
5973#define MAYBE_ProcessPKPReportOnly DISABLED_ProcessPKPReportOnly
5974#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5975 DISABLED_ProcessPKPReportOnlyWithNoViolation
5976#else
5977#define MAYBE_ProcessPKP ProcessPKP
5978#define MAYBE_ProcessPKPAndSendReport ProcessPKPAndSendReport
5979#define MAYBE_ProcessPKPReportOnly ProcessPKPReportOnly
5980#define MAYBE_ProcessPKPReportOnlyWithNoViolation \
5981 ProcessPKPReportOnlyWithNoViolation
5982#endif
5983
estark06e0dac2015-08-07 21:56:015984namespace {
estark1614475f2016-03-10 03:46:475985const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
estark06e0dac2015-08-07 21:56:015986const char kHPKPReportUri[] = "https://hpkp-report.test";
5987} // namespace
5988
[email protected]37fd55fb2013-06-29 13:13:275989// Tests that enabling HPKP on a domain does not affect the HSTS
5990// validity/expiration.
mathpc992e602015-10-21 20:34:035991TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
estark06e0dac2015-08-07 21:56:015992 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555993 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5994 https_test_server.SetSSLConfig(
5995 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5996 https_test_server.ServeFilesFromSourceDirectory(
5997 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275998 ASSERT_TRUE(https_test_server.Start());
5999
tommycli59a63432015-11-06 00:10:556000 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166001
[email protected]37fd55fb2013-06-29 13:13:276002 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366003 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556004 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196005 request->Start();
[email protected]255620da2013-08-19 13:14:296006 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276007 TransportSecurityState* security_state =
6008 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406009 TransportSecurityState::STSState sts_state;
6010 TransportSecurityState::PKPState pkp_state;
6011 EXPECT_FALSE(
6012 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6013 EXPECT_TRUE(
6014 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6015 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
6016 sts_state.upgrade_mode);
6017 EXPECT_FALSE(sts_state.include_subdomains);
6018 EXPECT_FALSE(pkp_state.include_subdomains);
6019 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:016020 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:406021 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:466022}
6023
estark06e0dac2015-08-07 21:56:016024// Tests that reports get sent on HPKP violations when a report-uri is set.
mathpc992e602015-10-21 20:34:036025TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016026 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556027 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6028 https_test_server.SetSSLConfig(
6029 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6030 https_test_server.ServeFilesFromSourceDirectory(
6031 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016032 ASSERT_TRUE(https_test_server.Start());
6033
tommycli59a63432015-11-06 00:10:556034 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016035
6036 // Set up a pin for |test_server_hostname|.
6037 TransportSecurityState security_state;
6038 const base::Time current_time(base::Time::Now());
6039 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6040 HashValueVector hashes;
6041 HashValue hash1;
6042 HashValue hash2;
6043 // The values here don't matter, as long as they are different from
6044 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446045 ASSERT_TRUE(
6046 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6047 ASSERT_TRUE(
6048 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016049 hashes.push_back(hash1);
6050 hashes.push_back(hash2);
6051 security_state.AddHPKP(test_server_hostname, expiry,
6052 false, /* include subdomains */
6053 hashes, report_uri);
6054
6055 MockCertificateReportSender mock_report_sender;
6056 security_state.SetReportSender(&mock_report_sender);
6057
6058 // Set up a MockCertVerifier to trigger a violation of the previously
6059 // set pin.
6060 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6061 ASSERT_TRUE(cert);
6062
6063 MockCertVerifier cert_verifier;
6064 CertVerifyResult verify_result;
6065 verify_result.verified_cert = cert;
6066 verify_result.is_issued_by_known_root = true;
6067 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446068 ASSERT_TRUE(
6069 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016070 verify_result.public_key_hashes.push_back(hash3);
6071 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6072
6073 TestNetworkDelegate network_delegate;
6074 TestURLRequestContext context(true);
6075 context.set_transport_security_state(&security_state);
6076 context.set_network_delegate(&network_delegate);
6077 context.set_cert_verifier(&cert_verifier);
6078 context.Init();
6079
6080 // Now send a request to trigger the violation.
6081 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366082 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556083 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016084 violating_request->Start();
6085 base::RunLoop().Run();
6086
6087 // Check that a report was sent.
6088 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6089 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366090 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016091 base::JSONReader::Read(mock_report_sender.latest_report()));
6092 ASSERT_TRUE(value);
6093 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6094 base::DictionaryValue* report_dict;
6095 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6096 std::string report_hostname;
6097 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6098 EXPECT_EQ(test_server_hostname, report_hostname);
6099}
6100
6101// Tests that reports get sent on requests with
6102// Public-Key-Pins-Report-Only headers.
mathpc992e602015-10-21 20:34:036103TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016104 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556105 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6106 https_test_server.SetSSLConfig(
6107 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6108 https_test_server.ServeFilesFromSourceDirectory(
6109 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016110 ASSERT_TRUE(https_test_server.Start());
6111
tommycli59a63432015-11-06 00:10:556112 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016113
6114 TransportSecurityState security_state;
6115 MockCertificateReportSender mock_report_sender;
6116 security_state.SetReportSender(&mock_report_sender);
6117
6118 // Set up a MockCertVerifier to violate the pin in the Report-Only
6119 // header.
6120 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6121 ASSERT_TRUE(cert);
6122
6123 MockCertVerifier cert_verifier;
6124 CertVerifyResult verify_result;
6125 verify_result.verified_cert = cert;
6126 verify_result.is_issued_by_known_root = true;
6127 HashValue hash;
6128 // This value doesn't matter, as long as it is different from the pins
6129 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446130 ASSERT_TRUE(
6131 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016132 verify_result.public_key_hashes.push_back(hash);
6133 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6134
6135 TestNetworkDelegate network_delegate;
6136 TestURLRequestContext context(true);
6137 context.set_transport_security_state(&security_state);
6138 context.set_network_delegate(&network_delegate);
6139 context.set_cert_verifier(&cert_verifier);
6140 context.Init();
6141
6142 // Now send a request to trigger the violation.
6143 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366144 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556145 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016146 DEFAULT_PRIORITY, &d));
6147 violating_request->Start();
6148 base::RunLoop().Run();
6149
6150 // Check that a report was sent.
6151 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6152 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366153 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016154 base::JSONReader::Read(mock_report_sender.latest_report()));
6155 ASSERT_TRUE(value);
6156 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6157 base::DictionaryValue* report_dict;
6158 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6159 std::string report_hostname;
6160 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6161 EXPECT_EQ(test_server_hostname, report_hostname);
6162}
6163
6164// Tests that reports do not get sent on requests with
6165// Public-Key-Pins-Report-Only headers that don't have pin violations.
mathpc992e602015-10-21 20:34:036166TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016167 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556168 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6169 https_test_server.SetSSLConfig(
6170 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6171 https_test_server.ServeFilesFromSourceDirectory(
6172 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016173 ASSERT_TRUE(https_test_server.Start());
6174
tommycli59a63432015-11-06 00:10:556175 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016176
6177 TransportSecurityState security_state;
6178 MockCertificateReportSender mock_report_sender;
6179 security_state.SetReportSender(&mock_report_sender);
6180
6181 TestNetworkDelegate network_delegate;
6182 MockCertVerifier mock_cert_verifier;
6183 TestURLRequestContext context(true);
6184 context.set_transport_security_state(&security_state);
6185 context.set_network_delegate(&network_delegate);
6186 context.set_cert_verifier(&mock_cert_verifier);
6187 mock_cert_verifier.set_default_result(OK);
6188 context.Init();
6189
6190 // Now send a request that does not trigger the violation.
6191 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366192 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556193 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016194 DEFAULT_PRIORITY, &d));
6195 request->Start();
6196 base::RunLoop().Run();
6197
6198 // Check that a report was not sent.
6199 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6200 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6201}
6202
estarka5da76702015-04-09 04:00:166203TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556204 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6205 https_test_server.ServeFilesFromSourceDirectory(
6206 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166207 ASSERT_TRUE(https_test_server.Start());
6208 // Make sure this test fails if the test server is changed to not
6209 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556210 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6211 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166212
6213 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366214 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556215 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166216 request->Start();
6217 base::RunLoop().Run();
6218
6219 TransportSecurityState* security_state =
6220 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406221 TransportSecurityState::PKPState pkp_state;
6222 EXPECT_FALSE(
6223 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166224}
6225
dadriandf302c42016-06-10 18:48:596226TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6227 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6228 https_test_server.SetSSLConfig(
6229 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6230 https_test_server.ServeFilesFromSourceDirectory(
6231 base::FilePath(kTestFilePath));
6232 ASSERT_TRUE(https_test_server.Start());
6233
6234 // Set up a MockCertVerifier to be a local root that violates the pin
6235 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6236 ASSERT_TRUE(cert);
6237
6238 MockCertVerifier cert_verifier;
6239 CertVerifyResult verify_result;
6240 verify_result.verified_cert = cert;
6241 verify_result.is_issued_by_known_root = false;
6242 HashValue hash;
6243 ASSERT_TRUE(
6244 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6245 verify_result.public_key_hashes.push_back(hash);
6246 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6247 cert_verifier.set_default_result(OK);
6248
6249 std::string test_server_hostname = https_test_server.GetURL("/").host();
6250
6251 // Set up HPKP
6252 base::Time current_time = base::Time::Now();
6253 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6254 HashValue pin;
6255 ASSERT_TRUE(
6256 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6257 HashValueVector hashes;
6258 hashes.push_back(pin);
6259 GURL report_uri(kHPKPReportUri);
6260 TransportSecurityState security_state;
6261 security_state.AddHPKP(test_server_hostname, expiry,
6262 false, /* include subdomains */
6263 hashes, report_uri);
6264
6265 TestNetworkDelegate network_delegate;
6266 TestURLRequestContext context(true);
6267 context.set_transport_security_state(&security_state);
6268 context.set_network_delegate(&network_delegate);
6269 context.set_cert_verifier(&cert_verifier);
6270 context.Init();
6271
6272 TestDelegate d;
6273 std::unique_ptr<URLRequest> request(context.CreateRequest(
6274 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6275 request->Start();
6276 base::RunLoop().Run();
6277
6278 TransportSecurityState::PKPState pkp_state;
6279 EXPECT_TRUE(
6280 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6281 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6282}
6283
[email protected]242d8562012-10-30 21:20:466284TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556285 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6286 https_test_server.SetSSLConfig(
6287 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6288 https_test_server.ServeFilesFromSourceDirectory(
6289 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466290 ASSERT_TRUE(https_test_server.Start());
6291
tommycli59a63432015-11-06 00:10:556292 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166293
[email protected]242d8562012-10-30 21:20:466294 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366295 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556296 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6297 &d));
[email protected]f7022f32014-08-21 16:32:196298 request->Start();
[email protected]255620da2013-08-19 13:14:296299 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466300
6301 // We should have set parameters from the first header, not the second.
6302 TransportSecurityState* security_state =
6303 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406304 TransportSecurityState::STSState sts_state;
6305 EXPECT_TRUE(
6306 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6307 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6308 sts_state.upgrade_mode);
6309 EXPECT_FALSE(sts_state.include_subdomains);
6310 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466311}
6312
[email protected]9f972ec2013-04-10 20:24:366313TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556314 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6315 https_test_server.SetSSLConfig(
6316 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6317 https_test_server.ServeFilesFromSourceDirectory(
6318 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366319 ASSERT_TRUE(https_test_server.Start());
6320
tommycli59a63432015-11-06 00:10:556321 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166322
[email protected]9f972ec2013-04-10 20:24:366323 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366324 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556325 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6326 &d));
[email protected]f7022f32014-08-21 16:32:196327 request->Start();
[email protected]255620da2013-08-19 13:14:296328 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366329
6330 // We should have set parameters from the first header, not the second.
6331 TransportSecurityState* security_state =
6332 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406333 TransportSecurityState::STSState sts_state;
6334 TransportSecurityState::PKPState pkp_state;
6335 EXPECT_TRUE(
6336 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6337 EXPECT_TRUE(
6338 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6339 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6340 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036341#if defined(OS_ANDROID)
6342 // Android's CertVerifyProc does not (yet) handle pins.
6343#else
martijnc0d6b622015-06-30 19:14:406344 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036345#endif
martijnc0d6b622015-06-30 19:14:406346 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366347
[email protected]a165f092013-06-12 16:10:056348 // Even though there is an HSTS header asserting includeSubdomains, it is
6349 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406350 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056351 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406352 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366353}
6354
[email protected]37fd55fb2013-06-29 13:13:276355// Tests that when multiple HPKP headers are present, asserting different
6356// policies, that only the first such policy is processed.
6357TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556358 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6359 https_test_server.SetSSLConfig(
6360 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6361 https_test_server.ServeFilesFromSourceDirectory(
6362 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276363 ASSERT_TRUE(https_test_server.Start());
6364
tommycli59a63432015-11-06 00:10:556365 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166366
[email protected]37fd55fb2013-06-29 13:13:276367 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366368 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556369 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366370 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196371 request->Start();
[email protected]255620da2013-08-19 13:14:296372 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276373
6374 TransportSecurityState* security_state =
6375 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406376 TransportSecurityState::STSState sts_state;
6377 TransportSecurityState::PKPState pkp_state;
6378 EXPECT_TRUE(
6379 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6380 EXPECT_TRUE(
6381 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6382 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6383 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036384#if defined(OS_ANDROID)
6385 // Android's CertVerifyProc does not (yet) handle pins.
6386#else
martijnc0d6b622015-06-30 19:14:406387 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036388#endif
martijnc0d6b622015-06-30 19:14:406389 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276390
martijnc0d6b622015-06-30 19:14:406391 EXPECT_TRUE(sts_state.include_subdomains);
6392 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276393}
6394
estark1614475f2016-03-10 03:46:476395// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6396// called.
6397class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6398 public:
6399 MockExpectCTReporter() : num_failures_(0) {}
6400 ~MockExpectCTReporter() override {}
6401
6402 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6403 const GURL& report_uri,
6404 const net::SSLInfo& ssl_info) override {
6405 num_failures_++;
6406 }
6407
6408 uint32_t num_failures() { return num_failures_; }
6409
6410 private:
6411 uint32_t num_failures_;
6412};
6413
6414// A CTVerifier that returns net::OK for every certificate.
6415class MockCTVerifier : public CTVerifier {
6416 public:
6417 MockCTVerifier() {}
6418 ~MockCTVerifier() override {}
6419
6420 int Verify(X509Certificate* cert,
6421 const std::string& stapled_ocsp_response,
6422 const std::string& sct_list_from_tls_extension,
6423 ct::CTVerifyResult* result,
6424 const BoundNetLog& net_log) override {
6425 return net::OK;
6426 }
6427
6428 void SetObserver(Observer* observer) override {}
6429};
6430
6431// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6432// for every certificate.
6433class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6434 public:
6435 MockCTPolicyEnforcer()
6436 : default_result_(
6437 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6438 ~MockCTPolicyEnforcer() override {}
6439
6440 ct::CertPolicyCompliance DoesConformToCertPolicy(
6441 X509Certificate* cert,
6442 const SCTList& verified_scts,
6443 const BoundNetLog& net_log) override {
6444 return default_result_;
6445 }
6446
6447 void set_default_result(ct::CertPolicyCompliance default_result) {
6448 default_result_ = default_result;
6449 }
6450
6451 private:
6452 ct::CertPolicyCompliance default_result_;
6453};
6454
6455// Tests that Expect CT headers are processed correctly.
6456TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6457 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6458 https_test_server.SetSSLConfig(
6459 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6460 https_test_server.ServeFilesFromSourceDirectory(
6461 base::FilePath(kTestFilePath));
6462 ASSERT_TRUE(https_test_server.Start());
6463
6464 MockExpectCTReporter reporter;
6465 TransportSecurityState transport_security_state;
6466 transport_security_state.enable_static_expect_ct_ = true;
6467 transport_security_state.SetExpectCTReporter(&reporter);
6468
6469 // Set up a MockCertVerifier to accept the certificate that the server sends.
6470 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6471 ASSERT_TRUE(cert);
6472 MockCertVerifier cert_verifier;
6473 CertVerifyResult verify_result;
6474 verify_result.verified_cert = cert;
6475 verify_result.is_issued_by_known_root = true;
6476 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6477
6478 // Set up a MockCTVerifier and MockCTPolicyEnforcer to trigger an Expect CT
6479 // violation.
6480 MockCTVerifier ct_verifier;
6481 MockCTPolicyEnforcer ct_policy_enforcer;
6482 ct_policy_enforcer.set_default_result(
6483 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6484
6485 TestNetworkDelegate network_delegate;
6486 // Use a MockHostResolver (which by default maps all hosts to
6487 // 127.0.0.1) so that the request can be sent to a site on the Expect
6488 // CT preload list.
6489 MockHostResolver host_resolver;
6490 TestURLRequestContext context(true);
6491 context.set_host_resolver(&host_resolver);
6492 context.set_transport_security_state(&transport_security_state);
6493 context.set_network_delegate(&network_delegate);
6494 context.set_cert_verifier(&cert_verifier);
6495 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206496 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476497 context.Init();
6498
6499 // Now send a request to trigger the violation.
6500 TestDelegate d;
6501 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6502 GURL::Replacements replace_host;
6503 replace_host.SetHostStr(kExpectCTStaticHostname);
6504 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366505 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476506 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6507 violating_request->Start();
6508 base::RunLoop().Run();
6509
6510 EXPECT_EQ(1u, reporter.num_failures());
6511}
6512
tommycli59a63432015-11-06 00:10:556513#endif // !defined(OS_IOS)
6514
[email protected]316c1e5e2012-09-12 15:17:446515TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556516 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446517
6518 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366519 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556520 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366521 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196522 req->Start();
[email protected]255620da2013-08-19 13:14:296523 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446524
6525 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196526 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446527 EXPECT_EQ("text/html", mime_type);
6528
6529 std::string charset;
[email protected]f7022f32014-08-21 16:32:196530 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446531 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196532 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446533}
6534
[email protected]02494ec2014-05-07 15:05:296535TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346536 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346537 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346538 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026539 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346540
6541 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506542 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346543}
6544
[email protected]02494ec2014-05-07 15:05:296545#if !defined(DISABLE_FILE_SUPPORT)
6546TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6547 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6548 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456549 FileProtocolHandler file_protocol_handler(
6550 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296551 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6552
6553 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506554 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296555}
6556
[email protected]588614c22013-08-16 00:09:026557TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556558 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446559
6560 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366561 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556562 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366563 &d));
[email protected]f7022f32014-08-21 16:32:196564 req->Start();
[email protected]255620da2013-08-19 13:14:296565 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446566
[email protected]f7022f32014-08-21 16:32:196567 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6568 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446569}
[email protected]02494ec2014-05-07 15:05:296570#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446571
[email protected]588614c22013-08-16 00:09:026572TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556573 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026574
6575 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366576 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556577 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366578 &d));
[email protected]f7022f32014-08-21 16:32:196579 req->Start();
fdoray5eeb7642016-06-22 16:11:286580 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026581
[email protected]f7022f32014-08-21 16:32:196582 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6583 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:026584}
6585
[email protected]316c1e5e2012-09-12 15:17:446586TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556587 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446588
6589 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366590 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556591 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366592 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196593 req->Start();
[email protected]255620da2013-08-19 13:14:296594 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446595
[email protected]f7022f32014-08-21 16:32:196596 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6597 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:446598}
6599
[email protected]e50efea2014-03-24 18:41:006600// Make sure redirects are cached, despite not reading their bodies.
6601TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556602 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006603 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556604 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006605
6606 {
6607 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366608 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366609 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196610 req->Start();
[email protected]e50efea2014-03-24 18:41:006611 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196612 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006613 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556614 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006615 }
6616
6617 {
6618 TestDelegate d;
6619 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366620 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366621 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196622 req->Start();
[email protected]e50efea2014-03-24 18:41:006623 base::RunLoop().Run();
6624
6625 EXPECT_EQ(1, d.received_redirect_count());
6626 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196627 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006628
[email protected]f7022f32014-08-21 16:32:196629 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006630 base::RunLoop().Run();
6631 EXPECT_EQ(1, d.received_redirect_count());
6632 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196633 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556634 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006635 }
6636}
6637
6638// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6639// when the headers are read, since the body won't have been read.
6640TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556641 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006642 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556643 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006644
6645 {
6646 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556647 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006648 default_network_delegate_.set_redirect_on_headers_received_url(
6649 redirect_to_url);
6650
6651 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366652 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366653 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196654 req->Start();
[email protected]e50efea2014-03-24 18:41:006655 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196656 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006657 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196658 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006659 }
6660
6661 {
6662 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366663 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366664 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196665 req->Start();
[email protected]e50efea2014-03-24 18:41:006666 base::RunLoop().Run();
6667
[email protected]f7022f32014-08-21 16:32:196668 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6669 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006670 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196671 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006672 }
6673}
6674
[email protected]5f714132014-03-26 10:41:166675// Tests that redirection to an unsafe URL is allowed when it has been marked as
6676// safe.
6677TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556678 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166679
6680 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6681 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6682 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6683
6684 TestDelegate d;
6685 {
danakj8522a25b2016-04-16 00:17:366686 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556687 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166688
[email protected]f7022f32014-08-21 16:32:196689 r->Start();
[email protected]5f714132014-03-26 10:41:166690 base::RunLoop().Run();
6691
[email protected]f7022f32014-08-21 16:32:196692 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166693
[email protected]f7022f32014-08-21 16:32:196694 EXPECT_EQ(2U, r->url_chain().size());
6695 EXPECT_EQ(OK, r->status().error());
6696 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166697 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6698 }
6699}
6700
6701// Tests that a redirect to a different unsafe URL is blocked, even after adding
6702// some other URL to the whitelist.
6703TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556704 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166705
6706 GURL unsafe_url("data:text/html,something");
6707 GURL different_unsafe_url("data:text/html,something-else");
6708 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6709 default_network_delegate_.set_allowed_unsafe_redirect_url(
6710 different_unsafe_url);
6711
6712 TestDelegate d;
6713 {
danakj8522a25b2016-04-16 00:17:366714 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556715 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166716
[email protected]f7022f32014-08-21 16:32:196717 r->Start();
[email protected]5f714132014-03-26 10:41:166718 base::RunLoop().Run();
6719
[email protected]f7022f32014-08-21 16:32:196720 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
6721 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:166722 }
6723}
6724
[email protected]5f714132014-03-26 10:41:166725// Redirects from an URL with fragment to an unsafe URL with fragment should
6726// be allowed, and the reference fragment of the target URL should be preserved.
6727TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556728 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166729
tommycli59a63432015-11-06 00:10:556730 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166731 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6732 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6733
6734 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6735 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6736
6737 TestDelegate d;
6738 {
danakj8522a25b2016-04-16 00:17:366739 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366740 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166741
[email protected]f7022f32014-08-21 16:32:196742 r->Start();
[email protected]5f714132014-03-26 10:41:166743 base::RunLoop().Run();
6744
[email protected]f7022f32014-08-21 16:32:196745 EXPECT_EQ(2U, r->url_chain().size());
6746 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6747 EXPECT_EQ(OK, r->status().error());
6748 EXPECT_EQ(original_url, r->original_url());
6749 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166750 }
6751}
6752
6753// When a delegate has specified a safe redirect URL, but it does not match the
6754// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146755TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556756 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166757
tommycli59a63432015-11-06 00:10:556758 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166759 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556760 GURL redirect_url(http_test_server()->GetURL("/target"));
6761 GURL expected_redirect_url(
6762 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166763
6764 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6765 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6766
6767 TestDelegate d;
6768 {
danakj8522a25b2016-04-16 00:17:366769 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366770 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166771
[email protected]f7022f32014-08-21 16:32:196772 r->Start();
[email protected]5f714132014-03-26 10:41:166773 base::RunLoop().Run();
6774
[email protected]f7022f32014-08-21 16:32:196775 EXPECT_EQ(2U, r->url_chain().size());
6776 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6777 EXPECT_EQ(OK, r->status().error());
6778 EXPECT_EQ(original_url, r->original_url());
6779 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166780 }
6781}
6782
[email protected]f878230e2014-04-03 15:36:146783// When a delegate has specified a safe redirect URL, assume that the redirect
6784// URL should not be changed. In particular, the reference fragment should not
6785// be modified.
6786TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556787 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146788
tommycli59a63432015-11-06 00:10:556789 GURL original_url(
6790 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146791 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6792
6793 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6794 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6795
6796 TestDelegate d;
6797 {
danakj8522a25b2016-04-16 00:17:366798 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366799 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146800
[email protected]f7022f32014-08-21 16:32:196801 r->Start();
[email protected]f878230e2014-04-03 15:36:146802 base::RunLoop().Run();
6803
[email protected]f7022f32014-08-21 16:32:196804 EXPECT_EQ(2U, r->url_chain().size());
6805 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6806 EXPECT_EQ(OK, r->status().error());
6807 EXPECT_EQ(original_url, r->original_url());
6808 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146809 }
6810}
6811
6812// When a URLRequestRedirectJob is created, the redirection must be followed and
6813// the reference fragment of the target URL must not be modified.
6814TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556815 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146816
tommycli59a63432015-11-06 00:10:556817 GURL original_url(
6818 http_test_server()->GetURL("/original#should-not-be-appended"));
6819 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146820
6821 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366822 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366823 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146824
danakj8522a25b2016-04-16 00:17:366825 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196826 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426827 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6828 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146829
[email protected]f7022f32014-08-21 16:32:196830 r->Start();
[email protected]f878230e2014-04-03 15:36:146831 base::RunLoop().Run();
6832
[email protected]f7022f32014-08-21 16:32:196833 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6834 EXPECT_EQ(OK, r->status().error());
6835 EXPECT_EQ(original_url, r->original_url());
6836 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146837}
6838
lizeb5120f6dc2016-02-19 09:29:446839TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6840 ASSERT_TRUE(http_test_server()->Start());
6841
6842 const std::string referrer("foobar://totally.legit.referrer");
6843 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366844 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446845 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6846 req->SetReferrer(referrer);
6847 req->Start();
6848 base::RunLoop().Run();
6849
6850 EXPECT_EQ(std::string("None"), d.data_received());
6851}
6852
[email protected]316c1e5e2012-09-12 15:17:446853TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556854 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446855
6856 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366857 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556858 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196859 req->SetReferrer("http://user:[email protected]/");
6860 req->Start();
[email protected]255620da2013-08-19 13:14:296861 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446862
6863 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6864}
6865
[email protected]99ecf6e2013-04-10 22:46:136866TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556867 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136868
6869 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366870 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556871 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196872 req->SetReferrer("http://foo.com/test#fragment");
6873 req->Start();
[email protected]255620da2013-08-19 13:14:296874 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136875
6876 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6877}
6878
6879TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556880 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136881
6882 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366883 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556884 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196885 req->SetReferrer("http://foo.com/test#fragment");
6886 req->SetReferrer("");
6887 req->Start();
[email protected]255620da2013-08-19 13:14:296888 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136889
6890 EXPECT_EQ(std::string("None"), d.data_received());
6891}
6892
[email protected]1826a402014-01-08 15:40:486893// Defer network start and then resume, checking that the request was a success
6894// and bytes were received.
6895TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556896 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486897
6898 TestDelegate d;
6899 {
6900 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556901 GURL test_url(http_test_server()->GetURL("/echo"));
danakj8522a25b2016-04-16 00:17:366902 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366903 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486904
[email protected]f7022f32014-08-21 16:32:196905 req->Start();
[email protected]1826a402014-01-08 15:40:486906 base::RunLoop().Run();
6907
6908 EXPECT_EQ(1, d.received_before_network_start_count());
6909 EXPECT_EQ(0, d.response_started_count());
6910
[email protected]f7022f32014-08-21 16:32:196911 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486912 base::RunLoop().Run();
6913
6914 EXPECT_EQ(1, d.response_started_count());
6915 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196916 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486917 }
6918}
6919
6920// Check that OnBeforeNetworkStart is only called once even if there is a
6921// redirect.
6922TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
tommycli59a63432015-11-06 00:10:556923 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486924
6925 TestDelegate d;
6926 {
6927 d.set_quit_on_redirect(true);
6928 d.set_quit_on_network_start(true);
danakj8522a25b2016-04-16 00:17:366929 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556930 http_test_server()->GetURL("/server-redirect?echo"), DEFAULT_PRIORITY,
6931 &d));
[email protected]1826a402014-01-08 15:40:486932
[email protected]f7022f32014-08-21 16:32:196933 req->Start();
[email protected]1826a402014-01-08 15:40:486934 base::RunLoop().Run();
6935
6936 EXPECT_EQ(1, d.received_before_network_start_count());
6937 EXPECT_EQ(0, d.response_started_count());
6938 EXPECT_EQ(0, d.received_redirect_count());
6939
[email protected]f7022f32014-08-21 16:32:196940 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486941 base::RunLoop().Run();
6942
6943 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196944 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486945 base::RunLoop().Run();
6946
6947 // Check that the redirect's new network transaction does not get propagated
6948 // to a second OnBeforeNetworkStart() notification.
6949 EXPECT_EQ(1, d.received_before_network_start_count());
6950
6951 EXPECT_EQ(1, d.response_started_count());
6952 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196953 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486954 }
6955}
6956
6957// Cancel the request after learning that the request would use the network.
6958TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
tommycli59a63432015-11-06 00:10:556959 ASSERT_TRUE(http_test_server()->Start());
[email protected]1826a402014-01-08 15:40:486960
6961 TestDelegate d;
6962 {
6963 d.set_quit_on_network_start(true);
tommycli59a63432015-11-06 00:10:556964 GURL test_url(http_test_server()->GetURL("/echo"));
danakj8522a25b2016-04-16 00:17:366965 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366966 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:486967
[email protected]f7022f32014-08-21 16:32:196968 req->Start();
[email protected]1826a402014-01-08 15:40:486969 base::RunLoop().Run();
6970
6971 EXPECT_EQ(1, d.received_before_network_start_count());
6972 EXPECT_EQ(0, d.response_started_count());
6973
[email protected]f7022f32014-08-21 16:32:196974 req->Cancel();
[email protected]1826a402014-01-08 15:40:486975 base::RunLoop().Run();
6976
6977 EXPECT_EQ(1, d.response_started_count());
6978 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196979 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486980 }
6981}
6982
[email protected]316c1e5e2012-09-12 15:17:446983TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556984 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446985
6986 TestDelegate d;
6987 {
6988 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366989 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556990 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6991 &d));
[email protected]f7022f32014-08-21 16:32:196992 req->Start();
[email protected]255620da2013-08-19 13:14:296993 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446994
6995 EXPECT_EQ(1, d.response_started_count());
6996 EXPECT_EQ(0, d.bytes_received());
6997 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196998 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446999 }
7000}
7001
7002TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:557003 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447004
7005 TestDelegate d;
7006 {
7007 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557008 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:367009 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367010 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:047011
[email protected]f7022f32014-08-21 16:32:197012 req->Start();
[email protected]255620da2013-08-19 13:14:297013 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447014
7015 EXPECT_EQ(1, d.received_redirect_count());
7016
[email protected]f7022f32014-08-21 16:32:197017 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297018 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447019
7020 EXPECT_EQ(1, d.response_started_count());
7021 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:197022 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:447023
[email protected]6cdfd7f2013-02-08 20:40:157024 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:447025 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477026 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:447027 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7028
7029 std::string contents;
[email protected]82f84b92013-08-30 18:23:507030 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:447031 EXPECT_EQ(contents, d.data_received());
7032 }
7033}
7034
[email protected]79e1fd62013-06-20 06:50:047035TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:557036 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:047037
7038 TestDelegate d;
7039 {
7040 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:557041 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:367042 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367043 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:047044
7045 EXPECT_FALSE(d.have_full_request_headers());
7046
[email protected]f7022f32014-08-21 16:32:197047 req->Start();
[email protected]255620da2013-08-19 13:14:297048 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047049
7050 EXPECT_EQ(1, d.received_redirect_count());
7051 EXPECT_TRUE(d.have_full_request_headers());
7052 CheckFullRequestHeaders(d.full_request_headers(), test_url);
7053 d.ClearFullRequestHeaders();
7054
[email protected]f7022f32014-08-21 16:32:197055 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:297056 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:047057
tommycli59a63432015-11-06 00:10:557058 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:047059 EXPECT_EQ(1, d.response_started_count());
7060 EXPECT_TRUE(d.have_full_request_headers());
7061 CheckFullRequestHeaders(d.full_request_headers(), target_url);
7062 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:197063 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:047064
7065 base::FilePath path;
7066 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:477067 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:047068 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
7069
7070 std::string contents;
[email protected]82f84b92013-08-30 18:23:507071 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:047072 EXPECT_EQ(contents, d.data_received());
7073 }
7074}
7075
[email protected]316c1e5e2012-09-12 15:17:447076TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:557077 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447078
7079 TestDelegate d;
7080 {
7081 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:367082 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557083 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
7084 &d));
[email protected]f7022f32014-08-21 16:32:197085 req->Start();
[email protected]255620da2013-08-19 13:14:297086 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447087
7088 EXPECT_EQ(1, d.received_redirect_count());
7089
[email protected]f7022f32014-08-21 16:32:197090 req->Cancel();
[email protected]255620da2013-08-19 13:14:297091 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447092
7093 EXPECT_EQ(1, d.response_started_count());
7094 EXPECT_EQ(0, d.bytes_received());
7095 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:197096 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:447097 }
7098}
7099
7100TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:557101 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447102
[email protected]3b23a222013-05-15 21:33:257103 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:447104 {
7105 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367106 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557107 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7108 &d));
[email protected]316c1e5e2012-09-12 15:17:447109 HttpRequestHeaders headers;
7110 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197111 req->SetExtraRequestHeaders(headers);
7112 req->Start();
[email protected]255620da2013-08-19 13:14:297113 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257114
7115 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197116 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257117 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447118 }
7119
[email protected]3b23a222013-05-15 21:33:257120 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447121 {
7122 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367123 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557124 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7125 &d));
[email protected]316c1e5e2012-09-12 15:17:447126 HttpRequestHeaders headers;
7127 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197128 req->SetExtraRequestHeaders(headers);
7129 req->Start();
[email protected]255620da2013-08-19 13:14:297130 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447131
[email protected]f7022f32014-08-21 16:32:197132 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257133
7134 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197135 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257136 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447137 }
7138
[email protected]3b23a222013-05-15 21:33:257139 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447140 {
7141 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367142 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557143 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7144 &d));
[email protected]316c1e5e2012-09-12 15:17:447145 HttpRequestHeaders headers;
7146 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197147 req->SetExtraRequestHeaders(headers);
7148 req->Start();
[email protected]255620da2013-08-19 13:14:297149 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447150
[email protected]f7022f32014-08-21 16:32:197151 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257152
7153 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197154 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257155 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447156 }
7157}
7158
7159TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557160 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447161
7162 // populate the cache
7163 {
7164 TestDelegate d;
7165 d.set_credentials(AuthCredentials(kUser, kSecret));
7166
danakj8522a25b2016-04-16 00:17:367167 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557168 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197169 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447170
[email protected]255620da2013-08-19 13:14:297171 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447172
7173 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7174 }
7175
7176 // repeat request with end-to-end validation. since auth-basic results in a
7177 // cachable page, we expect this test to result in a 304. in which case, the
7178 // response should be fetched from the cache.
7179 {
7180 TestDelegate d;
7181 d.set_credentials(AuthCredentials(kUser, kSecret));
7182
danakj8522a25b2016-04-16 00:17:367183 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557184 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197185 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7186 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447187
[email protected]255620da2013-08-19 13:14:297188 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447189
7190 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7191
7192 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197193 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447194 }
7195}
7196
7197// Check that Set-Cookie headers in 401 responses are respected.
7198// http://crbug.com/6450
7199TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557200 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447201
7202 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557203 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447204
7205 // Request a page that will give a 401 containing a Set-Cookie header.
7206 // Verify that when the transaction is restarted, it includes the new cookie.
7207 {
[email protected]ceefd7fd2012-11-29 00:36:247208 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447209 TestURLRequestContext context(true);
7210 context.set_network_delegate(&network_delegate);
7211 context.Init();
7212
7213 TestDelegate d;
7214 d.set_credentials(AuthCredentials(kUser, kSecret));
7215
danakj8522a25b2016-04-16 00:17:367216 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367217 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197218 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447219
[email protected]255620da2013-08-19 13:14:297220 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447221
7222 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7223
7224 // Make sure we sent the cookie in the restarted transaction.
7225 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7226 != std::string::npos);
7227 }
7228
7229 // Same test as above, except this time the restart is initiated earlier
7230 // (without user intervention since identity is embedded in the URL).
7231 {
[email protected]ceefd7fd2012-11-29 00:36:247232 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447233 TestURLRequestContext context(true);
7234 context.set_network_delegate(&network_delegate);
7235 context.Init();
7236
7237 TestDelegate d;
7238
7239 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187240 replacements.SetUsernameStr("user2");
7241 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447242 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7243
danakj8522a25b2016-04-16 00:17:367244 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367245 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197246 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447247
[email protected]255620da2013-08-19 13:14:297248 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447249
7250 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7251
7252 // Make sure we sent the cookie in the restarted transaction.
7253 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7254 != std::string::npos);
7255 }
7256}
7257
[email protected]58e32bb2013-01-21 18:23:257258// Tests that load timing works as expected with auth and the cache.
7259TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557260 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257261
7262 // populate the cache
7263 {
7264 TestDelegate d;
7265 d.set_credentials(AuthCredentials(kUser, kSecret));
7266
danakj8522a25b2016-04-16 00:17:367267 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557268 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197269 r->Start();
[email protected]58e32bb2013-01-21 18:23:257270
[email protected]255620da2013-08-19 13:14:297271 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257272
7273 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7274
7275 LoadTimingInfo load_timing_info_before_auth;
7276 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7277 &load_timing_info_before_auth));
7278 TestLoadTimingNotReused(load_timing_info_before_auth,
7279 CONNECT_TIMING_HAS_DNS_TIMES);
7280
7281 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197282 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257283 // The test server does not support keep alive sockets, so the second
7284 // request with auth should use a new socket.
7285 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7286 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7287 load_timing_info.socket_log_id);
7288 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7289 load_timing_info.connect_timing.connect_start);
7290 }
7291
[email protected]3b23a222013-05-15 21:33:257292 // Repeat request with end-to-end validation. Since auth-basic results in a
7293 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257294 // response should be fetched from the cache.
7295 {
7296 TestDelegate d;
7297 d.set_credentials(AuthCredentials(kUser, kSecret));
7298
danakj8522a25b2016-04-16 00:17:367299 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557300 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197301 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7302 r->Start();
[email protected]58e32bb2013-01-21 18:23:257303
[email protected]255620da2013-08-19 13:14:297304 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257305
7306 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7307
7308 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197309 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257310
[email protected]3b23a222013-05-15 21:33:257311 // Since there was a request that went over the wire, the load timing
7312 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257313 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197314 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257315 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257316 }
7317}
7318
[email protected]316c1e5e2012-09-12 15:17:447319// In this test, we do a POST which the server will 302 redirect.
7320// The subsequent transaction should use GET, and should not send the
7321// Content-Type header.
7322// http://code.google.com/p/chromium/issues/detail?id=843
7323TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557324 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447325
7326 const char kData[] = "hello world";
7327
7328 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367329 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557330 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7331 &d));
[email protected]f7022f32014-08-21 16:32:197332 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077333 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447334
7335 // Set headers (some of which are specific to the POST).
7336 HttpRequestHeaders headers;
7337 headers.AddHeadersFromString(
7338 "Content-Type: multipart/form-data; "
7339 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7340 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7341 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7342 "Accept-Language: en-US,en\r\n"
7343 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7344 "Content-Length: 11\r\n"
7345 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197346 req->SetExtraRequestHeaders(headers);
7347 req->Start();
[email protected]255620da2013-08-19 13:14:297348 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447349
7350 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197351 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447352 EXPECT_EQ("text/html", mime_type);
7353
7354 const std::string& data = d.data_received();
7355
7356 // Check that the post-specific headers were stripped:
7357 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7358 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7359 EXPECT_FALSE(ContainsString(data, "Origin:"));
7360
7361 // These extra request headers should not have been stripped.
7362 EXPECT_TRUE(ContainsString(data, "Accept:"));
7363 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7364 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7365}
7366
jww5fe460ff2015-03-28 00:22:517367// The following tests check that we handle mutating the request for HTTP
7368// redirects as expected.
7369// See https://crbug.com/56373, https://crbug.com/102130, and
7370// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447371
7372TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557373 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447374
tommycli59a63432015-11-06 00:10:557375 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517376 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557377 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447378
7379 HTTPRedirectMethodTest(url, "POST", "GET", true);
7380 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7381 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517382
7383 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7384 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7385 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7386 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7387 std::string());
[email protected]316c1e5e2012-09-12 15:17:447388}
7389
7390TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557391 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447392
tommycli59a63432015-11-06 00:10:557393 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517394 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557395 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447396
7397 HTTPRedirectMethodTest(url, "POST", "GET", true);
7398 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7399 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517400
7401 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7402 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7403 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7404 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7405 std::string());
[email protected]316c1e5e2012-09-12 15:17:447406}
7407
7408TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557409 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447410
tommycli59a63432015-11-06 00:10:557411 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517412 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557413 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447414
7415 HTTPRedirectMethodTest(url, "POST", "GET", true);
7416 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7417 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517418
7419 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7420 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7421 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7422 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7423 std::string());
[email protected]316c1e5e2012-09-12 15:17:447424}
7425
7426TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557427 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447428
tommycli59a63432015-11-06 00:10:557429 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517430 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557431 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447432
7433 HTTPRedirectMethodTest(url, "POST", "POST", true);
7434 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7435 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517436
7437 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7438 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7439 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7440 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447441}
7442
[email protected]0a17aab32014-04-24 03:32:377443TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557444 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377445
tommycli59a63432015-11-06 00:10:557446 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517447 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557448 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377449
7450 HTTPRedirectMethodTest(url, "POST", "POST", true);
7451 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7452 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517453
7454 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7455 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7456 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7457 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377458}
7459
7460// Make sure that 308 responses without bodies are not treated as redirects.
7461// Certain legacy apis that pre-date the response code expect this behavior
7462// (Like Google Drive).
7463TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557464 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377465
7466 TestDelegate d;
tommycli59a63432015-11-06 00:10:557467 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377468
danakj8522a25b2016-04-16 00:17:367469 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367470 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377471
[email protected]f7022f32014-08-21 16:32:197472 request->Start();
[email protected]0a17aab32014-04-24 03:32:377473 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197474 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
7475 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:377476 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197477 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377478 EXPECT_EQ("This is not a redirect.", d.data_received());
7479}
7480
[email protected]f878230e2014-04-03 15:36:147481TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557482 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147483
tommycli59a63432015-11-06 00:10:557484 GURL original_url(
7485 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7486 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147487
7488 TestDelegate d;
7489 {
danakj8522a25b2016-04-16 00:17:367490 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367491 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147492
[email protected]f7022f32014-08-21 16:32:197493 r->Start();
[email protected]f878230e2014-04-03 15:36:147494 base::RunLoop().Run();
7495
[email protected]f7022f32014-08-21 16:32:197496 EXPECT_EQ(2U, r->url_chain().size());
7497 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7498 EXPECT_EQ(OK, r->status().error());
7499 EXPECT_EQ(original_url, r->original_url());
7500 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147501 }
7502}
7503
[email protected]cba24642014-08-15 20:49:597504TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557505 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597506
tommycli59a63432015-11-06 00:10:557507 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597508 GURL first_party_url("http://example.com");
7509
7510 TestDelegate d;
7511 {
danakj8522a25b2016-04-16 00:17:367512 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367513 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197514 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597515
[email protected]f7022f32014-08-21 16:32:197516 r->Start();
[email protected]cba24642014-08-15 20:49:597517 base::RunLoop().Run();
7518
[email protected]f7022f32014-08-21 16:32:197519 EXPECT_EQ(2U, r->url_chain().size());
7520 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7521 EXPECT_EQ(OK, r->status().error());
7522 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597523 }
7524}
7525
7526TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557527 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597528
tommycli59a63432015-11-06 00:10:557529 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597530 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557531 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597532
7533 TestDelegate d;
7534 {
danakj8522a25b2016-04-16 00:17:367535 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367536 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197537 r->set_first_party_for_cookies(original_first_party_url);
7538 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597539 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7540
[email protected]f7022f32014-08-21 16:32:197541 r->Start();
[email protected]cba24642014-08-15 20:49:597542 base::RunLoop().Run();
7543
[email protected]f7022f32014-08-21 16:32:197544 EXPECT_EQ(2U, r->url_chain().size());
7545 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
7546 EXPECT_EQ(OK, r->status().error());
7547 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597548 }
7549}
7550
[email protected]316c1e5e2012-09-12 15:17:447551TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557552 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447553
7554 const char kData[] = "hello world";
7555
7556 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367557 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557558 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197559 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077560 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447561 HttpRequestHeaders headers;
7562 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517563 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197564 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447565
danakj8522a25b2016-04-16 00:17:367566 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557567 req.get(), &default_network_delegate_,
7568 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427569 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7570 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447571
[email protected]f7022f32014-08-21 16:32:197572 req->Start();
[email protected]255620da2013-08-19 13:14:297573 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197574 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447575}
7576
7577TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557578 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447579
7580 const char kData[] = "hello world";
7581
7582 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367583 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557584 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197585 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077586 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447587 HttpRequestHeaders headers;
7588 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517589 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197590 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447591
danakj8522a25b2016-04-16 00:17:367592 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557593 req.get(), &default_network_delegate_,
7594 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097595 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427596 "Very Good Reason"));
7597 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447598
[email protected]f7022f32014-08-21 16:32:197599 req->Start();
[email protected]255620da2013-08-19 13:14:297600 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197601 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447602 EXPECT_EQ(kData, d.data_received());
7603}
7604
7605// Check that default A-L header is sent.
7606TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557607 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447608
[email protected]8790210c2013-12-02 05:29:537609 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247610 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447611 TestURLRequestContext context(true);
7612 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437613 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447614 context.Init();
7615
7616 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367617 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557618 http_test_server()->GetURL("/echoheader?Accept-Language"),
7619 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197620 req->Start();
[email protected]255620da2013-08-19 13:14:297621 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447622 EXPECT_EQ("en", d.data_received());
7623}
7624
7625// Check that an empty A-L header is not sent. http://crbug.com/77365.
7626TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557627 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447628
[email protected]8790210c2013-12-02 05:29:537629 std::string empty_string; // Avoid most vexing parse on line below.
7630 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247631 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447632 TestURLRequestContext context(true);
7633 context.set_network_delegate(&network_delegate);
7634 context.Init();
7635 // We override the language after initialization because empty entries
7636 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437637 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447638
7639 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367640 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557641 http_test_server()->GetURL("/echoheader?Accept-Language"),
7642 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197643 req->Start();
[email protected]255620da2013-08-19 13:14:297644 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447645 EXPECT_EQ("None", d.data_received());
7646}
7647
7648// Check that if request overrides the A-L header, the default is not appended.
7649// See http://crbug.com/20894
7650TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557651 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447652
7653 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367654 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557655 http_test_server()->GetURL("/echoheader?Accept-Language"),
7656 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447657 HttpRequestHeaders headers;
7658 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197659 req->SetExtraRequestHeaders(headers);
7660 req->Start();
[email protected]255620da2013-08-19 13:14:297661 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447662 EXPECT_EQ(std::string("ru"), d.data_received());
7663}
7664
7665// Check that default A-E header is sent.
7666TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557667 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447668
7669 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367670 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557671 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7672 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447673 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197674 req->SetExtraRequestHeaders(headers);
7675 req->Start();
[email protected]255620da2013-08-19 13:14:297676 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447677 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7678}
7679
7680// Check that if request overrides the A-E header, the default is not appended.
7681// See http://crbug.com/47381
7682TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557683 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447684
7685 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367686 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557687 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7688 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447689 HttpRequestHeaders headers;
7690 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197691 req->SetExtraRequestHeaders(headers);
7692 req->Start();
[email protected]255620da2013-08-19 13:14:297693 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447694 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7695 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7696}
7697
[email protected]84f05432013-03-15 01:00:127698// Check that setting the A-C header sends the proper header.
7699TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557700 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447701
7702 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367703 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557704 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7705 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447706 HttpRequestHeaders headers;
7707 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197708 req->SetExtraRequestHeaders(headers);
7709 req->Start();
[email protected]255620da2013-08-19 13:14:297710 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447711 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7712}
7713
7714// Check that default User-Agent header is sent.
7715TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557716 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447717
7718 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367719 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557720 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7721 &d));
[email protected]f7022f32014-08-21 16:32:197722 req->Start();
[email protected]255620da2013-08-19 13:14:297723 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197724 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377725 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447726}
7727
7728// Check that if request overrides the User-Agent header,
7729// the default is not appended.
marqf14fff8d2015-12-02 15:52:297730// TODO(crbug.com/564656) This test is flaky on iOS.
7731#if defined(OS_IOS)
7732#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7733#else
7734#define MAYBE_OverrideUserAgent OverrideUserAgent
7735#endif
7736TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557737 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447738
7739 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367740 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557741 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7742 &d));
[email protected]316c1e5e2012-09-12 15:17:447743 HttpRequestHeaders headers;
7744 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197745 req->SetExtraRequestHeaders(headers);
7746 req->Start();
[email protected]255620da2013-08-19 13:14:297747 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357748 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447749}
7750
[email protected]ee4c30d2012-11-07 15:08:437751// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7752// User-Agent header to be sent but does not send the Accept-Language and
7753// Accept-Charset headers.
7754TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557755 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437756
[email protected]ceefd7fd2012-11-29 00:36:247757 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437758 TestURLRequestContext context(true);
7759 context.set_network_delegate(&network_delegate);
7760 context.Init();
7761 // We override the HttpUserAgentSettings after initialization because empty
7762 // entries get overridden by Init().
7763 context.set_http_user_agent_settings(NULL);
7764
7765 struct {
7766 const char* request;
7767 const char* expected_response;
tommycli59a63432015-11-06 00:10:557768 } tests[] = {{"/echoheader?Accept-Language", "None"},
7769 {"/echoheader?Accept-Charset", "None"},
7770 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437771
viettrungluue4a8b882014-10-16 06:17:387772 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437773 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367774 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557775 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197776 req->Start();
[email protected]255620da2013-08-19 13:14:297777 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437778 EXPECT_EQ(tests[i].expected_response, d.data_received())
7779 << " Request = \"" << tests[i].request << "\"";
7780 }
7781}
7782
[email protected]5033ab82013-03-22 20:17:467783// Make sure that URLRequest passes on its priority updates to
7784// newly-created jobs after the first one.
7785TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557786 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467787
7788 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367789 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557790 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197791 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467792
danakj8522a25b2016-04-16 00:17:367793 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557794 req.get(), &default_network_delegate_,
7795 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427796 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7797 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467798
[email protected]f7022f32014-08-21 16:32:197799 req->SetPriority(LOW);
7800 req->Start();
7801 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467802
mmenkeed0498b2015-12-08 23:20:427803 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367804 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427805 req.get(), &default_network_delegate_, &job_priority));
7806 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467807
7808 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297809 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427810 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467811}
7812
[email protected]80abdad2014-03-15 00:20:547813// Check that creating a network request while entering/exiting suspend mode
7814// fails as it should. This is the only case where an HttpTransactionFactory
7815// does not return an HttpTransaction.
7816TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7817 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367818 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177819 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547820 network_layer->OnSuspend();
7821
dchengc7eeda422015-12-26 03:56:487822 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427823 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547824
7825 TestURLRequestContext context(true);
7826 context.set_http_transaction_factory(&http_cache);
7827 context.Init();
7828
7829 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367830 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367831 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197832 req->Start();
[email protected]80abdad2014-03-15 00:20:547833 base::RunLoop().Run();
7834
7835 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197836 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7837 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547838}
7839
mmenke2281f3762015-11-02 20:38:177840namespace {
[email protected]80abdad2014-03-15 00:20:547841
mmenke2281f3762015-11-02 20:38:177842// HttpTransactionFactory that synchronously fails to create transactions.
7843class FailingHttpTransactionFactory : public HttpTransactionFactory {
7844 public:
7845 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7846 : network_session_(network_session) {}
7847
7848 ~FailingHttpTransactionFactory() override {}
7849
7850 // HttpTransactionFactory methods:
7851 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367852 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177853 return ERR_FAILED;
7854 }
7855
7856 HttpCache* GetCache() override { return nullptr; }
7857
7858 HttpNetworkSession* GetSession() override { return network_session_; }
7859
7860 private:
7861 HttpNetworkSession* network_session_;
7862
7863 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7864};
7865
7866} // namespace
7867
7868// Check that when a request that fails to create an HttpTransaction can be
7869// cancelled while the failure notification is pending, and doesn't send two
7870// failure notifications.
7871//
7872// This currently only happens when in suspend mode and there's no cache, but
7873// just use a special HttpTransactionFactory, to avoid depending on those
7874// behaviors.
7875TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7876 FailingHttpTransactionFactory http_transaction_factory(
7877 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547878 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177879 context.set_http_transaction_factory(&http_transaction_factory);
7880 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547881 context.Init();
7882
7883 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367884 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367885 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177886 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7887 // try to create an HttpNetworkTransaction synchronously on start).
7888 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197889 req->Start();
mmenke2281f3762015-11-02 20:38:177890 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547891 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177892 // Run pending error task, if there is one.
7893 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547894
7895 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177896 EXPECT_EQ(1, d.response_started_count());
7897 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7898
7899 // NetworkDelegate should see the cancellation, but not the error.
7900 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7901 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547902}
7903
ttuttlec0c828492015-05-15 01:25:557904TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557905 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557906
7907 TestDelegate d;
tommycli59a63432015-11-06 00:10:557908 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367909 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557910 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7911
7912 req->Start();
7913 base::RunLoop().Run();
7914
7915 EXPECT_TRUE(req->response_info().network_accessed);
7916}
7917
7918TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557919 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557920
7921 // Populate the cache.
7922 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367923 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557924 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557925 req->Start();
7926 base::RunLoop().Run();
7927
7928 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7929 EXPECT_TRUE(req->response_info().network_accessed);
7930 EXPECT_FALSE(req->response_info().was_cached);
7931
tommycli59a63432015-11-06 00:10:557932 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557933 DEFAULT_PRIORITY, &d);
7934 req->Start();
7935 base::RunLoop().Run();
7936
7937 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7938 EXPECT_FALSE(req->response_info().network_accessed);
7939 EXPECT_TRUE(req->response_info().was_cached);
7940}
7941
7942TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557943 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557944
7945 TestDelegate d;
tommycli59a63432015-11-06 00:10:557946 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367947 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557948 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7949 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7950
7951 req->Start();
7952 base::RunLoop().Run();
7953
7954 EXPECT_FALSE(req->response_info().network_accessed);
7955}
7956
ricea3a1c71f2016-06-17 10:05:267957TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
7958 ASSERT_TRUE(http_test_server()->Start());
7959
7960 TestDelegate d;
7961 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7962 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
7963 req->Start();
7964 base::RunLoop().Run();
7965
7966 EXPECT_EQ(5, req->GetRawBodyBytes());
7967}
7968
7969TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
7970 ASSERT_TRUE(http_test_server()->Start());
7971
7972 TestDelegate d;
7973 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7974 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
7975 req->Start();
7976 base::RunLoop().Run();
7977
7978 EXPECT_EQ(30, req->GetRawBodyBytes());
7979}
7980
bengr1bf8e942014-11-07 01:36:507981class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7982 public:
7983 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7984 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7985 // tests into the factory tests.
7986 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7987 }
7988
7989 void SetUpFactory() override {
7990 interceptor_ = new MockURLRequestInterceptor();
7991 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:367992 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:507993 }
7994
7995 MockURLRequestInterceptor* interceptor() const {
7996 return interceptor_;
7997 }
7998
7999 private:
8000 MockURLRequestInterceptor* interceptor_;
8001};
8002
8003TEST_F(URLRequestInterceptorTestHTTP,
8004 NetworkDelegateNotificationOnRedirectIntercept) {
8005 interceptor()->set_intercept_redirect(true);
8006 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
8007 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
8008
tommycli59a63432015-11-06 00:10:558009 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508010
8011 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368012 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558013 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508014 req->Start();
8015 base::RunLoop().Run();
8016
8017 EXPECT_TRUE(interceptor()->did_intercept_redirect());
8018 // Check we got one good response
8019 EXPECT_TRUE(req->status().is_success());
8020 if (req->status().is_success())
8021 EXPECT_EQ(200, req->response_headers()->response_code());
8022
8023 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8024 EXPECT_EQ(1, d.response_started_count());
8025 EXPECT_EQ(0, d.received_redirect_count());
8026
8027 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008028 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508029 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
8030}
8031
8032TEST_F(URLRequestInterceptorTestHTTP,
8033 NetworkDelegateNotificationOnErrorIntercept) {
8034 // Intercept that error and respond with an OK response.
8035 interceptor()->set_intercept_final_response(true);
8036 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
8037 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
8038 default_network_delegate()->set_can_be_intercepted_on_error(true);
8039
tommycli59a63432015-11-06 00:10:558040 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508041
8042 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368043 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558044 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:368045 &d));
bengr1bf8e942014-11-07 01:36:508046 req->set_method("GET");
8047 req->Start();
8048 base::RunLoop().Run();
8049
8050 EXPECT_TRUE(interceptor()->did_intercept_final());
8051
8052 // Check we received one good response.
8053 EXPECT_TRUE(req->status().is_success());
8054 if (req->status().is_success())
8055 EXPECT_EQ(200, req->response_headers()->response_code());
8056 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
8057 EXPECT_EQ(1, d.response_started_count());
8058 EXPECT_EQ(0, d.received_redirect_count());
8059
8060 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008061 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508062 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
8063}
8064
8065TEST_F(URLRequestInterceptorTestHTTP,
8066 NetworkDelegateNotificationOnResponseIntercept) {
8067 // Intercept that error and respond with an OK response.
8068 interceptor()->set_intercept_final_response(true);
8069
8070 // Intercept with a real URLRequestHttpJob.
8071 interceptor()->set_use_url_request_http_job(true);
8072
tommycli59a63432015-11-06 00:10:558073 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:508074
8075 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368076 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:558077 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:508078 req->set_method("GET");
8079 req->Start();
8080 base::RunLoop().Run();
8081
8082 EXPECT_TRUE(interceptor()->did_intercept_final());
8083
8084 // Check we received one good response.
8085 EXPECT_TRUE(req->status().is_success());
8086 if (req->status().is_success())
8087 EXPECT_EQ(200, req->response_headers()->response_code());
8088 EXPECT_EQ("hello", d.data_received());
8089 EXPECT_EQ(1, d.response_started_count());
8090 EXPECT_EQ(0, d.received_redirect_count());
8091
8092 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:008093 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:508094 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
8095}
8096
mkwst0c5eab872014-11-21 14:18:548097class URLRequestTestReferrerPolicy : public URLRequestTest {
8098 public:
8099 URLRequestTestReferrerPolicy() {}
8100
tommycli59a63432015-11-06 00:10:558101 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
8102 origin_server_.reset(new EmbeddedTestServer(type));
8103 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
8104 origin_server_->AddDefaultHandlers(
8105 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8106 } else {
8107 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8108 }
mkwst0c5eab872014-11-21 14:18:548109 ASSERT_TRUE(origin_server_->Start());
8110 }
8111
tommycli59a63432015-11-06 00:10:558112 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8113 net::EmbeddedTestServer::Type dest_type) {
8114 origin_server_.reset(new EmbeddedTestServer(origin_type));
8115 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8116 origin_server_->AddDefaultHandlers(
8117 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8118 } else {
8119 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8120 }
mkwst0c5eab872014-11-21 14:18:548121 ASSERT_TRUE(origin_server_->Start());
8122
tommycli59a63432015-11-06 00:10:558123 destination_server_.reset(new EmbeddedTestServer(dest_type));
8124 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8125 destination_server_->AddDefaultHandlers(
8126 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8127 } else {
8128 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8129 }
mkwst0c5eab872014-11-21 14:18:548130 ASSERT_TRUE(destination_server_->Start());
8131 }
8132
8133 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8134 const GURL& referrer,
8135 const GURL& expected) {
8136 // Create and execute the request: we'll only have a |destination_server_|
8137 // if the origins are meant to be distinct. Otherwise, we'll use the
8138 // |origin_server_| for both endpoints.
8139 GURL destination_url =
tommycli59a63432015-11-06 00:10:558140 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8141 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548142 GURL origin_url =
tommycli59a63432015-11-06 00:10:558143 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548144
8145 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368146 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368147 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548148 req->set_referrer_policy(policy);
8149 req->SetReferrer(referrer.spec());
8150 req->Start();
8151 base::RunLoop().Run();
8152
8153 EXPECT_EQ(1, d.response_started_count());
8154 EXPECT_EQ(1, d.received_redirect_count());
8155 EXPECT_EQ(destination_url, req->url());
8156 EXPECT_TRUE(req->status().is_success());
8157 EXPECT_EQ(200, req->response_headers()->response_code());
8158
8159 EXPECT_EQ(expected.spec(), req->referrer());
8160 if (expected.is_empty())
8161 EXPECT_EQ("None", d.data_received());
8162 else
8163 EXPECT_EQ(expected.spec(), d.data_received());
8164 }
8165
tommycli59a63432015-11-06 00:10:558166 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548167
8168 private:
danakj8522a25b2016-04-16 00:17:368169 std::unique_ptr<EmbeddedTestServer> origin_server_;
8170 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548171};
8172
8173TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558174 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548175
8176 VerifyReferrerAfterRedirect(
8177 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558178 origin_server()->GetURL("/path/to/file.html"),
8179 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548180
8181 VerifyReferrerAfterRedirect(
8182 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558183 origin_server()->GetURL("/path/to/file.html"),
8184 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548185
8186 VerifyReferrerAfterRedirect(
8187 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558188 origin_server()->GetURL("/path/to/file.html"),
8189 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548190
8191 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558192 origin_server()->GetURL("/path/to/file.html"),
8193 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548194}
8195
tommycli59a63432015-11-06 00:10:558196TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8197 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8198 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548199
8200 VerifyReferrerAfterRedirect(
8201 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558202 origin_server()->GetURL("/path/to/file.html"),
8203 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548204
8205 VerifyReferrerAfterRedirect(
8206 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558207 origin_server()->GetURL("/path/to/file.html"),
8208 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548209
8210 VerifyReferrerAfterRedirect(
8211 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558212 origin_server()->GetURL("/path/to/file.html"),
8213 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548214
8215 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558216 origin_server()->GetURL("/path/to/file.html"),
8217 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548218}
8219
8220TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558221 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548222
8223 VerifyReferrerAfterRedirect(
8224 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558225 origin_server()->GetURL("/path/to/file.html"),
8226 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548227
8228 VerifyReferrerAfterRedirect(
8229 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558230 origin_server()->GetURL("/path/to/file.html"),
8231 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548232
8233 VerifyReferrerAfterRedirect(
8234 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558235 origin_server()->GetURL("/path/to/file.html"),
8236 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548237
8238 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558239 origin_server()->GetURL("/path/to/file.html"),
8240 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548241}
8242
tommycli59a63432015-11-06 00:10:558243TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8244 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8245 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548246
8247 VerifyReferrerAfterRedirect(
8248 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558249 origin_server()->GetURL("/path/to/file.html"),
8250 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548251
8252 VerifyReferrerAfterRedirect(
8253 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558254 origin_server()->GetURL("/path/to/file.html"),
8255 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548256
8257 VerifyReferrerAfterRedirect(
8258 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558259 origin_server()->GetURL("/path/to/file.html"),
8260 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548261
8262 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558263 origin_server()->GetURL("/path/to/file.html"),
8264 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548265}
8266
tommycli59a63432015-11-06 00:10:558267TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8268 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8269 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548270
8271 VerifyReferrerAfterRedirect(
8272 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558273 origin_server()->GetURL("/path/to/file.html"),
8274 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548275
8276 VerifyReferrerAfterRedirect(
8277 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558278 origin_server()->GetURL("/path/to/file.html"),
8279 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548280
8281 VerifyReferrerAfterRedirect(
8282 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558283 origin_server()->GetURL("/path/to/file.html"),
8284 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548285
8286 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558287 origin_server()->GetURL("/path/to/file.html"),
8288 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548289}
8290
tommycli59a63432015-11-06 00:10:558291TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8292 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8293 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548294
8295 VerifyReferrerAfterRedirect(
8296 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558297 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548298
8299 VerifyReferrerAfterRedirect(
8300 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558301 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548302
8303 VerifyReferrerAfterRedirect(
8304 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558305 origin_server()->GetURL("/path/to/file.html"),
8306 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548307
8308 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558309 origin_server()->GetURL("/path/to/file.html"),
8310 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548311}
8312
[email protected]73e0bba2009-02-19 22:57:098313class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508314 public:
[email protected]ef2bf422012-05-11 03:27:098315 HTTPSRequestTest() : default_context_(true) {
8316 default_context_.set_network_delegate(&default_network_delegate_);
8317 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508318 }
dcheng67be2b1f2014-10-27 21:47:298319 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508320
8321 protected:
[email protected]ceefd7fd2012-11-29 00:36:248322 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098323 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468324};
8325
[email protected]c044616e2013-02-20 02:01:268326TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558327 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8328 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228329 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118330 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468331
[email protected]ea224582008-12-07 20:25:468332 TestDelegate d;
8333 {
danakj8522a25b2016-04-16 00:17:368334 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558335 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198336 r->Start();
8337 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468338
[email protected]255620da2013-08-19 13:14:298339 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468340
8341 EXPECT_EQ(1, d.response_started_count());
8342 EXPECT_FALSE(d.received_data_before_response());
8343 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198344 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198345 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198346 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198347 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198348 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468349 }
[email protected]ea224582008-12-07 20:25:468350}
8351
[email protected]5774ada2010-07-15 06:30:548352TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558353 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8354 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8355 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228356 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118357 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338358
8359 bool err_allowed = true;
8360 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8361 TestDelegate d;
8362 {
8363 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368364 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558365 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338366
[email protected]f7022f32014-08-21 16:32:198367 r->Start();
8368 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338369
[email protected]255620da2013-08-19 13:14:298370 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338371
8372 EXPECT_EQ(1, d.response_started_count());
8373 EXPECT_FALSE(d.received_data_before_response());
8374 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178375 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338376 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198377 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178378 } else {
[email protected]bacff652009-03-31 17:50:338379 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178380 }
[email protected]bacff652009-03-31 17:50:338381 }
8382 }
8383}
8384
[email protected]5774ada2010-07-15 06:30:548385TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558386 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8387 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8388 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228389 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118390 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338391
8392 // Iterate from false to true, just so that we do the opposite of the
8393 // previous test in order to increase test coverage.
8394 bool err_allowed = false;
8395 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8396 TestDelegate d;
8397 {
8398 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368399 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558400 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338401
[email protected]f7022f32014-08-21 16:32:198402 r->Start();
8403 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338404
[email protected]255620da2013-08-19 13:14:298405 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338406
8407 EXPECT_EQ(1, d.response_started_count());
8408 EXPECT_FALSE(d.received_data_before_response());
8409 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178410 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338411 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198412 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178413 } else {
[email protected]bacff652009-03-31 17:50:338414 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178415 }
[email protected]bacff652009-03-31 17:50:338416 }
8417 }
8418}
[email protected]73e0bba2009-02-19 22:57:098419
tommycli59a63432015-11-06 00:10:558420// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8421// security state. (see http://crbug.com/550977).
8422#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448423// This tests that a load of www.google.com with a certificate error sets
8424// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8425// the interstitial to be fatal.
8426TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558427 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8428 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8429 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448430 ASSERT_TRUE(test_server.Start());
8431
8432 // We require that the URL be www.google.com in order to pick up the
8433 // preloaded HSTS entries in the TransportSecurityState. This means that we
8434 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248435 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448436
8437 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248438 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448439 TestURLRequestContext context(true);
8440 context.set_network_delegate(&network_delegate);
8441 context.set_host_resolver(&host_resolver);
8442 TransportSecurityState transport_security_state;
8443 context.set_transport_security_state(&transport_security_state);
8444 context.Init();
8445
8446 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368447 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198448 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368449 test_server.host_port_pair().port())),
8450 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448451
[email protected]f7022f32014-08-21 16:32:198452 r->Start();
8453 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448454
[email protected]255620da2013-08-19 13:14:298455 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448456
8457 EXPECT_EQ(1, d.response_started_count());
8458 EXPECT_FALSE(d.received_data_before_response());
8459 EXPECT_TRUE(d.have_certificate_errors());
8460 EXPECT_TRUE(d.certificate_errors_are_fatal());
8461}
8462
8463// This tests that cached HTTPS page loads do not cause any updates to the
8464// TransportSecurityState.
8465TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8466 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8467 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558468 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8469 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8470 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448471 ASSERT_TRUE(test_server.Start());
8472
[email protected]9e6968d2014-05-07 21:46:268473 // We require that the URL be www.google.com in order to pick up the static
8474 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8475 // that we have to use a MockHostResolver in order to direct www.google.com to
8476 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448477
8478 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248479 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448480 TestURLRequestContext context(true);
8481 context.set_network_delegate(&network_delegate);
8482 context.set_host_resolver(&host_resolver);
8483 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268484
martijnc0d6b622015-06-30 19:14:408485 TransportSecurityState::STSState static_sts_state;
8486 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268487 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408488 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448489 context.set_transport_security_state(&transport_security_state);
8490 context.Init();
8491
martijnc0d6b622015-06-30 19:14:408492 TransportSecurityState::STSState dynamic_sts_state;
8493 TransportSecurityState::PKPState dynamic_pkp_state;
8494 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8495 &dynamic_sts_state));
8496 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8497 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268498
[email protected]316c1e5e2012-09-12 15:17:448499 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368500 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198501 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368502 test_server.host_port_pair().port())),
8503 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448504
[email protected]f7022f32014-08-21 16:32:198505 r->Start();
8506 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448507
[email protected]255620da2013-08-19 13:14:298508 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448509
8510 EXPECT_EQ(1, d.response_started_count());
8511 EXPECT_FALSE(d.received_data_before_response());
8512 EXPECT_TRUE(d.have_certificate_errors());
8513 EXPECT_TRUE(d.certificate_errors_are_fatal());
8514
[email protected]9e6968d2014-05-07 21:46:268515 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408516 TransportSecurityState::STSState new_static_sts_state;
8517 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268518 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408519 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8520 TransportSecurityState::STSState new_dynamic_sts_state;
8521 TransportSecurityState::PKPState new_dynamic_pkp_state;
8522 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8523 "www.google.com", &new_dynamic_sts_state));
8524 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8525 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268526
martijnc0d6b622015-06-30 19:14:408527 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8528 EXPECT_EQ(new_static_sts_state.include_subdomains,
8529 static_sts_state.include_subdomains);
8530 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8531 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488532 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8533 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8534 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448535}
8536
[email protected]8ccc69f2012-11-28 19:52:148537// Make sure HSTS preserves a POST request's method and body.
8538TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8539 static const char kData[] = "hello world";
8540
tommycli59a63432015-11-06 00:10:558541 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8542 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228543 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148544 ASSERT_TRUE(test_server.Start());
8545
8546
8547 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8548 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558549 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228550 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148551 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148552
8553 // Force https for www.somewhere.com.
8554 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208555 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8556 bool include_subdomains = false;
8557 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8558 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148559
8560 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8561
8562 TestURLRequestContext context(true);
8563 context.set_host_resolver(&host_resolver);
8564 context.set_transport_security_state(&transport_security_state);
8565 context.set_network_delegate(&network_delegate);
8566 context.Init();
8567
8568 TestDelegate d;
8569 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8570 // cause a certificate error. Ignore the error.
8571 d.set_allow_certificate_errors(true);
8572
danakj8522a25b2016-04-16 00:17:368573 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198574 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368575 test_server.host_port_pair().port())),
8576 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198577 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078578 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148579
[email protected]f7022f32014-08-21 16:32:198580 req->Start();
[email protected]255620da2013-08-19 13:14:298581 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148582
[email protected]f7022f32014-08-21 16:32:198583 EXPECT_EQ("https", req->url().scheme());
8584 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148585 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408586
8587 LoadTimingInfo load_timing_info;
8588 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8589 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8590 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148591}
8592
rob4e0be1f2014-09-11 23:40:228593// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8594TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8595 static const char kOriginHeaderValue[] = "http://www.example.com";
8596
tommycli59a63432015-11-06 00:10:558597 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8598 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228599 ASSERT_TRUE(test_server.Start());
8600
8601 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8602 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558603 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8604 // default.
rob4e0be1f2014-09-11 23:40:228605 MockHostResolver host_resolver;
8606
8607 TransportSecurityState transport_security_state;
8608 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8609 bool include_subdomains = false;
8610 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8611
8612 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8613
8614 MockCertVerifier cert_verifier;
8615 cert_verifier.set_default_result(OK);
8616
8617 TestURLRequestContext context(true);
8618 context.set_host_resolver(&host_resolver);
8619 context.set_transport_security_state(&transport_security_state);
8620 context.set_network_delegate(&network_delegate);
8621 context.set_cert_verifier(&cert_verifier);
8622 context.Init();
8623
8624 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8625 test_server.host_port_pair().port()));
8626 url::Replacements<char> replacements;
8627 const char kNewScheme[] = "https";
8628 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8629 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8630
8631 TestDelegate d;
8632 // Quit on redirect to allow response header inspection upon redirect.
8633 d.set_quit_on_redirect(true);
8634
danakj8522a25b2016-04-16 00:17:368635 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368636 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228637 // Set Origin header to simulate a cross-origin request.
8638 HttpRequestHeaders request_headers;
8639 request_headers.SetHeader("Origin", kOriginHeaderValue);
8640 req->SetExtraRequestHeaders(request_headers);
8641
8642 req->Start();
8643 base::RunLoop().Run();
8644
8645 EXPECT_EQ(1, d.received_redirect_count());
8646
8647 const HttpResponseHeaders* headers = req->response_headers();
8648 std::string redirect_location;
8649 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8650 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8651
8652 std::string received_cors_header;
8653 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8654 &received_cors_header));
8655 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8656}
8657
davidbenb4c25b62016-06-24 02:39:278658// Test that DHE-only servers fail with the expected dedicated error code.
8659TEST_F(HTTPSRequestTest, DHE) {
8660 SpawnedTestServer::SSLOptions ssl_options;
8661 ssl_options.key_exchanges =
8662 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
8663 SpawnedTestServer test_server(
8664 SpawnedTestServer::TYPE_HTTPS, ssl_options,
8665 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8666 ASSERT_TRUE(test_server.Start());
8667
8668 TestDelegate d;
8669 {
8670 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8671 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
8672
8673 r->Start();
8674 EXPECT_TRUE(r->is_pending());
8675
8676 base::RunLoop().Run();
8677
8678 EXPECT_EQ(1, d.response_started_count());
8679 EXPECT_FALSE(r->status().is_success());
8680 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8681 EXPECT_EQ(ERR_SSL_OBSOLETE_CIPHER, r->status().error());
8682 }
8683}
8684
[email protected]316c1e5e2012-09-12 15:17:448685namespace {
8686
8687class SSLClientAuthTestDelegate : public TestDelegate {
8688 public:
8689 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8690 }
dchengb03027d2014-10-21 12:00:208691 void OnCertificateRequested(URLRequest* request,
8692 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448693 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178694 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448695 }
8696 int on_certificate_requested_count() {
8697 return on_certificate_requested_count_;
8698 }
8699 private:
8700 int on_certificate_requested_count_;
8701};
8702
8703} // namespace
8704
8705// TODO(davidben): Test the rest of the code. Specifically,
8706// - Filtering which certificates to select.
8707// - Sending a certificate back.
8708// - Getting a certificate request in an SSL renegotiation sending the
8709// HTTP request.
8710TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558711 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8712 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128713 ssl_config.client_cert_type =
8714 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558715 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8716 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228717 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448718 ASSERT_TRUE(test_server.Start());
8719
8720 SSLClientAuthTestDelegate d;
8721 {
danakj8522a25b2016-04-16 00:17:368722 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558723 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448724
[email protected]f7022f32014-08-21 16:32:198725 r->Start();
8726 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448727
[email protected]255620da2013-08-19 13:14:298728 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448729
8730 EXPECT_EQ(1, d.on_certificate_requested_count());
8731 EXPECT_FALSE(d.received_data_before_response());
8732 EXPECT_EQ(0, d.bytes_received());
8733
8734 // Send no certificate.
8735 // TODO(davidben): Get temporary client cert import (with keys) working on
8736 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548737 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448738
[email protected]255620da2013-08-19 13:14:298739 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448740
8741 EXPECT_EQ(1, d.response_started_count());
8742 EXPECT_FALSE(d.received_data_before_response());
8743 EXPECT_NE(0, d.bytes_received());
8744 }
8745}
8746
8747TEST_F(HTTPSRequestTest, ResumeTest) {
8748 // Test that we attempt a session resume when making two connections to the
8749 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228750 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448751 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228752 SpawnedTestServer test_server(
8753 SpawnedTestServer::TYPE_HTTPS,
8754 ssl_options,
8755 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448756 ASSERT_TRUE(test_server.Start());
8757
8758 SSLClientSocket::ClearSessionCache();
8759
8760 {
8761 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368762 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368763 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448764
[email protected]f7022f32014-08-21 16:32:198765 r->Start();
8766 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448767
[email protected]255620da2013-08-19 13:14:298768 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448769
8770 EXPECT_EQ(1, d.response_started_count());
8771 }
8772
8773 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8774 CloseAllConnections();
8775
8776 {
8777 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368778 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368779 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448780
[email protected]f7022f32014-08-21 16:32:198781 r->Start();
8782 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448783
[email protected]255620da2013-08-19 13:14:298784 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448785
8786 // The response will look like;
8787 // insert abc
8788 // lookup abc
8789 // insert xyz
8790 //
8791 // With a newline at the end which makes the split think that there are
8792 // four lines.
8793
8794 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298795 std::vector<std::string> lines = base::SplitString(
8796 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448797 ASSERT_EQ(4u, lines.size()) << d.data_received();
8798
8799 std::string session_id;
8800
8801 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298802 std::vector<std::string> parts = base::SplitString(
8803 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448804 ASSERT_EQ(2u, parts.size());
8805 if (i == 0) {
8806 EXPECT_EQ("insert", parts[0]);
8807 session_id = parts[1];
8808 } else {
8809 EXPECT_EQ("lookup", parts[0]);
8810 EXPECT_EQ(session_id, parts[1]);
8811 }
8812 }
8813 }
8814}
8815
Adam Langley32352ad2014-10-14 22:31:008816// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8817// the result of fetching "ssl-session-cache" from the test server, indicates
8818// that exactly two different sessions were inserted, with no lookups etc.
8819static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298820 std::vector<std::string> lines = base::SplitString(
8821 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008822 ASSERT_EQ(3u, lines.size()) << session_info;
8823
8824 std::string session_id;
8825 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298826 std::vector<std::string> parts = base::SplitString(
8827 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008828 ASSERT_EQ(2u, parts.size());
8829 EXPECT_EQ("insert", parts[0]);
8830 if (i == 0) {
8831 session_id = parts[1];
8832 } else {
8833 EXPECT_NE(session_id, parts[1]);
8834 }
8835 }
8836}
8837
[email protected]316c1e5e2012-09-12 15:17:448838TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8839 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8840 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228841 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448842 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228843 SpawnedTestServer test_server(
8844 SpawnedTestServer::TYPE_HTTPS,
8845 ssl_options,
8846 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448847 ASSERT_TRUE(test_server.Start());
8848
8849 SSLClientSocket::ClearSessionCache();
8850
8851 {
8852 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368853 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368854 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448855
[email protected]f7022f32014-08-21 16:32:198856 r->Start();
8857 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448858
[email protected]255620da2013-08-19 13:14:298859 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448860
8861 EXPECT_EQ(1, d.response_started_count());
8862 }
8863
8864 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8865 HttpNetworkSession::Params params;
8866 params.host_resolver = default_context_.host_resolver();
8867 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118868 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:208869 params.cert_transparency_verifier =
8870 default_context_.cert_transparency_verifier();
8871 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:448872 params.proxy_service = default_context_.proxy_service();
8873 params.ssl_config_service = default_context_.ssl_config_service();
8874 params.http_auth_handler_factory =
8875 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:448876 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448877
mmenkee65e7af2015-10-13 17:16:428878 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:368879 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428880 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448881
8882 default_context_.set_http_transaction_factory(cache.get());
8883
8884 {
8885 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368886 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368887 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448888
[email protected]f7022f32014-08-21 16:32:198889 r->Start();
8890 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448891
[email protected]255620da2013-08-19 13:14:298892 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448893
8894 // The response will look like;
8895 // insert abc
8896 // insert xyz
8897 //
8898 // With a newline at the end which makes the split think that there are
8899 // three lines.
8900
8901 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008902 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448903 }
8904}
8905
Adam Langley32352ad2014-10-14 22:31:008906class FallbackTestURLRequestContext : public TestURLRequestContext {
8907 public:
8908 explicit FallbackTestURLRequestContext(bool delay_initialization)
8909 : TestURLRequestContext(delay_initialization) {}
8910
avibf0746c2015-12-09 19:53:148911 void set_fallback_min_version(uint16_t version) {
nharperb7441ef2016-01-25 23:54:148912 TestSSLConfigService* ssl_config_service = new TestSSLConfigService(
8913 true /* check for EV */, false /* online revocation checking */,
8914 false /* require rev. checking for local
8915 anchors */,
8916 false /* token binding enabled */);
Adam Langley32352ad2014-10-14 22:31:008917 ssl_config_service->set_fallback_min_version(version);
8918 set_ssl_config_service(ssl_config_service);
8919 }
8920};
8921
[email protected]48d2b7c52014-06-27 01:16:558922class HTTPSFallbackTest : public testing::Test {
8923 public:
Adam Langley32352ad2014-10-14 22:31:008924 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298925 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558926
8927 protected:
8928 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8929 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008930 context_.Init();
8931 delegate_.set_allow_certificate_errors(true);
8932
[email protected]48d2b7c52014-06-27 01:16:558933 SpawnedTestServer test_server(
8934 SpawnedTestServer::TYPE_HTTPS,
8935 ssl_options,
8936 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8937 ASSERT_TRUE(test_server.Start());
8938
tommycli59a63432015-11-06 00:10:558939 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8940 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558941 request_->Start();
8942
8943 base::RunLoop().Run();
8944 }
8945
avibf0746c2015-12-09 19:53:148946 void set_fallback_min_version(uint16_t version) {
Adam Langley32352ad2014-10-14 22:31:008947 context_.set_fallback_min_version(version);
8948 }
8949
[email protected]48d2b7c52014-06-27 01:16:558950 void ExpectConnection(int version) {
8951 EXPECT_EQ(1, delegate_.response_started_count());
8952 EXPECT_NE(0, delegate_.bytes_received());
8953 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8954 request_->ssl_info().connection_status));
8955 EXPECT_TRUE(request_->ssl_info().connection_status &
8956 SSL_CONNECTION_VERSION_FALLBACK);
8957 }
8958
8959 void ExpectFailure(int error) {
8960 EXPECT_EQ(1, delegate_.response_started_count());
8961 EXPECT_FALSE(request_->status().is_success());
8962 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8963 EXPECT_EQ(error, request_->status().error());
8964 }
8965
8966 private:
8967 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:008968 FallbackTestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:368969 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:558970};
8971
davidbenb127ca82015-06-15 19:05:428972// Tests the TLS 1.0 fallback doesn't happen.
8973TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558974 SpawnedTestServer::SSLOptions ssl_options(
8975 SpawnedTestServer::SSLOptions::CERT_OK);
8976 ssl_options.tls_intolerant =
8977 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8978
8979 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558980 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:428981}
8982
davidben3b267512016-02-24 19:46:558983// Tests the TLS 1.1 fallback doesn't happen but 1.2-intolerance is detected.
8984TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:428985 SpawnedTestServer::SSLOptions ssl_options(
8986 SpawnedTestServer::SSLOptions::CERT_OK);
8987 ssl_options.tls_intolerant =
8988 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8989
8990 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558991 ExpectFailure(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION);
8992}
8993
8994// Tests the TLS 1.1 fallback when explicitly enabled.
8995TEST_F(HTTPSFallbackTest, TLSv1_1Fallback) {
8996 SpawnedTestServer::SSLOptions ssl_options(
8997 SpawnedTestServer::SSLOptions::CERT_OK);
8998 ssl_options.tls_intolerant =
8999 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
9000
9001 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
9002 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:429003 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
9004}
9005
davidben3b267512016-02-24 19:46:559006// Tests that the TLS 1.1 fallback, if enabled, triggers on closed connections.
davidbenb127ca82015-06-15 19:05:429007TEST_F(HTTPSFallbackTest, TLSv1_1FallbackClosed) {
davidbenb127ca82015-06-15 19:05:429008 SpawnedTestServer::SSLOptions ssl_options(
9009 SpawnedTestServer::SSLOptions::CERT_OK);
9010 ssl_options.tls_intolerant =
9011 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
9012 ssl_options.tls_intolerance_type =
9013 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
9014
davidben3b267512016-02-24 19:46:559015 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
davidbenb127ca82015-06-15 19:05:429016 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
9017 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:559018}
9019
9020// This test is disabled on Android because the remote test server doesn't cause
9021// a TCP reset.
9022#if !defined(OS_ANDROID)
davidben3b267512016-02-24 19:46:559023// Tests fallback to TLS 1.1, if enabled, on connection reset.
davidbenb127ca82015-06-15 19:05:429024TEST_F(HTTPSFallbackTest, TLSv1_1FallbackReset) {
[email protected]48d2b7c52014-06-27 01:16:559025 SpawnedTestServer::SSLOptions ssl_options(
9026 SpawnedTestServer::SSLOptions::CERT_OK);
9027 ssl_options.tls_intolerant =
davidbenb127ca82015-06-15 19:05:429028 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
[email protected]48d2b7c52014-06-27 01:16:559029 ssl_options.tls_intolerance_type =
9030 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
9031
davidben3b267512016-02-24 19:46:559032 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:559033 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidbenb127ca82015-06-15 19:05:429034 ExpectConnection(SSL_CONNECTION_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:559035}
9036#endif // !OS_ANDROID
9037
davidben3b267512016-02-24 19:46:559038// Tests that we don't fallback, even if enabled, on handshake failure with
9039// servers that implement TLS_FALLBACK_SCSV. Also ensure that the original error
9040// code is reported.
[email protected]48d2b7c52014-06-27 01:16:559041TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:559042 SpawnedTestServer::SSLOptions ssl_options(
9043 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:439044 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:559045 // a version fallback.
9046 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:439047 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:559048 // Have the server process TLS_FALLBACK_SCSV so that version fallback
9049 // connections are rejected.
9050 ssl_options.fallback_scsv_enabled = true;
9051
davidben3b267512016-02-24 19:46:559052 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]48d2b7c52014-06-27 01:16:559053 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
9054
9055 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
9056 // intolerance. If the fallback SCSV is processed when the original error
9057 // that caused the fallback should be returned, which should be
9058 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
9059 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
9060}
9061
davidben3b267512016-02-24 19:46:559062// Tests that we don't fallback, even if enabled, on connection closed with
9063// servers that implement TLS_FALLBACK_SCSV. Also ensure that the original error
9064// code is reported.
[email protected]12833302014-07-02 01:57:319065TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:319066 SpawnedTestServer::SSLOptions ssl_options(
9067 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:439068 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:319069 // a version fallback.
9070 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:439071 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:319072 ssl_options.tls_intolerance_type =
9073 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
9074 // Have the server process TLS_FALLBACK_SCSV so that version fallback
9075 // connections are rejected.
9076 ssl_options.fallback_scsv_enabled = true;
9077
davidben3b267512016-02-24 19:46:559078 set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
[email protected]12833302014-07-02 01:57:319079 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
9080
9081 // The original error should be replayed on rejected fallback.
9082 ExpectFailure(ERR_CONNECTION_CLOSED);
9083}
9084
davidbenb937d6c2015-05-14 04:53:429085// Test that fallback probe connections don't cause sessions to be cached.
9086TEST_F(HTTPSRequestTest, FallbackProbeNoCache) {
Adam Langley32352ad2014-10-14 22:31:009087 SpawnedTestServer::SSLOptions ssl_options(
9088 SpawnedTestServer::SSLOptions::CERT_OK);
9089 ssl_options.tls_intolerant =
davidben3b267512016-02-24 19:46:559090 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
Adam Langley32352ad2014-10-14 22:31:009091 ssl_options.tls_intolerance_type =
9092 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
9093 ssl_options.record_resume = true;
9094
9095 SpawnedTestServer test_server(
9096 SpawnedTestServer::TYPE_HTTPS,
9097 ssl_options,
9098 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9099 ASSERT_TRUE(test_server.Start());
9100
9101 SSLClientSocket::ClearSessionCache();
9102
davidben3b267512016-02-24 19:46:559103 // Make a connection that does a probe fallback to TLSv1.1 but fails because
9104 // fallback is disabled. We don't wish a session for this connection to be
9105 // inserted locally.
Adam Langley32352ad2014-10-14 22:31:009106 {
9107 TestDelegate delegate;
9108 FallbackTestURLRequestContext context(true);
9109
9110 context.Init();
danakj8522a25b2016-04-16 00:17:369111 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:559112 test_server.GetURL("/"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:009113 request->Start();
9114
9115 base::RunLoop().Run();
9116
9117 EXPECT_EQ(1, delegate.response_started_count());
9118 EXPECT_FALSE(request->status().is_success());
9119 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
9120 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
9121 request->status().error());
9122 }
9123
davidben3b267512016-02-24 19:46:559124 // Now allow TLSv1.1 fallback connections and request the session cache log.
Adam Langley32352ad2014-10-14 22:31:009125 {
9126 TestDelegate delegate;
9127 FallbackTestURLRequestContext context(true);
davidben3b267512016-02-24 19:46:559128 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1_1);
Adam Langley32352ad2014-10-14 22:31:009129
9130 context.Init();
danakj8522a25b2016-04-16 00:17:369131 std::unique_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:369132 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:009133 request->Start();
9134
9135 base::RunLoop().Run();
9136
9137 EXPECT_EQ(1, delegate.response_started_count());
9138 EXPECT_NE(0, delegate.bytes_received());
davidbenb937d6c2015-05-14 04:53:429139 EXPECT_EQ(
davidben3b267512016-02-24 19:46:559140 SSL_CONNECTION_VERSION_TLS1_1,
davidbenb937d6c2015-05-14 04:53:429141 SSLConnectionStatusToVersion(request->ssl_info().connection_status));
Adam Langley32352ad2014-10-14 22:31:009142 EXPECT_TRUE(request->ssl_info().connection_status &
9143 SSL_CONNECTION_VERSION_FALLBACK);
9144
9145 std::vector<std::string> lines;
9146 // If no sessions were cached then the server should have seen two sessions
9147 // inserted with no lookups.
9148 AssertTwoDistinctSessionsInserted(delegate.data_received());
9149 }
9150}
9151
[email protected]a8fed1742013-12-27 02:14:249152class HTTPSSessionTest : public testing::Test {
9153 public:
9154 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:599155 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249156
9157 default_context_.set_network_delegate(&default_network_delegate_);
9158 default_context_.set_cert_verifier(&cert_verifier_);
9159 default_context_.Init();
9160 }
dcheng67be2b1f2014-10-27 21:47:299161 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:249162
9163 protected:
9164 MockCertVerifier cert_verifier_;
9165 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
9166 TestURLRequestContext default_context_;
9167};
9168
9169// Tests that session resumption is not attempted if an invalid certificate
9170// is presented.
9171TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
9172 SpawnedTestServer::SSLOptions ssl_options;
9173 ssl_options.record_resume = true;
9174 SpawnedTestServer test_server(
9175 SpawnedTestServer::TYPE_HTTPS,
9176 ssl_options,
9177 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
9178 ASSERT_TRUE(test_server.Start());
9179
9180 SSLClientSocket::ClearSessionCache();
9181
9182 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:599183 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:249184 {
9185 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369186 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369187 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249188
[email protected]f7022f32014-08-21 16:32:199189 r->Start();
9190 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249191
9192 base::RunLoop().Run();
9193
9194 EXPECT_EQ(1, d.response_started_count());
9195 }
9196
9197 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
9198 CloseAllConnections();
9199
9200 // Now change the certificate to be acceptable (so that the response is
9201 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:599202 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:249203 {
9204 TestDelegate d;
danakj8522a25b2016-04-16 00:17:369205 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:369206 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:249207
[email protected]f7022f32014-08-21 16:32:199208 r->Start();
9209 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:249210
9211 base::RunLoop().Run();
9212
9213 // The response will look like;
9214 // insert abc
9215 // insert xyz
9216 //
9217 // With a newline at the end which makes the split think that there are
9218 // three lines.
9219 //
9220 // If a session was presented (eg: a bug), then the response would look
9221 // like;
9222 // insert abc
9223 // lookup abc
9224 // insert xyz
9225
9226 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:009227 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:249228 }
9229}
9230
[email protected]dffe8242012-03-20 15:14:279231// This the fingerprint of the "Testing CA" certificate used by the testserver.
9232// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:269233static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:279234 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
9235 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
9236
[email protected]51523f52013-07-31 21:57:289237// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
9238// testserver.
9239static const SHA256HashValue kOCSPTestCertSPKI = { {
9240 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
9241 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
9242 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
9243 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
9244} };
9245
[email protected]dffe8242012-03-20 15:14:279246// This is the policy OID contained in the certificates that testserver
9247// generates.
9248static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
9249
9250class HTTPSOCSPTest : public HTTPSRequestTest {
9251 public:
9252 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:099253 : context_(true),
[email protected]b6f2de32012-08-17 04:35:089254 ev_test_policy_(
9255 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
9256 kOCSPTestCertFingerprint,
9257 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:029258 }
9259
dcheng67be2b1f2014-10-27 21:47:299260 void SetUp() override {
rsleevid6de8302016-06-21 01:33:209261 context_.SetCTPolicyEnforcer(
9262 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
9263 SetupContext();
[email protected]ef2bf422012-05-11 03:27:099264 context_.Init();
[email protected]dffe8242012-03-20 15:14:279265
[email protected]cba24642014-08-15 20:49:599266 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:209267 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:429268 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:509269 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:279270
svaldez2135be52016-04-20 16:34:539271#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:099272 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:279273 EnsureNSSHttpIOInit();
9274#endif
9275 }
9276
[email protected]ce7d0cbc2013-05-03 18:57:229277 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:279278 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:539279 // We always overwrite out_cert_status.
9280 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:229281 SpawnedTestServer test_server(
9282 SpawnedTestServer::TYPE_HTTPS,
9283 ssl_options,
9284 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:279285 ASSERT_TRUE(test_server.Start());
9286
9287 TestDelegate d;
9288 d.set_allow_certificate_errors(true);
danakj8522a25b2016-04-16 00:17:369289 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:559290 context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199291 r->Start();
[email protected]dffe8242012-03-20 15:14:279292
[email protected]255620da2013-08-19 13:14:299293 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:279294
9295 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:199296 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:279297 }
9298
dcheng67be2b1f2014-10-27 21:47:299299 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:539300#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:279301 ShutdownNSSHttpIO();
9302#endif
9303 }
9304
[email protected]a13234c2012-03-20 21:45:029305 protected:
rsleevid6de8302016-06-21 01:33:209306 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9307 public:
9308 AllowAnyCertCTPolicyEnforcer() = default;
9309 ~AllowAnyCertCTPolicyEnforcer() override = default;
9310
9311 ct::CertPolicyCompliance DoesConformToCertPolicy(
9312 X509Certificate* cert,
9313 const SCTList& verified_scts,
9314 const BoundNetLog& net_log) override {
9315 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9316 }
9317
9318 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9319 X509Certificate* cert,
9320 const ct::EVCertsWhitelist* ev_whitelist,
9321 const SCTList& verified_scts,
9322 const BoundNetLog& net_log) override {
9323 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9324 }
9325 };
[email protected]a13234c2012-03-20 21:45:029326 // SetupContext configures the URLRequestContext that will be used for making
9327 // connetions to testserver. This can be overridden in test subclasses for
9328 // different behaviour.
rsleevid6de8302016-06-21 01:33:209329 virtual void SetupContext() {
9330 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149331 true /* check for EV */, true /* online revocation checking */,
9332 false /* require rev. checking for local
9333 anchors */,
9334 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029335 }
9336
danakj8522a25b2016-04-16 00:17:369337 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099338 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369339 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279340};
9341
[email protected]a13234c2012-03-20 21:45:029342static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:019343#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029344 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9345 // have that ability on other platforms.
9346 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9347#else
9348 return 0;
9349#endif
9350}
9351
[email protected]3a86a712013-07-30 07:16:209352// SystemSupportsHardFailRevocationChecking returns true iff the current
9353// operating system supports revocation checking and can distinguish between
9354// situations where a given certificate lacks any revocation information (eg:
9355// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9356// revocation information cannot be obtained (eg: the CRL was unreachable).
9357// If it does not, then tests which rely on 'hard fail' behaviour should be
9358// skipped.
9359static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539360#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209361 return true;
9362#else
9363 return false;
9364#endif
9365}
9366
[email protected]a13234c2012-03-20 21:45:029367// SystemUsesChromiumEVMetadata returns true iff the current operating system
9368// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9369// several tests are effected because our testing EV certificate won't be
9370// recognised as EV.
9371static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329372#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579373 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9374 return false;
[email protected]e1b2d732014-03-28 16:20:329375#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9376 // On OS X and Android, we use the system to tell us whether a certificate is
9377 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019378 return false;
9379#else
9380 return true;
9381#endif
9382}
9383
[email protected]b6f2de32012-08-17 04:35:089384static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339385#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029386 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9387 return false;
9388#else
9389 return true;
9390#endif
9391}
9392
davidbend1fb2f12014-11-08 02:51:009393static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339394#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039395 return true;
mathpc992e602015-10-21 20:34:039396#else
9397 return false;
9398#endif
davidbend1fb2f12014-11-08 02:51:009399}
9400
[email protected]dffe8242012-03-20 15:14:279401TEST_F(HTTPSOCSPTest, Valid) {
9402 if (!SystemSupportsOCSP()) {
9403 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9404 return;
9405 }
9406
[email protected]ce7d0cbc2013-05-03 18:57:229407 SpawnedTestServer::SSLOptions ssl_options(
9408 SpawnedTestServer::SSLOptions::CERT_AUTO);
9409 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279410
[email protected]924e9f92012-12-16 22:00:539411 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129412 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279413
9414 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9415
[email protected]a13234c2012-03-20 21:45:029416 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9417 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279418
9419 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9420}
9421
9422TEST_F(HTTPSOCSPTest, Revoked) {
9423 if (!SystemSupportsOCSP()) {
9424 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9425 return;
9426 }
9427
[email protected]ce7d0cbc2013-05-03 18:57:229428 SpawnedTestServer::SSLOptions ssl_options(
9429 SpawnedTestServer::SSLOptions::CERT_AUTO);
9430 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279431
9432 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129433 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279434
[email protected]a592c0432012-12-01 18:10:299435#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279436 // Doesn't pass on OS X yet for reasons that need to be investigated.
9437 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9438#endif
9439 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9440 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9441}
9442
9443TEST_F(HTTPSOCSPTest, Invalid) {
9444 if (!SystemSupportsOCSP()) {
9445 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9446 return;
9447 }
9448
[email protected]ce7d0cbc2013-05-03 18:57:229449 SpawnedTestServer::SSLOptions ssl_options(
9450 SpawnedTestServer::SSLOptions::CERT_AUTO);
9451 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:279452
[email protected]924e9f92012-12-16 22:00:539453 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129454 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279455
[email protected]a13234c2012-03-20 21:45:029456 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279457 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279458
9459 // Without a positive OCSP response, we shouldn't show the EV status.
9460 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9461 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9462}
[email protected]a13234c2012-03-20 21:45:029463
davidbend1fb2f12014-11-08 02:51:009464TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039465 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009466 LOG(WARNING)
9467 << "Skipping test because system doesn't support OCSP stapling";
9468 return;
9469 }
9470
9471 SpawnedTestServer::SSLOptions ssl_options(
9472 SpawnedTestServer::SSLOptions::CERT_AUTO);
9473 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9474 ssl_options.staple_ocsp_response = true;
9475 ssl_options.ocsp_server_unavailable = true;
9476
9477 CertStatus cert_status;
9478 DoConnection(ssl_options, &cert_status);
9479
9480 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9481
9482 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9483 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9484
9485 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9486}
9487
davidben6c3191b2014-11-21 22:38:049488// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489489#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049490#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9491#else
9492#define MAYBE_RevokedStapled RevokedStapled
9493#endif
9494TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039495 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009496 LOG(WARNING)
9497 << "Skipping test because system doesn't support OCSP stapling";
9498 return;
9499 }
9500
9501 SpawnedTestServer::SSLOptions ssl_options(
9502 SpawnedTestServer::SSLOptions::CERT_AUTO);
9503 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9504 ssl_options.staple_ocsp_response = true;
9505 ssl_options.ocsp_server_unavailable = true;
9506
9507 CertStatus cert_status;
9508 DoConnection(ssl_options, &cert_status);
9509
9510 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9511 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9512 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9513}
9514
[email protected]3a86a712013-07-30 07:16:209515class HTTPSHardFailTest : public HTTPSOCSPTest {
9516 protected:
rsleevid6de8302016-06-21 01:33:209517 void SetupContext() override {
9518 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149519 false /* check for EV */, false /* online revocation checking */,
9520 true /* require rev. checking for local
9521 anchors */,
9522 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209523 }
9524};
9525
[email protected]3a86a712013-07-30 07:16:209526TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9527 if (!SystemSupportsOCSP()) {
9528 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9529 return;
9530 }
9531
9532 if (!SystemSupportsHardFailRevocationChecking()) {
9533 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9534 << "revocation checking";
9535 return;
9536 }
9537
9538 SpawnedTestServer::SSLOptions ssl_options(
9539 SpawnedTestServer::SSLOptions::CERT_AUTO);
9540 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9541
9542 CertStatus cert_status;
9543 DoConnection(ssl_options, &cert_status);
9544
9545 EXPECT_EQ(CERT_STATUS_REVOKED,
9546 cert_status & CERT_STATUS_REVOKED);
9547
9548 // Without a positive OCSP response, we shouldn't show the EV status.
9549 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9550}
9551
[email protected]a13234c2012-03-20 21:45:029552class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9553 protected:
rsleevid6de8302016-06-21 01:33:209554 void SetupContext() override {
9555 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149556 true /* check for EV */, false /* online revocation checking */,
9557 false /* require rev. checking for local
9558 anchors */,
9559 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029560 }
9561};
9562
9563TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9564 if (!SystemSupportsOCSP()) {
9565 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9566 return;
9567 }
9568
[email protected]ce7d0cbc2013-05-03 18:57:229569 SpawnedTestServer::SSLOptions ssl_options(
9570 SpawnedTestServer::SSLOptions::CERT_AUTO);
9571 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029572 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9573
[email protected]924e9f92012-12-16 22:00:539574 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129575 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029576
9577 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9578 cert_status & CERT_STATUS_ALL_ERRORS);
9579
9580 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089581 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9582 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029583}
9584
[email protected]be0fff62013-08-29 23:37:489585TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9586 if (!SystemSupportsOCSP()) {
9587 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9588 return;
9589 }
9590
9591 SpawnedTestServer::SSLOptions ssl_options(
9592 SpawnedTestServer::SSLOptions::CERT_AUTO);
9593 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9594 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9595
9596 CertStatus cert_status;
9597 DoConnection(ssl_options, &cert_status);
9598
9599 // Currently only works for Windows. When using NSS or OS X, it's not
9600 // possible to determine whether the check failed because of actual
9601 // revocation or because there was an OCSP failure.
9602#if defined(OS_WIN)
9603 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9604#else
9605 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9606#endif
9607
9608 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9609 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9610 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9611}
9612
[email protected]a13234c2012-03-20 21:45:029613TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9614 if (!SystemSupportsOCSP()) {
9615 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9616 return;
9617 }
9618
[email protected]ce7d0cbc2013-05-03 18:57:229619 SpawnedTestServer::SSLOptions ssl_options(
9620 SpawnedTestServer::SSLOptions::CERT_AUTO);
9621 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029622 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9623
9624 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129625 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029626
9627 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9628
9629 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9630 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089631 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9632 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029633}
9634
9635TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9636 if (!SystemSupportsOCSP()) {
9637 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9638 return;
9639 }
9640
[email protected]ce7d0cbc2013-05-03 18:57:229641 SpawnedTestServer::SSLOptions ssl_options(
9642 SpawnedTestServer::SSLOptions::CERT_AUTO);
9643 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029644 SSLConfigService::SetCRLSet(
9645 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9646
9647 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129648 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029649
9650 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9651 cert_status & CERT_STATUS_ALL_ERRORS);
9652
9653 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089654 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9655 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029656}
9657
[email protected]51523f52013-07-31 21:57:289658TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9659 if (!SystemSupportsOCSP()) {
9660 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9661 return;
9662 }
9663
9664 SpawnedTestServer::SSLOptions ssl_options(
9665 SpawnedTestServer::SSLOptions::CERT_AUTO);
9666 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
9667 SSLConfigService::SetCRLSet(
9668 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9669 false, &kOCSPTestCertSPKI, "")));
9670
9671 CertStatus cert_status;
9672 DoConnection(ssl_options, &cert_status);
9673
9674 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9675 // revocation check for EV.
9676 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9677 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9678 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9679 EXPECT_FALSE(
9680 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9681}
9682
9683TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9684 if (!SystemSupportsOCSP()) {
9685 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9686 return;
9687 }
9688
[email protected]ce7d0cbc2013-05-03 18:57:229689 SpawnedTestServer::SSLOptions ssl_options(
9690 SpawnedTestServer::SSLOptions::CERT_AUTO);
9691 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029692 SSLConfigService::SetCRLSet(
9693 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9694
[email protected]51523f52013-07-31 21:57:289695 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129696 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029697
[email protected]51523f52013-07-31 21:57:289698 // Even with a fresh CRLSet, we should still do online revocation checks when
9699 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9700 // test.
9701 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9702 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029703
[email protected]51523f52013-07-31 21:57:289704 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029705 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289706 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029707}
9708
[email protected]b6f2de32012-08-17 04:35:089709TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9710 // Test that when EV verification is requested, but online revocation
9711 // checking is disabled, and the leaf certificate is not in fact EV, that
9712 // no revocation checking actually happens.
9713 if (!SystemSupportsOCSP()) {
9714 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9715 return;
9716 }
9717
9718 // Unmark the certificate's OID as EV, which should disable revocation
9719 // checking (as per the user preference)
9720 ev_test_policy_.reset();
9721
[email protected]ce7d0cbc2013-05-03 18:57:229722 SpawnedTestServer::SSLOptions ssl_options(
9723 SpawnedTestServer::SSLOptions::CERT_AUTO);
9724 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089725 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]b6f2de32012-08-17 04:35:089730
9731 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9732
9733 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9734 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9735}
9736
[email protected]a13234c2012-03-20 21:45:029737class HTTPSCRLSetTest : public HTTPSOCSPTest {
9738 protected:
rsleevid6de8302016-06-21 01:33:209739 void SetupContext() override {
9740 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149741 false /* check for EV */, false /* online revocation checking */,
9742 false /* require rev. checking for local
9743 anchors */,
9744 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029745 }
9746};
9747
9748TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229749 SpawnedTestServer::SSLOptions ssl_options(
9750 SpawnedTestServer::SSLOptions::CERT_AUTO);
9751 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:029752 SSLConfigService::SetCRLSet(
9753 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9754
[email protected]924e9f92012-12-16 22:00:539755 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129756 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029757
9758 // If we're not trying EV verification then, even if the CRLSet has expired,
9759 // we don't fall back to online revocation checks.
9760 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9761 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9762 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9763}
[email protected]51523f52013-07-31 21:57:289764
9765TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309766#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289767 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9768 return;
9769#endif
9770
9771 SpawnedTestServer::SSLOptions ssl_options(
9772 SpawnedTestServer::SSLOptions::CERT_AUTO);
9773 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9774 ssl_options.cert_serial = 10;
9775 SSLConfigService::SetCRLSet(
9776 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9777 false, &kOCSPTestCertSPKI, "\x0a")));
9778
9779 CertStatus cert_status = 0;
9780 DoConnection(ssl_options, &cert_status);
9781
9782 // If the certificate is recorded as revoked in the CRLSet, that should be
9783 // reflected without online revocation checking.
9784 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9785 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9786 EXPECT_FALSE(
9787 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9788}
[email protected]316c1e5e2012-09-12 15:17:449789#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279790
mmenke9f2ec60c2015-06-01 20:59:479791#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9792// These tests aren't passing on Android. Either the RemoteTestServer isn't
9793// starting up successfully, or it can't access the test files.
9794// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319795class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119796 public:
[email protected]d9fca99a2012-02-24 16:16:209797 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479798 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559799 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9800 SpawnedTestServer::kLocalhost,
9801 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479802 // Can't use |default_context_|'s HostResolver to set up the
9803 // FTPTransactionFactory because it hasn't been created yet.
9804 default_context_.set_host_resolver(&host_resolver_);
9805 }
9806
9807 // URLRequestTest interface:
9808 void SetUpFactory() override {
9809 // Add FTP support to the default URLRequestContext.
9810 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209811 "ftp",
danakj8522a25b2016-04-16 00:17:369812 base::WrapUnique(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479813 }
9814
9815 std::string GetTestFileContents() {
9816 base::FilePath path;
9817 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9818 path = path.Append(kTestFilePath);
9819 path = path.AppendASCII(kFtpTestFile);
9820 std::string contents;
9821 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9822 return contents;
[email protected]95409e12010-08-17 20:07:119823 }
9824
[email protected]b89ca032009-08-31 21:41:319825 protected:
mmenke9f2ec60c2015-06-01 20:59:479826 MockHostResolver host_resolver_;
9827 FtpNetworkLayer ftp_transaction_factory_;
9828
tommycli59a63432015-11-06 00:10:559829 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319830};
9831
[email protected]d2a133182012-08-05 16:44:089832// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099833TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089834 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089835
9836 TestDelegate d;
9837 {
danakj8522a25b2016-04-16 00:17:369838 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:369839 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199840 r->Start();
9841 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089842
[email protected]255620da2013-08-19 13:14:299843 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089844
[email protected]f7022f32014-08-21 16:32:199845 EXPECT_FALSE(r->is_pending());
9846 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
9847 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:089848 }
9849}
9850
mmenke9f2ec60c2015-06-01 20:59:479851TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559852 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119853
[email protected]a25e90e2009-09-09 17:05:379854 TestDelegate d;
9855 {
danakj8522a25b2016-04-16 00:17:369856 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559857 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199858 r->Start();
9859 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379860
[email protected]255620da2013-08-19 13:14:299861 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379862
[email protected]f7022f32014-08-21 16:32:199863 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379864 EXPECT_EQ(1, d.response_started_count());
9865 EXPECT_FALSE(d.received_data_before_response());
9866 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559867 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199868 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559869 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199870 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379871 }
9872}
9873
mmenke9f2ec60c2015-06-01 20:59:479874TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559875 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119876
[email protected]dd265012009-01-08 20:45:279877 TestDelegate d;
9878 {
danakj8522a25b2016-04-16 00:17:369879 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559880 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199881 r->Start();
9882 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279883
[email protected]255620da2013-08-19 13:14:299884 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279885
[email protected]f7022f32014-08-21 16:32:199886 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279887 EXPECT_EQ(1, d.response_started_count());
9888 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479889 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559890 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199891 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559892 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199893 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279894 }
9895}
9896
mmenke9f2ec60c2015-06-01 20:59:479897TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559898 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119899
[email protected]dd265012009-01-08 20:45:279900 TestDelegate d;
9901 {
danakj8522a25b2016-04-16 00:17:369902 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559903 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9904 "chrome"),
9905 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199906 r->Start();
9907 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279908
[email protected]255620da2013-08-19 13:14:299909 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279910
[email protected]f7022f32014-08-21 16:32:199911 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479912 EXPECT_EQ(1, d.response_started_count());
9913 EXPECT_FALSE(d.received_data_before_response());
9914 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559915 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199916 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559917 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199918 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259919
9920 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199921 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259922 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279923 }
9924}
9925
mmenke9f2ec60c2015-06-01 20:59:479926TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559927 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119928
[email protected]dd265012009-01-08 20:45:279929 TestDelegate d;
9930 {
danakj8522a25b2016-04-16 00:17:369931 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559932 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9933 "wrong_password"),
davidben151423e2015-03-23 18:48:369934 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199935 r->Start();
9936 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279937
[email protected]255620da2013-08-19 13:14:299938 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279939
[email protected]f7022f32014-08-21 16:32:199940 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279941 EXPECT_EQ(1, d.response_started_count());
9942 EXPECT_FALSE(d.received_data_before_response());
9943 EXPECT_EQ(d.bytes_received(), 0);
9944 }
9945}
9946
mmenke9f2ec60c2015-06-01 20:59:479947TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559948 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119949
[email protected]8b8a197d2009-08-26 15:57:589950 TestDelegate d;
9951 // Set correct login credentials. The delegate will be asked for them when
9952 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589953 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589954 {
danakj8522a25b2016-04-16 00:17:369955 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559956 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9957 "wrong_password"),
davidben151423e2015-03-23 18:48:369958 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199959 r->Start();
9960 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589961
[email protected]255620da2013-08-19 13:14:299962 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589963
[email protected]f7022f32014-08-21 16:32:199964 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589965 EXPECT_EQ(1, d.response_started_count());
9966 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479967 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589968 }
9969}
9970
mmenke9f2ec60c2015-06-01 20:59:479971TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559972 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119973
[email protected]dd265012009-01-08 20:45:279974 TestDelegate d;
9975 {
danakj8522a25b2016-04-16 00:17:369976 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559977 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9978 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479979 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199980 r->Start();
9981 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279982
[email protected]255620da2013-08-19 13:14:299983 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279984
[email protected]f7022f32014-08-21 16:32:199985 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279986 EXPECT_EQ(1, d.response_started_count());
9987 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479988 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279989 }
9990}
[email protected]8b8a197d2009-08-26 15:57:589991
mmenke9f2ec60c2015-06-01 20:59:479992TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559993 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119994
[email protected]8b8a197d2009-08-26 15:57:589995 TestDelegate d;
9996 // Set correct login credentials. The delegate will be asked for them when
9997 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589998 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589999 {
danakj8522a25b2016-04-16 00:17:3610000 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510001 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10002 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710003 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910004 r->Start();
10005 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810006
[email protected]255620da2013-08-19 13:14:2910007 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810008
[email protected]f7022f32014-08-21 16:32:1910009 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810010 EXPECT_EQ(1, d.response_started_count());
10011 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710012 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810013 }
10014}
[email protected]60a3df52009-09-22 16:13:2410015
mmenke9f2ec60c2015-06-01 20:59:4710016TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510017 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110018
danakj8522a25b2016-04-16 00:17:3610019 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410020 {
10021 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610022 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510023 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10024 "chrome"),
10025 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910026 r->Start();
10027 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410028
[email protected]255620da2013-08-19 13:14:2910029 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410030
[email protected]f7022f32014-08-21 16:32:1910031 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410032 EXPECT_EQ(1, d->response_started_count());
10033 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710034 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410035 }
10036
10037 d.reset(new TestDelegate);
10038 {
10039 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610040 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510041 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910042 r->Start();
10043 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410044
[email protected]255620da2013-08-19 13:14:2910045 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410046
[email protected]f7022f32014-08-21 16:32:1910047 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410048 EXPECT_EQ(1, d->response_started_count());
10049 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710050 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410051 }
10052}
10053
mmenke9f2ec60c2015-06-01 20:59:4710054TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510055 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110056
danakj8522a25b2016-04-16 00:17:3610057 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410058 // Set correct login credentials. The delegate will be asked for them when
10059 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810060 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410061 {
danakj8522a25b2016-04-16 00:17:3610062 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510063 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10064 "wrong_password"),
davidben151423e2015-03-23 18:48:3610065 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910066 r->Start();
10067 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410068
[email protected]255620da2013-08-19 13:14:2910069 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410070
[email protected]f7022f32014-08-21 16:32:1910071 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410072 EXPECT_EQ(1, d->response_started_count());
10073 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710074 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410075 }
10076
10077 // Use a new delegate without explicit credentials. The cached ones should be
10078 // used.
10079 d.reset(new TestDelegate);
10080 {
10081 // Don't pass wrong credentials in the URL, they would override valid cached
10082 // ones.
danakj8522a25b2016-04-16 00:17:3610083 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510084 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910085 r->Start();
10086 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410087
[email protected]255620da2013-08-19 13:14:2910088 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410089
[email protected]f7022f32014-08-21 16:32:1910090 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410091 EXPECT_EQ(1, d->response_started_count());
10092 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710093 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410094 }
10095}
ricea3a1c71f2016-06-17 10:05:2610096
10097TEST_F(URLRequestTestFTP, RawBodyBytes) {
10098 ASSERT_TRUE(ftp_test_server_.Start());
10099
10100 TestDelegate d;
10101 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10102 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10103 req->Start();
10104 base::RunLoop().Run();
10105
10106 EXPECT_EQ(6, req->GetRawBodyBytes());
10107}
10108
[email protected]316c1e5e2012-09-12 15:17:4410109#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110110
ttuttlec0c828492015-05-15 01:25:5510111TEST_F(URLRequestTest, NetworkAccessedClearBeforeNetworkStart) {
10112 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610113 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510114 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10115 d.set_quit_on_network_start(true);
10116
10117 EXPECT_FALSE(req->response_info().network_accessed);
10118
10119 req->Start();
10120 base::RunLoop().Run();
10121
10122 EXPECT_EQ(1, d.received_before_network_start_count());
10123 EXPECT_EQ(0, d.response_started_count());
10124 EXPECT_FALSE(req->response_info().network_accessed);
10125
10126 req->ResumeNetworkStart();
10127 base::RunLoop().Run();
10128}
10129
10130TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10131 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610132 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510133 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10134
10135 EXPECT_FALSE(req->response_info().network_accessed);
10136
10137 req->Start();
10138 base::RunLoop().Run();
10139
10140 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10141 EXPECT_FALSE(req->response_info().network_accessed);
10142}
10143
10144TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10145 MockHostResolver host_resolver;
10146 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10147 TestURLRequestContext context(true);
10148 context.set_network_delegate(&network_delegate);
10149 context.set_host_resolver(&host_resolver);
10150 host_resolver.rules()->AddSimulatedFailure("*");
10151 context.Init();
10152
10153 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610154 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510155 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10156
10157 EXPECT_FALSE(req->response_info().network_accessed);
10158
10159 req->Start();
10160 base::RunLoop().Run();
10161 EXPECT_TRUE(req->response_info().network_accessed);
10162}
10163
mmenkeed0498b2015-12-08 23:20:4210164// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210165// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210166TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210167 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610168 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210169 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10170
danakj8522a25b2016-04-16 00:17:3610171 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210172 req.get(), &default_network_delegate_,
10173 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210174 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10175 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210176
10177 req->Start();
10178 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210179 base::RunLoop().RunUntilIdle();
10180 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
10181 EXPECT_EQ(0, d.received_redirect_count());
10182}
10183
[email protected]7461a402011-03-24 23:19:5110184} // namespace net