blob: 7a5805bc73efef4e40a78290ac41abde01708f26 [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"
robpercival214763f2016-07-01 23:27:0196#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:2197#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:4398#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:5099#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:34100#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43101#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52102#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50103#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14104#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50105#include "net/url_request/url_request_intercepting_job_factory.h"
106#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49107#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51108#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47109#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44110#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01111#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52112#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15113#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52114
[email protected]02494ec2014-05-07 15:05:29115#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55116#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29117#include "net/url_request/file_protocol_handler.h"
118#include "net/url_request/url_request_file_dir_job.h"
119#endif
120
mmenke9f2ec60c2015-06-01 20:59:47121#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
122#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29123#include "net/url_request/ftp_protocol_handler.h"
124#endif
125
[email protected]dffe8242012-03-20 15:14:27126#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48127#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56128#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27129#endif
130
robpercival214763f2016-07-01 23:27:01131using net::test::IsError;
132using net::test::IsOk;
133
[email protected]ad65a3e2013-12-25 18:18:01134using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33135using base::Time;
halton.huoe4e45742014-12-08 07:55:46136using std::string;
[email protected]e1acf6f2008-10-27 20:43:33137
[email protected]7461a402011-03-24 23:19:51138namespace net {
139
initial.commit586acc5fe2008-07-26 22:42:52140namespace {
141
[email protected]42cba2fb2013-03-29 19:58:57142const base::string16 kChrome(ASCIIToUTF16("chrome"));
143const base::string16 kSecret(ASCIIToUTF16("secret"));
144const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44145
mmenke9f2ec60c2015-06-01 20:59:47146const base::FilePath::CharType kTestFilePath[] =
147 FILE_PATH_LITERAL("net/data/url_request_unittest");
148
149#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
150// Test file used in most FTP tests.
151const char kFtpTestFile[] = "BullRunSpeech.txt";
152#endif
153
[email protected]2bba3252013-04-08 19:50:59154// Tests load timing information in the case a fresh connection was used, with
155// no proxy.
[email protected]cba24642014-08-15 20:49:59156void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25157 int connect_timing_flags) {
158 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59159 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25160
161 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
162 EXPECT_FALSE(load_timing_info.request_start.is_null());
163
164 EXPECT_LE(load_timing_info.request_start,
165 load_timing_info.connect_timing.connect_start);
166 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
167 connect_timing_flags);
168 EXPECT_LE(load_timing_info.connect_timing.connect_end,
169 load_timing_info.send_start);
170 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
171 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
172
[email protected]58e32bb2013-01-21 18:23:25173 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
174 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
175}
176
[email protected]2bba3252013-04-08 19:50:59177// Same as above, but with proxy times.
178void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59179 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59180 int connect_timing_flags) {
181 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59182 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59183
184 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
185 EXPECT_FALSE(load_timing_info.request_start.is_null());
186
187 EXPECT_LE(load_timing_info.request_start,
188 load_timing_info.proxy_resolve_start);
189 EXPECT_LE(load_timing_info.proxy_resolve_start,
190 load_timing_info.proxy_resolve_end);
191 EXPECT_LE(load_timing_info.proxy_resolve_end,
192 load_timing_info.connect_timing.connect_start);
193 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
194 connect_timing_flags);
195 EXPECT_LE(load_timing_info.connect_timing.connect_end,
196 load_timing_info.send_start);
197 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
198 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
199}
200
201// Same as above, but with a reused socket and proxy times.
202void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59203 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59204 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59205 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59206
207 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
208 EXPECT_FALSE(load_timing_info.request_start.is_null());
209
210 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
211
212 EXPECT_LE(load_timing_info.request_start,
213 load_timing_info.proxy_resolve_start);
214 EXPECT_LE(load_timing_info.proxy_resolve_start,
215 load_timing_info.proxy_resolve_end);
216 EXPECT_LE(load_timing_info.proxy_resolve_end,
217 load_timing_info.send_start);
218 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
219 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
220}
221
xunjielia6888202015-04-14 21:34:25222#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25223// Tests load timing information in the case of a cache hit, when no cache
224// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17225base::StringPiece TestNetResourceProvider(int key) {
226 return "header";
227}
228
229void FillBuffer(char* buffer, size_t len) {
230 static bool called = false;
231 if (!called) {
232 called = true;
233 int seed = static_cast<int>(Time::Now().ToInternalValue());
234 srand(seed);
235 }
236
237 for (size_t i = 0; i < len; i++) {
238 buffer[i] = static_cast<char>(rand());
239 if (!buffer[i])
240 buffer[i] = 'g';
241 }
242}
xunjielia6888202015-04-14 21:34:25243#endif
[email protected]e3a85452013-11-14 01:46:17244
[email protected]3b23a222013-05-15 21:33:25245void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59246 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25247 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59248 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25249
250 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
251 EXPECT_FALSE(load_timing_info.request_start.is_null());
252
253 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
254 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
255 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
256 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
257
258 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
259 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
260}
261
mmenke9f2ec60c2015-06-01 20:59:47262#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25263// Tests load timing in the case that there is no HTTP response. This can be
264// used to test in the case of errors or non-HTTP requests.
265void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59266 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25267 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59268 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25269
270 // Only the request times should be non-null.
271 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
272 EXPECT_FALSE(load_timing_info.request_start.is_null());
273
274 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
275
276 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
277 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
278 EXPECT_TRUE(load_timing_info.send_start.is_null());
279 EXPECT_TRUE(load_timing_info.send_end.is_null());
280 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
281}
xunjielia6888202015-04-14 21:34:25282#endif
[email protected]58e32bb2013-01-21 18:23:25283
mmenkefb18c772015-09-30 22:22:50284// Test power monitor source that can simulate entering suspend mode. Can't use
285// the one in base/ because it insists on bringing its own MessageLoop.
286class TestPowerMonitorSource : public base::PowerMonitorSource {
287 public:
288 TestPowerMonitorSource() {}
289 ~TestPowerMonitorSource() override {}
290
291 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
292
293 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
294
295 bool IsOnBatteryPowerImpl() override { return false; }
296
297 private:
298 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
299};
300
mmenkeed0498b2015-12-08 23:20:42301// Job that allows monitoring of its priority.
302class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
303 public:
304 // The latest priority of the job is always written to |request_priority_|.
305 PriorityMonitoringURLRequestJob(URLRequest* request,
306 NetworkDelegate* network_delegate,
307 RequestPriority* request_priority)
308 : URLRequestTestJob(request, network_delegate),
309 request_priority_(request_priority) {
310 *request_priority_ = DEFAULT_PRIORITY;
311 }
312
313 void SetPriority(RequestPriority priority) override {
314 *request_priority_ = priority;
315 URLRequestTestJob::SetPriority(priority);
316 }
317
318 private:
319 RequestPriority* const request_priority_;
320};
321
[email protected]71c64f62008-11-15 04:36:51322// Do a case-insensitive search through |haystack| for |needle|.
323bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50324 std::string::const_iterator it = std::search(
325 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
326 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51327 return it != haystack.end();
328}
329
danakj8522a25b2016-04-16 00:17:36330std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
331 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28332 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48333 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23334}
335
[email protected]96adadb2010-08-28 01:16:17336// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51337void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17338 // -1 means unknown. 0 means no encryption.
339 EXPECT_GT(ssl_info.security_bits, 0);
340
341 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14342 uint16_t cipher_suite =
343 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29344 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17345}
346
[email protected]79e1fd62013-06-20 06:50:04347void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
348 const GURL& host_url) {
349 std::string sent_value;
350
351 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
352 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
353
354 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
355 EXPECT_EQ("keep-alive", sent_value);
356}
357
[email protected]dc5a5cf2012-09-26 02:49:30358// A network delegate that allows the user to choose a subset of request stages
359// to block in. When blocking, the delegate can do one of the following:
360// * synchronously return a pre-specified error code, or
361// * asynchronously return that value via an automatically called callback,
362// or
363// * block and wait for the user to do a callback.
364// Additionally, the user may also specify a redirect URL -- then each request
365// with the current URL different from the redirect target will be redirected
366// to that target, in the on-before-URL-request stage, independent of whether
367// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12368class BlockingNetworkDelegate : public TestNetworkDelegate {
369 public:
[email protected]dc5a5cf2012-09-26 02:49:30370 // Stages in which the delegate can block.
371 enum Stage {
[email protected]9045b8822012-01-13 20:35:35372 NOT_BLOCKED = 0,
373 ON_BEFORE_URL_REQUEST = 1 << 0,
374 ON_BEFORE_SEND_HEADERS = 1 << 1,
375 ON_HEADERS_RECEIVED = 1 << 2,
376 ON_AUTH_REQUIRED = 1 << 3
377 };
378
[email protected]dc5a5cf2012-09-26 02:49:30379 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59380 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30381 enum BlockMode {
382 SYNCHRONOUS, // No callback, returns specified return values.
383 AUTO_CALLBACK, // |this| posts a task to run the callback using the
384 // specified return codes.
385 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
386 // |auth_retval_| are ignored. In every blocking stage the
387 // message loop is quit.
388 };
389
390 // Creates a delegate which does not block at all.
391 explicit BlockingNetworkDelegate(BlockMode block_mode);
392
393 // For users to trigger a callback returning |response|.
394 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
395 // Only call if |block_mode_| == USER_CALLBACK.
396 void DoCallback(int response);
397 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
398
399 // Setters.
400 void set_retval(int retval) {
401 ASSERT_NE(USER_CALLBACK, block_mode_);
402 ASSERT_NE(ERR_IO_PENDING, retval);
403 ASSERT_NE(OK, retval);
404 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35405 }
406
[email protected]dc5a5cf2012-09-26 02:49:30407 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
408 // |auth_credentials_| will be passed with the response.
409 void set_auth_retval(AuthRequiredResponse auth_retval) {
410 ASSERT_NE(USER_CALLBACK, block_mode_);
411 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
412 auth_retval_ = auth_retval;
413 }
414 void set_auth_credentials(const AuthCredentials& auth_credentials) {
415 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35416 }
417
[email protected]dc5a5cf2012-09-26 02:49:30418 void set_redirect_url(const GURL& url) {
419 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35420 }
421
[email protected]dc5a5cf2012-09-26 02:49:30422 void set_block_on(int block_on) {
423 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35424 }
425
[email protected]dc5a5cf2012-09-26 02:49:30426 // Allows the user to check in which state did we block.
427 Stage stage_blocked_for_callback() const {
428 EXPECT_EQ(USER_CALLBACK, block_mode_);
429 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35430 }
431
432 private:
[email protected]dc5a5cf2012-09-26 02:49:30433 void RunCallback(int response, const CompletionCallback& callback);
434 void RunAuthCallback(AuthRequiredResponse response,
435 const AuthCallback& callback);
436
[email protected]9045b8822012-01-13 20:35:35437 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20438 int OnBeforeURLRequest(URLRequest* request,
439 const CompletionCallback& callback,
440 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35441
ryansturm2343cb62016-06-15 01:09:00442 int OnBeforeStartTransaction(URLRequest* request,
443 const CompletionCallback& callback,
444 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35445
dchengb03027d2014-10-21 12:00:20446 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35447 URLRequest* request,
448 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32449 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16450 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13451 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35452
dchengb03027d2014-10-21 12:00:20453 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35454 URLRequest* request,
455 const AuthChallengeInfo& auth_info,
456 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13457 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35458
[email protected]dc5a5cf2012-09-26 02:49:30459 // Resets the callbacks and |stage_blocked_for_callback_|.
460 void Reset();
[email protected]9045b8822012-01-13 20:35:35461
[email protected]dc5a5cf2012-09-26 02:49:30462 // Checks whether we should block in |stage|. If yes, returns an error code
463 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
464 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
465
466 // Configuration parameters, can be adjusted by public methods:
467 const BlockMode block_mode_;
468
469 // Values returned on blocking stages when mode is SYNCHRONOUS or
470 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
471 int retval_; // To be returned in non-auth stages.
472 AuthRequiredResponse auth_retval_;
473
[email protected]5f714132014-03-26 10:41:16474 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30475 int block_on_; // Bit mask: in which stages to block.
476
477 // |auth_credentials_| will be copied to |*target_auth_credential_| on
478 // callback.
479 AuthCredentials auth_credentials_;
480 AuthCredentials* target_auth_credentials_;
481
482 // Internal variables, not set by not the user:
483 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
484 // USER_CALLBACK).
485 Stage stage_blocked_for_callback_;
486
487 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35488 CompletionCallback callback_;
489 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30490
491 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
492
493 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35494};
495
[email protected]dc5a5cf2012-09-26 02:49:30496BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
497 : block_mode_(block_mode),
498 retval_(OK),
499 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
500 block_on_(0),
501 target_auth_credentials_(NULL),
502 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32503 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30504}
505
506void BlockingNetworkDelegate::DoCallback(int response) {
507 ASSERT_EQ(USER_CALLBACK, block_mode_);
508 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
509 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
510 CompletionCallback callback = callback_;
511 Reset();
512 RunCallback(response, callback);
513}
514
515void BlockingNetworkDelegate::DoAuthCallback(
516 NetworkDelegate::AuthRequiredResponse response) {
517 ASSERT_EQ(USER_CALLBACK, block_mode_);
518 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
519 AuthCallback auth_callback = auth_callback_;
520 Reset();
521 RunAuthCallback(response, auth_callback);
522}
523
524void BlockingNetworkDelegate::RunCallback(int response,
525 const CompletionCallback& callback) {
526 callback.Run(response);
527}
528
529void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
530 const AuthCallback& callback) {
531 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
532 ASSERT_TRUE(target_auth_credentials_ != NULL);
533 *target_auth_credentials_ = auth_credentials_;
534 }
535 callback.Run(response);
536}
537
538int BlockingNetworkDelegate::OnBeforeURLRequest(
539 URLRequest* request,
540 const CompletionCallback& callback,
541 GURL* new_url) {
542 if (redirect_url_ == request->url())
543 return OK; // We've already seen this request and redirected elsewhere.
544
545 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
546
547 if (!redirect_url_.is_empty())
548 *new_url = redirect_url_;
549
550 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
551}
552
ryansturm2343cb62016-06-15 01:09:00553int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30554 URLRequest* request,
555 const CompletionCallback& callback,
556 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00557 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30558
559 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
560}
561
562int BlockingNetworkDelegate::OnHeadersReceived(
563 URLRequest* request,
564 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32565 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16566 scoped_refptr<HttpResponseHeaders>* override_response_headers,
567 GURL* allowed_unsafe_redirect_url) {
568 TestNetworkDelegate::OnHeadersReceived(request,
569 callback,
570 original_response_headers,
571 override_response_headers,
572 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30573
574 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
575}
576
577NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
578 URLRequest* request,
579 const AuthChallengeInfo& auth_info,
580 const AuthCallback& callback,
581 AuthCredentials* credentials) {
582 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
583 credentials);
584 // Check that the user has provided callback for the previous blocked stage.
585 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
586
587 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
588 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
589 }
590
591 target_auth_credentials_ = credentials;
592
593 switch (block_mode_) {
594 case SYNCHRONOUS:
595 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
596 *target_auth_credentials_ = auth_credentials_;
597 return auth_retval_;
598
599 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45600 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30601 FROM_HERE,
602 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
603 weak_factory_.GetWeakPtr(), auth_retval_, callback));
604 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
605
606 case USER_CALLBACK:
607 auth_callback_ = callback;
608 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45609 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17610 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30611 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
612 }
613 NOTREACHED();
614 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
615}
616
617void BlockingNetworkDelegate::Reset() {
618 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
619 stage_blocked_for_callback_ = NOT_BLOCKED;
620 callback_.Reset();
621 auth_callback_.Reset();
622}
623
624int BlockingNetworkDelegate::MaybeBlockStage(
625 BlockingNetworkDelegate::Stage stage,
626 const CompletionCallback& callback) {
627 // Check that the user has provided callback for the previous blocked stage.
628 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
629
630 if ((block_on_ & stage) == 0) {
631 return OK;
632 }
633
634 switch (block_mode_) {
635 case SYNCHRONOUS:
636 EXPECT_NE(OK, retval_);
637 return retval_;
638
639 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45640 base::ThreadTaskRunnerHandle::Get()->PostTask(
641 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
642 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30643 return ERR_IO_PENDING;
644
645 case USER_CALLBACK:
646 callback_ = callback;
647 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45648 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17649 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30650 return ERR_IO_PENDING;
651 }
652 NOTREACHED();
653 return 0;
654}
655
[email protected]d5a4dd62012-05-23 01:41:04656class TestURLRequestContextWithProxy : public TestURLRequestContext {
657 public:
658 // Does not own |delegate|.
659 TestURLRequestContextWithProxy(const std::string& proxy,
660 NetworkDelegate* delegate)
661 : TestURLRequestContext(true) {
662 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
663 set_network_delegate(delegate);
664 Init();
665 }
dchengb03027d2014-10-21 12:00:20666 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04667};
668
stefanocsbd5be5202016-06-10 03:37:55669// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01670// URI and report to be sent.
671class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55672 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01673 public:
674 MockCertificateReportSender() {}
675 ~MockCertificateReportSender() override {}
676
677 void Send(const GURL& report_uri, const std::string& report) override {
678 latest_report_uri_ = report_uri;
679 latest_report_ = report;
680 }
681
estarkf2979122016-04-05 17:04:39682 void SetErrorCallback(
683 const base::Callback<void(const GURL&, int)>& error_callback) override {}
684
estark06e0dac2015-08-07 21:56:01685 const GURL& latest_report_uri() { return latest_report_uri_; }
686 const std::string& latest_report() { return latest_report_; }
687
688 private:
689 GURL latest_report_uri_;
690 std::string latest_report_;
691};
692
estarkcd39c11f2015-10-19 19:46:36693class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
694 public:
695 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34696 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36697};
698
dadrian612337a2016-07-20 22:36:58699// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
700// This is needed because after the certificate failure, the URLRequest will
701// retry the connection, and return a partial SSLInfo with a cached cert status.
702// The partial SSLInfo does not have the OCSP information filled out.
703class OCSPErrorTestDelegate : public TestDelegate {
704 public:
705 void OnSSLCertificateError(URLRequest* request,
706 const SSLInfo& ssl_info,
707 bool fatal) override {
708 ssl_info_ = ssl_info;
709 on_ssl_certificate_error_called_ = true;
710 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
711 }
712
713 bool on_ssl_certificate_error_called() {
714 return on_ssl_certificate_error_called_;
715 }
716
717 SSLInfo ssl_info() { return ssl_info_; }
718
719 private:
720 bool on_ssl_certificate_error_called_ = false;
721 SSLInfo ssl_info_;
722};
723
[email protected]d5a4dd62012-05-23 01:41:04724} // namespace
725
[email protected]a592c0432012-12-01 18:10:29726// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48727class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00728 public:
[email protected]ef2bf422012-05-11 03:27:09729 URLRequestTest() : default_context_(true) {
730 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25731 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50732 job_factory_impl_ = new URLRequestJobFactoryImpl();
733 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50734 }
bengr1bf8e942014-11-07 01:36:50735
dcheng67be2b1f2014-10-27 21:47:29736 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18737 // URLRequestJobs may post clean-up tasks on destruction.
738 base::RunLoop().RunUntilIdle();
739 }
[email protected]87a09a92011-07-14 15:50:50740
dcheng2339883c2014-12-23 00:23:05741 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50742 SetUpFactory();
743 default_context_.set_job_factory(job_factory_.get());
744 default_context_.Init();
745 PlatformTest::SetUp();
746 }
747
748 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20749 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36750 "data", base::WrapUnique(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50751#if !defined(DISABLE_FILE_SUPPORT)
752 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36753 "file", base::WrapUnique(new FileProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:20754 base::ThreadTaskRunnerHandle::Get())));
bengr1bf8e942014-11-07 01:36:50755#endif
756 }
757
758 TestNetworkDelegate* default_network_delegate() {
759 return &default_network_delegate_;
760 }
761
762 const TestURLRequestContext& default_context() const {
763 return default_context_;
764 }
765
766
[email protected]3c5ca8c2011-09-29 01:14:51767 // Adds the TestJobInterceptor to the default context.
768 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23769 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20770 job_factory_impl_->SetProtocolHandler("http", nullptr);
771 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36772 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23773 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51774 }
775
[email protected]87a09a92011-07-14 15:50:50776 protected:
vishal.b62985ca92015-04-17 08:45:51777 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24778 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50779 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36780 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09781 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48782};
783
[email protected]316c1e5e2012-09-12 15:17:44784TEST_F(URLRequestTest, AboutBlankTest) {
785 TestDelegate d;
786 {
danakj8522a25b2016-04-16 00:17:36787 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36788 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44789
[email protected]f7022f32014-08-21 16:32:19790 r->Start();
791 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44792
[email protected]255620da2013-08-19 13:14:29793 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44794
[email protected]f7022f32014-08-21 16:32:19795 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44796 EXPECT_FALSE(d.received_data_before_response());
797 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19798 EXPECT_EQ("", r->GetSocketAddress().host());
799 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04800
801 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19802 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44803 }
804}
805
806TEST_F(URLRequestTest, DataURLImageTest) {
807 TestDelegate d;
808 {
809 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36810 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
811 GURL("data:image/png;base64,"
812 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
813 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
814 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
815 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
816 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
817 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
818 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
819 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
820 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
821 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
822 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
823 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
824 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
825 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
826 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
827 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
828 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
829 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
830 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36831 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44832
[email protected]f7022f32014-08-21 16:32:19833 r->Start();
834 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44835
[email protected]255620da2013-08-19 13:14:29836 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44837
[email protected]f7022f32014-08-21 16:32:19838 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44839 EXPECT_FALSE(d.received_data_before_response());
840 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19841 EXPECT_EQ("", r->GetSocketAddress().host());
842 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04843
844 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19845 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44846 }
847}
848
[email protected]5ecf7cb282014-05-11 01:49:55849#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44850TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15851 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04852
853#if defined(OS_ANDROID)
854 // Android devices are not guaranteed to be able to read /proc/self/exe
855 // Use /etc/hosts instead
856 app_path = base::FilePath("/etc/hosts");
857#else
[email protected]316c1e5e2012-09-12 15:17:44858 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04859#endif // OS_ANDROID
860
[email protected]316c1e5e2012-09-12 15:17:44861 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]316c1e5e2012-09-12 15:17:44867
[email protected]f7022f32014-08-21 16:32:19868 r->Start();
869 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44870
[email protected]255620da2013-08-19 13:14:29871 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44872
avibf0746c2015-12-09 19:53:14873 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49874 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44875
[email protected]f7022f32014-08-21 16:32:19876 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44877 EXPECT_EQ(1, d.response_started_count());
878 EXPECT_FALSE(d.received_data_before_response());
879 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19880 EXPECT_EQ("", r->GetSocketAddress().host());
881 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04882
883 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19884 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44885 }
886}
887
[email protected]ba40bb762012-12-17 07:11:04888TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15889 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04890 PathService::Get(base::FILE_EXE, &app_path);
891 GURL app_url = FilePathToFileURL(app_path);
892
893 TestDelegate d;
894 {
danakj8522a25b2016-04-16 00:17:36895 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36896 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04897
[email protected]f7022f32014-08-21 16:32:19898 r->Start();
899 EXPECT_TRUE(r->is_pending());
900 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04901 }
[email protected]79e1fd62013-06-20 06:50:04902 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04903 // destroyed.
[email protected]255620da2013-08-19 13:14:29904 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04905}
906
[email protected]316c1e5e2012-09-12 15:17:44907TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
908 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36909 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44910 FillBuffer(buffer.get(), buffer_size);
911
[email protected]6cdfd7f2013-02-08 20:40:15912 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52913 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44914 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30915 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44916
avibf0746c2015-12-09 19:53:14917 int64_t file_size;
[email protected]56285702013-12-04 18:22:49918 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44919
920 const size_t first_byte_position = 500;
921 const size_t last_byte_position = buffer_size - first_byte_position;
922 const size_t content_length = last_byte_position - first_byte_position + 1;
923 std::string partial_buffer_string(buffer.get() + first_byte_position,
924 buffer.get() + last_byte_position + 1);
925
926 TestDelegate d;
927 {
danakj8522a25b2016-04-16 00:17:36928 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36929 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44930
931 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38932 headers.SetHeader(
933 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59934 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38935 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19936 r->SetExtraRequestHeaders(headers);
937 r->Start();
938 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44939
[email protected]255620da2013-08-19 13:14:29940 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19941 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44942 EXPECT_EQ(1, d.response_started_count());
943 EXPECT_FALSE(d.received_data_before_response());
944 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
945 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
946 EXPECT_TRUE(partial_buffer_string == d.data_received());
947 }
948
[email protected]dd3aa792013-07-16 19:10:23949 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44950}
951
952TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
953 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36954 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44955 FillBuffer(buffer.get(), buffer_size);
956
[email protected]6cdfd7f2013-02-08 20:40:15957 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52958 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44959 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30960 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44961
avibf0746c2015-12-09 19:53:14962 int64_t file_size;
[email protected]56285702013-12-04 18:22:49963 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44964
965 const size_t first_byte_position = 500;
966 const size_t last_byte_position = buffer_size - 1;
967 const size_t content_length = last_byte_position - first_byte_position + 1;
968 std::string partial_buffer_string(buffer.get() + first_byte_position,
969 buffer.get() + last_byte_position + 1);
970
971 TestDelegate d;
972 {
danakj8522a25b2016-04-16 00:17:36973 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36974 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44975
976 HttpRequestHeaders headers;
977 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59978 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38979 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19980 r->SetExtraRequestHeaders(headers);
981 r->Start();
982 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44983
[email protected]255620da2013-08-19 13:14:29984 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19985 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44986 EXPECT_EQ(1, d.response_started_count());
987 EXPECT_FALSE(d.received_data_before_response());
988 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
989 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
990 EXPECT_TRUE(partial_buffer_string == d.data_received());
991 }
992
[email protected]dd3aa792013-07-16 19:10:23993 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44994}
995
996TEST_F(URLRequestTest, FileTestMultipleRanges) {
997 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:36998 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44999 FillBuffer(buffer.get(), buffer_size);
1000
[email protected]6cdfd7f2013-02-08 20:40:151001 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521002 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441003 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301004 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441005
avibf0746c2015-12-09 19:53:141006 int64_t file_size;
[email protected]56285702013-12-04 18:22:491007 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441008
1009 TestDelegate d;
1010 {
danakj8522a25b2016-04-16 00:17:361011 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361012 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441013
1014 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381015 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191016 r->SetExtraRequestHeaders(headers);
1017 r->Start();
1018 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441019
[email protected]255620da2013-08-19 13:14:291020 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441021 EXPECT_TRUE(d.request_failed());
1022 }
1023
[email protected]dd3aa792013-07-16 19:10:231024 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441025}
1026
[email protected]3ca8b362013-11-11 22:18:071027TEST_F(URLRequestTest, AllowFileURLs) {
1028 base::ScopedTempDir temp_dir;
1029 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1030 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:521031 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071032 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301033 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591034 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071035
1036 {
1037 TestDelegate d;
1038 TestNetworkDelegate network_delegate;
1039 network_delegate.set_can_access_files(true);
1040 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361041 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361042 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191043 r->Start();
[email protected]3ca8b362013-11-11 22:18:071044 base::RunLoop().Run();
1045 EXPECT_FALSE(d.request_failed());
1046 EXPECT_EQ(test_data, d.data_received());
1047 }
1048
1049 {
1050 TestDelegate d;
1051 TestNetworkDelegate network_delegate;
1052 network_delegate.set_can_access_files(false);
1053 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361054 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361055 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191056 r->Start();
[email protected]3ca8b362013-11-11 22:18:071057 base::RunLoop().Run();
1058 EXPECT_TRUE(d.request_failed());
1059 EXPECT_EQ("", d.data_received());
1060 }
1061}
1062
[email protected]316c1e5e2012-09-12 15:17:441063
1064TEST_F(URLRequestTest, FileDirCancelTest) {
1065 // Put in mock resource provider.
1066 NetModule::SetResourceProvider(TestNetResourceProvider);
1067
1068 TestDelegate d;
1069 {
[email protected]6cdfd7f2013-02-08 20:40:151070 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441071 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1072 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1073 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1074
danakj8522a25b2016-04-16 00:17:361075 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361076 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191077 req->Start();
1078 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441079
1080 d.set_cancel_in_received_data_pending(true);
1081
[email protected]255620da2013-08-19 13:14:291082 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441083 }
1084
1085 // Take out mock resource provider.
1086 NetModule::SetResourceProvider(NULL);
1087}
1088
[email protected]5f9581402013-10-30 13:08:321089TEST_F(URLRequestTest, FileDirOutputSanity) {
1090 // Verify the general sanity of the the output of the file:
1091 // directory lister by checking for the output of a known existing
1092 // file.
1093 const char sentinel_name[] = "filedir-sentinel";
1094
1095 base::FilePath path;
1096 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471097 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321098
1099 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361100 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361101 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191102 req->Start();
[email protected]5f9581402013-10-30 13:08:321103 base::RunLoop().Run();
1104
1105 // Generate entry for the sentinel file.
1106 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581107 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491108 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321109 EXPECT_GT(info.size, 0);
1110 std::string sentinel_output = GetDirectoryListingEntry(
1111 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1112 std::string(sentinel_name),
1113 false /* is_dir */,
1114 info.size,
1115 info.last_modified);
1116
1117 ASSERT_LT(0, d.bytes_received());
1118 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191119 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:321120 // Check for the entry generated for the "sentinel" file.
1121 const std::string& data = d.data_received();
1122 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1123}
1124
[email protected]316c1e5e2012-09-12 15:17:441125TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1126 // There is an implicit redirect when loading a file path that matches a
1127 // directory and does not end with a slash. Ensure that following such
1128 // redirects does not crash. See http://crbug.com/18686.
1129
[email protected]6cdfd7f2013-02-08 20:40:151130 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441131 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471132 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441133
1134 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361135 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361136 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191137 req->Start();
[email protected]255620da2013-08-19 13:14:291138 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441139
1140 ASSERT_EQ(1, d.received_redirect_count());
1141 ASSERT_LT(0, d.bytes_received());
1142 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191143 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441144}
1145
1146#if defined(OS_WIN)
1147// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1148TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1149 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361150 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361151 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191152 req->Start();
[email protected]255620da2013-08-19 13:14:291153 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441154
1155 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191156 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441157}
[email protected]5ecf7cb282014-05-11 01:49:551158#endif // defined(OS_WIN)
1159
1160#endif // !defined(DISABLE_FILE_SUPPORT)
1161
1162TEST_F(URLRequestTest, InvalidUrlTest) {
1163 TestDelegate d;
1164 {
danakj8522a25b2016-04-16 00:17:361165 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361166 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551167
[email protected]f7022f32014-08-21 16:32:191168 r->Start();
1169 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551170
1171 base::RunLoop().Run();
1172 EXPECT_TRUE(d.request_failed());
1173 }
1174}
1175
jochen0e3b3a62014-09-16 18:31:231176TEST_F(URLRequestTest, InvalidReferrerTest) {
1177 TestURLRequestContext context;
1178 TestNetworkDelegate network_delegate;
1179 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1180 context.set_network_delegate(&network_delegate);
1181 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361182 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361183 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231184 req->SetReferrer("https://somewhere.com/");
1185
1186 req->Start();
1187 base::RunLoop().Run();
1188 EXPECT_TRUE(d.request_failed());
1189}
1190
[email protected]5ecf7cb282014-05-11 01:49:551191#if defined(OS_WIN)
1192TEST_F(URLRequestTest, ResolveShortcutTest) {
1193 base::FilePath app_path;
1194 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471195 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551196 app_path = app_path.AppendASCII("with-headers.html");
1197
1198 std::wstring lnk_path = app_path.value() + L".lnk";
1199
1200 base::win::ScopedCOMInitializer com_initializer;
1201
1202 // Temporarily create a shortcut for test
1203 {
1204 base::win::ScopedComPtr<IShellLink> shell;
1205 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1206 CLSCTX_INPROC_SERVER)));
1207 base::win::ScopedComPtr<IPersistFile> persist;
1208 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1209 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1210 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1211 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1212 }
1213
1214 TestDelegate d;
1215 {
danakj8522a25b2016-04-16 00:17:361216 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361217 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551218
[email protected]f7022f32014-08-21 16:32:191219 r->Start();
1220 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551221
1222 base::RunLoop().Run();
1223
1224 WIN32_FILE_ATTRIBUTE_DATA data;
1225 GetFileAttributesEx(app_path.value().c_str(),
1226 GetFileExInfoStandard, &data);
1227 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1228 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1229 FILE_ATTRIBUTE_NORMAL, NULL);
1230 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361231 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551232 DWORD read_size;
1233 BOOL result;
1234 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1235 &read_size, NULL);
1236 std::string content(buffer.get(), read_size);
1237 CloseHandle(file);
1238
[email protected]f7022f32014-08-21 16:32:191239 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551240 EXPECT_EQ(1, d.received_redirect_count());
1241 EXPECT_EQ(content, d.data_received());
1242 }
1243
1244 // Clean the shortcut
1245 DeleteFile(lnk_path.c_str());
1246}
1247#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441248
1249// Custom URLRequestJobs for use with interceptor tests
1250class RestartTestJob : public URLRequestTestJob {
1251 public:
1252 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1253 : URLRequestTestJob(request, network_delegate, true) {}
1254 protected:
dchengb03027d2014-10-21 12:00:201255 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441256 private:
dchengb03027d2014-10-21 12:00:201257 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441258};
1259
1260class CancelTestJob : public URLRequestTestJob {
1261 public:
1262 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1263 : URLRequestTestJob(request, network_delegate, true) {}
1264 protected:
dchengb03027d2014-10-21 12:00:201265 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441266 private:
dchengb03027d2014-10-21 12:00:201267 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441268};
1269
1270class CancelThenRestartTestJob : public URLRequestTestJob {
1271 public:
1272 explicit CancelThenRestartTestJob(URLRequest* request,
1273 NetworkDelegate* network_delegate)
1274 : URLRequestTestJob(request, network_delegate, true) {
1275 }
1276 protected:
dchengb03027d2014-10-21 12:00:201277 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441278 request_->Cancel();
1279 this->NotifyRestartRequired();
1280 }
1281 private:
dchengb03027d2014-10-21 12:00:201282 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441283};
1284
bengr1bf8e942014-11-07 01:36:501285// An Interceptor for use with interceptor tests.
1286class MockURLRequestInterceptor : public URLRequestInterceptor {
1287 public:
1288 // Static getters for canned response header and data strings.
1289 static std::string ok_data() {
1290 return URLRequestTestJob::test_data_1();
1291 }
1292
1293 static std::string ok_headers() {
1294 return URLRequestTestJob::test_headers();
1295 }
1296
1297 static std::string redirect_data() {
1298 return std::string();
1299 }
1300
1301 static std::string redirect_headers() {
1302 return URLRequestTestJob::test_redirect_headers();
1303 }
1304
1305 static std::string error_data() {
1306 return std::string("ohhh nooooo mr. bill!");
1307 }
1308
1309 static std::string error_headers() {
1310 return URLRequestTestJob::test_error_headers();
1311 }
1312
1313 MockURLRequestInterceptor()
1314 : intercept_main_request_(false), restart_main_request_(false),
1315 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1316 simulate_main_network_error_(false),
1317 intercept_redirect_(false), cancel_redirect_request_(false),
1318 intercept_final_response_(false), cancel_final_request_(false),
1319 use_url_request_http_job_(false),
1320 did_intercept_main_(false), did_restart_main_(false),
1321 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1322 did_simulate_error_main_(false),
1323 did_intercept_redirect_(false), did_cancel_redirect_(false),
1324 did_intercept_final_(false), did_cancel_final_(false) {
1325 }
1326
1327 ~MockURLRequestInterceptor() override {
1328 }
1329
1330 // URLRequestInterceptor implementation:
1331 URLRequestJob* MaybeInterceptRequest(
1332 URLRequest* request,
1333 NetworkDelegate* network_delegate) const override {
1334 if (restart_main_request_) {
1335 restart_main_request_ = false;
1336 did_restart_main_ = true;
1337 return new RestartTestJob(request, network_delegate);
1338 }
1339 if (cancel_main_request_) {
1340 cancel_main_request_ = false;
1341 did_cancel_main_ = true;
1342 return new CancelTestJob(request, network_delegate);
1343 }
1344 if (cancel_then_restart_main_request_) {
1345 cancel_then_restart_main_request_ = false;
1346 did_cancel_then_restart_main_ = true;
1347 return new CancelThenRestartTestJob(request, network_delegate);
1348 }
1349 if (simulate_main_network_error_) {
1350 simulate_main_network_error_ = false;
1351 did_simulate_error_main_ = true;
1352 if (use_url_request_http_job_) {
1353 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1354 }
1355 // This job will result in error since the requested URL is not one of the
1356 // URLs supported by these tests.
1357 return new URLRequestTestJob(request, network_delegate, true);
1358 }
1359 if (!intercept_main_request_)
1360 return nullptr;
1361 intercept_main_request_ = false;
1362 did_intercept_main_ = true;
1363 URLRequestTestJob* job = new URLRequestTestJob(request,
1364 network_delegate,
1365 main_headers_,
1366 main_data_,
1367 true);
1368 job->set_load_timing_info(main_request_load_timing_info_);
1369 return job;
1370 }
1371
1372 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1373 NetworkDelegate* network_delegate,
1374 const GURL& location) const override {
1375 if (cancel_redirect_request_) {
1376 cancel_redirect_request_ = false;
1377 did_cancel_redirect_ = true;
1378 return new CancelTestJob(request, network_delegate);
1379 }
1380 if (!intercept_redirect_)
1381 return nullptr;
1382 intercept_redirect_ = false;
1383 did_intercept_redirect_ = true;
1384 if (use_url_request_http_job_) {
1385 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1386 }
1387 return new URLRequestTestJob(request,
1388 network_delegate,
1389 redirect_headers_,
1390 redirect_data_,
1391 true);
1392 }
1393
1394 URLRequestJob* MaybeInterceptResponse(
1395 URLRequest* request,
1396 NetworkDelegate* network_delegate) const override {
1397 if (cancel_final_request_) {
1398 cancel_final_request_ = false;
1399 did_cancel_final_ = true;
1400 return new CancelTestJob(request, network_delegate);
1401 }
1402 if (!intercept_final_response_)
1403 return nullptr;
1404 intercept_final_response_ = false;
1405 did_intercept_final_ = true;
1406 if (use_url_request_http_job_) {
1407 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1408 }
1409 return new URLRequestTestJob(request,
1410 network_delegate,
1411 final_headers_,
1412 final_data_,
1413 true);
1414 }
1415
1416 void set_intercept_main_request(bool intercept_main_request) {
1417 intercept_main_request_ = intercept_main_request;
1418 }
1419
1420 void set_main_headers(const std::string& main_headers) {
1421 main_headers_ = main_headers;
1422 }
1423
1424 void set_main_data(const std::string& main_data) {
1425 main_data_ = main_data;
1426 }
1427
1428 void set_main_request_load_timing_info(
1429 const LoadTimingInfo& main_request_load_timing_info) {
1430 main_request_load_timing_info_ = main_request_load_timing_info;
1431 }
1432
1433 void set_restart_main_request(bool restart_main_request) {
1434 restart_main_request_ = restart_main_request;
1435 }
1436
1437 void set_cancel_main_request(bool cancel_main_request) {
1438 cancel_main_request_ = cancel_main_request;
1439 }
1440
1441 void set_cancel_then_restart_main_request(
1442 bool cancel_then_restart_main_request) {
1443 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1444 }
1445
1446 void set_simulate_main_network_error(bool simulate_main_network_error) {
1447 simulate_main_network_error_ = simulate_main_network_error;
1448 }
1449
1450 void set_intercept_redirect(bool intercept_redirect) {
1451 intercept_redirect_ = intercept_redirect;
1452 }
1453
1454 void set_redirect_headers(const std::string& redirect_headers) {
1455 redirect_headers_ = redirect_headers;
1456 }
1457
1458 void set_redirect_data(const std::string& redirect_data) {
1459 redirect_data_ = redirect_data;
1460 }
1461
1462 void set_cancel_redirect_request(bool cancel_redirect_request) {
1463 cancel_redirect_request_ = cancel_redirect_request;
1464 }
1465
1466 void set_intercept_final_response(bool intercept_final_response) {
1467 intercept_final_response_ = intercept_final_response;
1468 }
1469
1470 void set_final_headers(const std::string& final_headers) {
1471 final_headers_ = final_headers;
1472 }
1473
1474 void set_final_data(const std::string& final_data) {
1475 final_data_ = final_data;
1476 }
1477
1478 void set_cancel_final_request(bool cancel_final_request) {
1479 cancel_final_request_ = cancel_final_request;
1480 }
1481
1482 void set_use_url_request_http_job(bool use_url_request_http_job) {
1483 use_url_request_http_job_ = use_url_request_http_job;
1484 }
1485
1486 bool did_intercept_main() const {
1487 return did_intercept_main_;
1488 }
1489
1490 bool did_restart_main() const {
1491 return did_restart_main_;
1492 }
1493
1494 bool did_cancel_main() const {
1495 return did_cancel_main_;
1496 }
1497
1498 bool did_cancel_then_restart_main() const {
1499 return did_cancel_then_restart_main_;
1500 }
1501
1502 bool did_simulate_error_main() const {
1503 return did_simulate_error_main_;
1504 }
1505
1506 bool did_intercept_redirect() const {
1507 return did_intercept_redirect_;
1508 }
1509
1510 bool did_cancel_redirect() const {
1511 return did_cancel_redirect_;
1512 }
1513
1514 bool did_intercept_final() const {
1515 return did_intercept_final_;
1516 }
1517
1518 bool did_cancel_final() const {
1519 return did_cancel_final_;
1520 }
1521
1522 private:
1523 // Indicate whether to intercept the main request, and if so specify the
1524 // response to return and the LoadTimingInfo to use.
1525 mutable bool intercept_main_request_;
1526 mutable std::string main_headers_;
1527 mutable std::string main_data_;
1528 mutable LoadTimingInfo main_request_load_timing_info_;
1529
1530 // These indicate actions that can be taken within MaybeInterceptRequest.
1531 mutable bool restart_main_request_;
1532 mutable bool cancel_main_request_;
1533 mutable bool cancel_then_restart_main_request_;
1534 mutable bool simulate_main_network_error_;
1535
1536 // Indicate whether to intercept redirects, and if so specify the response to
1537 // return.
1538 mutable bool intercept_redirect_;
1539 mutable std::string redirect_headers_;
1540 mutable std::string redirect_data_;
1541
1542 // Cancel the request within MaybeInterceptRedirect.
1543 mutable bool cancel_redirect_request_;
1544
1545 // Indicate whether to intercept the final response, and if so specify the
1546 // response to return.
1547 mutable bool intercept_final_response_;
1548 mutable std::string final_headers_;
1549 mutable std::string final_data_;
1550
1551 // Cancel the final request within MaybeInterceptResponse.
1552 mutable bool cancel_final_request_;
1553
1554 // Instruct the interceptor to use a real URLRequestHTTPJob.
1555 mutable bool use_url_request_http_job_;
1556
1557 // These indicate if the interceptor did something or not.
1558 mutable bool did_intercept_main_;
1559 mutable bool did_restart_main_;
1560 mutable bool did_cancel_main_;
1561 mutable bool did_cancel_then_restart_main_;
1562 mutable bool did_simulate_error_main_;
1563 mutable bool did_intercept_redirect_;
1564 mutable bool did_cancel_redirect_;
1565 mutable bool did_intercept_final_;
1566 mutable bool did_cancel_final_;
1567};
1568
1569// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1570class URLRequestInterceptorTest : public URLRequestTest {
1571 public:
1572 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1573 }
1574
1575 ~URLRequestInterceptorTest() override {
1576 // URLRequestJobs may post clean-up tasks on destruction.
1577 base::RunLoop().RunUntilIdle();
1578 }
1579
1580 void SetUpFactory() override {
1581 interceptor_ = new MockURLRequestInterceptor();
1582 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361583 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501584 }
1585
1586 MockURLRequestInterceptor* interceptor() const {
1587 return interceptor_;
1588 }
1589
1590 private:
1591 MockURLRequestInterceptor* interceptor_;
1592};
1593
1594TEST_F(URLRequestInterceptorTest, Intercept) {
1595 // Intercept the main request and respond with a simple response.
1596 interceptor()->set_intercept_main_request(true);
1597 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1598 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591599 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361600 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361601 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501602 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1603 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1604 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1605 req->SetUserData(nullptr, user_data0);
1606 req->SetUserData(&user_data1, user_data1);
1607 req->SetUserData(&user_data2, user_data2);
1608 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191609 req->Start();
[email protected]255620da2013-08-19 13:14:291610 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591611
bengr1bf8e942014-11-07 01:36:501612 // Make sure we can retrieve our specific user data.
1613 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1614 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1615 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591616
bengr1bf8e942014-11-07 01:36:501617 // Check that we got one good response.
1618 EXPECT_TRUE(req->status().is_success());
1619 EXPECT_EQ(200, req->response_headers()->response_code());
1620 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1621 EXPECT_EQ(1, d.response_started_count());
1622 EXPECT_EQ(0, d.received_redirect_count());
1623}
[email protected]2bba3252013-04-08 19:50:591624
bengr1bf8e942014-11-07 01:36:501625TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1626 // Intercept the main request and respond with a redirect.
1627 interceptor()->set_intercept_main_request(true);
1628 interceptor()->set_main_headers(
1629 MockURLRequestInterceptor::redirect_headers());
1630 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1631
1632 // Intercept that redirect and respond with a final OK response.
1633 interceptor()->set_intercept_redirect(true);
1634 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1635 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1636
1637 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361638 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361639 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501640 req->set_method("GET");
1641 req->Start();
1642 base::RunLoop().Run();
1643
1644 // Check that the interceptor got called as expected.
1645 EXPECT_TRUE(interceptor()->did_intercept_main());
1646 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1647
1648 // Check that we got one good response.
1649 EXPECT_TRUE(req->status().is_success());
1650 if (req->status().is_success())
1651 EXPECT_EQ(200, req->response_headers()->response_code());
1652
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, InterceptServerError) {
1659 // Intercept the main request to generate a server error response.
1660 interceptor()->set_intercept_main_request(true);
1661 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1662 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1663
1664 // Intercept that error and respond with an OK response.
1665 interceptor()->set_intercept_final_response(true);
1666 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1667 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1668
1669 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361670 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361671 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501672 req->set_method("GET");
1673 req->Start();
1674 base::RunLoop().Run();
1675
1676 // Check that the interceptor got called as expected.
1677 EXPECT_TRUE(interceptor()->did_intercept_main());
1678 EXPECT_TRUE(interceptor()->did_intercept_final());
1679
1680 // Check that we got one good response.
1681 EXPECT_TRUE(req->status().is_success());
1682 EXPECT_EQ(200, req->response_headers()->response_code());
1683 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1684 EXPECT_EQ(1, d.response_started_count());
1685 EXPECT_EQ(0, d.received_redirect_count());
1686}
1687
1688TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1689 // Intercept the main request to simulate a network error.
1690 interceptor()->set_simulate_main_network_error(true);
1691
1692 // Intercept that error and respond with an OK response.
1693 interceptor()->set_intercept_final_response(true);
1694 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1695 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1696
1697 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361698 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361699 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501700 req->set_method("GET");
1701 req->Start();
1702 base::RunLoop().Run();
1703
1704 // Check that the interceptor got called as expected.
1705 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1706 EXPECT_TRUE(interceptor()->did_intercept_final());
1707
1708 // Check that we received one good response.
1709 EXPECT_TRUE(req->status().is_success());
1710 EXPECT_EQ(200, req->response_headers()->response_code());
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, InterceptRestartRequired) {
1717 // Restart the main request.
1718 interceptor()->set_restart_main_request(true);
1719
1720 // then intercept the new main request and respond with an OK response
1721 interceptor()->set_intercept_main_request(true);
1722 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1723 interceptor()->set_main_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_restart_main());
1734 EXPECT_TRUE(interceptor()->did_intercept_main());
1735
1736 // Check that we received one good response.
1737 EXPECT_TRUE(req->status().is_success());
1738 if (req->status().is_success())
1739 EXPECT_EQ(200, req->response_headers()->response_code());
1740
1741 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1742 EXPECT_EQ(1, d.response_started_count());
1743 EXPECT_EQ(0, d.received_redirect_count());
1744}
1745
1746TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1747 // Intercept the main request and cancel from within the restarted job.
1748 interceptor()->set_cancel_main_request(true);
1749
1750 // Set up to intercept the final response and override it with an OK response.
1751 interceptor()->set_intercept_final_response(true);
1752 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1753 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1754
1755 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361756 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361757 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501758 req->set_method("GET");
1759 req->Start();
1760 base::RunLoop().Run();
1761
1762 // Check that the interceptor got called as expected.
1763 EXPECT_TRUE(interceptor()->did_cancel_main());
1764 EXPECT_FALSE(interceptor()->did_intercept_final());
1765
1766 // Check that we see a canceled request.
1767 EXPECT_FALSE(req->status().is_success());
1768 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1769}
1770
1771TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1772 // Intercept the main request and respond with a redirect.
1773 interceptor()->set_intercept_main_request(true);
1774 interceptor()->set_main_headers(
1775 MockURLRequestInterceptor::redirect_headers());
1776 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1777
1778 // Intercept the redirect and cancel from within that job.
1779 interceptor()->set_cancel_redirect_request(true);
1780
1781 // Set up to intercept the final response and override it with an OK response.
1782 interceptor()->set_intercept_final_response(true);
1783 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1784 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1785
1786 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361787 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361788 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501789 req->set_method("GET");
1790 req->Start();
1791 base::RunLoop().Run();
1792
1793 // Check that the interceptor got called as expected.
1794 EXPECT_TRUE(interceptor()->did_intercept_main());
1795 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1796 EXPECT_FALSE(interceptor()->did_intercept_final());
1797
1798 // Check that we see a canceled request.
1799 EXPECT_FALSE(req->status().is_success());
1800 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1801}
1802
1803TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1804 // Intercept the main request to simulate a network error.
1805 interceptor()->set_simulate_main_network_error(true);
1806
1807 // Set up to intercept final the response and cancel from within that job.
1808 interceptor()->set_cancel_final_request(true);
1809
1810 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361811 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361812 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501813 req->set_method("GET");
1814 req->Start();
1815 base::RunLoop().Run();
1816
1817 // Check that the interceptor got called as expected.
1818 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1819 EXPECT_TRUE(interceptor()->did_cancel_final());
1820
1821 // Check that we see a canceled request.
1822 EXPECT_FALSE(req->status().is_success());
1823 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1824}
1825
1826TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1827 // Intercept the main request and cancel then restart from within that job.
1828 interceptor()->set_cancel_then_restart_main_request(true);
1829
1830 // Set up to intercept the final response and override it with an OK response.
1831 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501832 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1833 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501834
1835 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361836 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361837 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501838 req->set_method("GET");
1839 req->Start();
1840 base::RunLoop().Run();
1841
1842 // Check that the interceptor got called as expected.
1843 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1844 EXPECT_FALSE(interceptor()->did_intercept_final());
1845
1846 // Check that we see a canceled request.
1847 EXPECT_FALSE(req->status().is_success());
1848 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591849}
1850
1851// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1852// reused. |connect_time_flags| is used to indicate if there should be dns
1853// or SSL times, and |used_proxy| is used for proxy times.
1854LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1855 int connect_time_flags,
1856 bool used_proxy) {
1857 LoadTimingInfo load_timing;
1858 load_timing.socket_log_id = 1;
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 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1866 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1867 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1868 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1869 }
1870 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1871 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1872 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1873 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1874 }
1875 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1876
1877 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1878 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1879 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1880 return load_timing;
1881}
1882
1883// Same as above, but in the case of a reused socket.
1884LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1885 bool used_proxy) {
1886 LoadTimingInfo load_timing;
1887 load_timing.socket_log_id = 1;
1888 load_timing.socket_reused = true;
1889
1890 if (used_proxy) {
1891 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1892 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1893 }
1894
1895 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1896 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1897 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1898 return load_timing;
1899}
1900
bengr1bf8e942014-11-07 01:36:501901LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1902 const LoadTimingInfo& job_load_timing,
1903 const URLRequestContext& context,
1904 MockURLRequestInterceptor* interceptor) {
1905 interceptor->set_intercept_main_request(true);
1906 interceptor->set_main_request_load_timing_info(job_load_timing);
1907 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361908 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361909 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501910 req->Start();
1911 base::RunLoop().Run();
1912
1913 LoadTimingInfo resulting_load_timing;
1914 req->GetLoadTimingInfo(&resulting_load_timing);
1915
1916 // None of these should be modified by the URLRequest.
1917 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1918 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1919 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1920 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1921 EXPECT_EQ(job_load_timing.receive_headers_end,
1922 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571923 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1924 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501925
1926 return resulting_load_timing;
1927}
1928
[email protected]2bba3252013-04-08 19:50:591929// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501930TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591931 base::TimeTicks now = base::TimeTicks::Now();
1932 LoadTimingInfo job_load_timing =
1933 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1934
[email protected]2ca01e52013-10-31 22:05:191935 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501936 RunURLRequestInterceptorLoadTimingTest(
1937 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591938
1939 // Nothing should have been changed by the URLRequest.
1940 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1941 load_timing_result.proxy_resolve_start);
1942 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1943 load_timing_result.proxy_resolve_end);
1944 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1945 load_timing_result.connect_timing.dns_start);
1946 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1947 load_timing_result.connect_timing.dns_end);
1948 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1949 load_timing_result.connect_timing.connect_start);
1950 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1951 load_timing_result.connect_timing.connect_end);
1952 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1953 load_timing_result.connect_timing.ssl_start);
1954 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1955 load_timing_result.connect_timing.ssl_end);
1956
1957 // Redundant sanity check.
1958 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1959}
1960
1961// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501962TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591963 base::TimeTicks now = base::TimeTicks::Now();
1964 LoadTimingInfo job_load_timing =
1965 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1966
[email protected]2ca01e52013-10-31 22:05:191967 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501968 RunURLRequestInterceptorLoadTimingTest(
1969 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591970
1971 // Nothing should have been changed by the URLRequest.
1972 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1973 load_timing_result.proxy_resolve_start);
1974 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1975 load_timing_result.proxy_resolve_end);
1976 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1977 load_timing_result.connect_timing.dns_start);
1978 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1979 load_timing_result.connect_timing.dns_end);
1980 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1981 load_timing_result.connect_timing.connect_start);
1982 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1983 load_timing_result.connect_timing.connect_end);
1984 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1985 load_timing_result.connect_timing.ssl_start);
1986 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1987 load_timing_result.connect_timing.ssl_end);
1988
1989 // Redundant sanity check.
1990 TestLoadTimingNotReusedWithProxy(load_timing_result,
1991 CONNECT_TIMING_HAS_SSL_TIMES);
1992}
1993
1994// Make sure that URLRequest correctly adjusts proxy times when they're before
1995// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101996// the case of reusing a SPDY session. The connected socket is not considered
1997// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591998//
1999// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502000TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592001 base::TimeTicks now = base::TimeTicks::Now();
2002 LoadTimingInfo job_load_timing =
2003 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2004 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2005 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2006 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2007 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2008 job_load_timing.connect_timing.connect_start =
2009 now - base::TimeDelta::FromDays(2);
2010 job_load_timing.connect_timing.connect_end =
2011 now - base::TimeDelta::FromDays(1);
2012
[email protected]2ca01e52013-10-31 22:05:192013 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502014 RunURLRequestInterceptorLoadTimingTest(
2015 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592016
2017 // Proxy times, connect times, and DNS times should all be replaced with
2018 // request_start.
2019 EXPECT_EQ(load_timing_result.request_start,
2020 load_timing_result.proxy_resolve_start);
2021 EXPECT_EQ(load_timing_result.request_start,
2022 load_timing_result.proxy_resolve_end);
2023 EXPECT_EQ(load_timing_result.request_start,
2024 load_timing_result.connect_timing.dns_start);
2025 EXPECT_EQ(load_timing_result.request_start,
2026 load_timing_result.connect_timing.dns_end);
2027 EXPECT_EQ(load_timing_result.request_start,
2028 load_timing_result.connect_timing.connect_start);
2029 EXPECT_EQ(load_timing_result.request_start,
2030 load_timing_result.connect_timing.connect_end);
2031
2032 // Other times should have been left null.
2033 TestLoadTimingNotReusedWithProxy(load_timing_result,
2034 CONNECT_TIMING_HAS_DNS_TIMES);
2035}
2036
2037// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502038TEST_F(URLRequestInterceptorTest,
2039 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592040 base::TimeTicks now = base::TimeTicks::Now();
2041 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2042 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2043 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
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 // Proxy times and connect times should all be replaced with request_start.
2050 EXPECT_EQ(load_timing_result.request_start,
2051 load_timing_result.proxy_resolve_start);
2052 EXPECT_EQ(load_timing_result.request_start,
2053 load_timing_result.proxy_resolve_end);
2054
2055 // Other times should have been left null.
2056 TestLoadTimingReusedWithProxy(load_timing_result);
2057}
2058
2059// Make sure that URLRequest correctly adjusts connect times when they're before
2060// |request_start|, due to reusing a connected socket. The connected socket is
2061// not considered reused in this test (May be a preconnect).
2062//
2063// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502064TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592065 base::TimeTicks now = base::TimeTicks::Now();
2066 LoadTimingInfo job_load_timing =
2067 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2068 job_load_timing.connect_timing.connect_start =
2069 now - base::TimeDelta::FromDays(1);
2070 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2071 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2072 job_load_timing.connect_timing.connect_end =
2073 now - base::TimeDelta::FromDays(4);
2074
[email protected]2ca01e52013-10-31 22:05:192075 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502076 RunURLRequestInterceptorLoadTimingTest(
2077 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592078
2079 // Connect times, and SSL times should be replaced with request_start.
2080 EXPECT_EQ(load_timing_result.request_start,
2081 load_timing_result.connect_timing.connect_start);
2082 EXPECT_EQ(load_timing_result.request_start,
2083 load_timing_result.connect_timing.ssl_start);
2084 EXPECT_EQ(load_timing_result.request_start,
2085 load_timing_result.connect_timing.ssl_end);
2086 EXPECT_EQ(load_timing_result.request_start,
2087 load_timing_result.connect_timing.connect_end);
2088
2089 // Other times should have been left null.
2090 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2091}
2092
2093// Make sure that URLRequest correctly adjusts connect times when they're before
2094// |request_start|, due to reusing a connected socket in the case that there
2095// are also proxy times. The connected socket is not considered reused in this
2096// test (May be a preconnect).
2097//
2098// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502099TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592100 base::TimeTicks now = base::TimeTicks::Now();
2101 LoadTimingInfo job_load_timing =
2102 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2103 job_load_timing.connect_timing.connect_start =
2104 now - base::TimeDelta::FromDays(1);
2105 job_load_timing.connect_timing.connect_end =
2106 now - base::TimeDelta::FromDays(2);
2107
[email protected]2ca01e52013-10-31 22:05:192108 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502109 RunURLRequestInterceptorLoadTimingTest(
2110 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592111
2112 // Connect times should be replaced with proxy_resolve_end.
2113 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2114 load_timing_result.connect_timing.connect_start);
2115 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2116 load_timing_result.connect_timing.connect_end);
2117
2118 // Other times should have been left null.
2119 TestLoadTimingNotReusedWithProxy(load_timing_result,
2120 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2121}
2122
[email protected]316c1e5e2012-09-12 15:17:442123// Check that two different URL requests have different identifiers.
2124TEST_F(URLRequestTest, Identifiers) {
2125 TestDelegate d;
2126 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362127 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362128 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362129 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362130 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442131
mmenke19378d22014-09-09 04:12:592132 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442133}
2134
blundellb8163592f2015-12-16 14:22:422135#if defined(OS_IOS)
2136// TODO(droger): Check that a failure to connect to the proxy is reported to
2137// the network delegate. crbug.com/496743
2138#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2139#else
2140#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2141#endif
2142TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442143 MockHostResolver host_resolver;
2144 host_resolver.rules()->AddSimulatedFailure("*");
2145
[email protected]ceefd7fd2012-11-29 00:36:242146 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442147 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2148
2149 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362150 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362151 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192152 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442153
[email protected]f7022f32014-08-21 16:32:192154 req->Start();
[email protected]255620da2013-08-19 13:14:292155 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442156
2157 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192158 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152159 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192160 EXPECT_TRUE(req->proxy_server().IsEmpty());
2161 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
robpercival214763f2016-07-01 23:27:012162 EXPECT_THAT(req->status().error(), IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442163
2164 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012165 EXPECT_THAT(network_delegate.last_error(),
2166 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442167 EXPECT_EQ(1, network_delegate.completed_requests());
2168}
2169
[email protected]cba24642014-08-15 20:49:592170// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442171// content is empty.
2172TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2173 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362174 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362175 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192176 req->Start();
[email protected]255620da2013-08-19 13:14:292177 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442178 EXPECT_EQ("", d.data_received());
2179 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2180}
2181
[email protected]5033ab82013-03-22 20:17:462182// Make sure that SetPriority actually sets the URLRequest's priority
2183// correctly, both before and after start.
2184TEST_F(URLRequestTest, SetPriorityBasic) {
2185 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362186 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362187 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192188 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462189
[email protected]f7022f32014-08-21 16:32:192190 req->SetPriority(LOW);
2191 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462192
[email protected]f7022f32014-08-21 16:32:192193 req->Start();
2194 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462195
[email protected]f7022f32014-08-21 16:32:192196 req->SetPriority(MEDIUM);
2197 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462198}
2199
2200// Make sure that URLRequest calls SetPriority on a job before calling
2201// Start on it.
2202TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2203 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362204 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362205 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192206 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462207
mmenkeed0498b2015-12-08 23:20:422208 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362209 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422210 req.get(), &default_network_delegate_, &job_priority));
2211 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2212 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462213
[email protected]f7022f32014-08-21 16:32:192214 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462215
[email protected]f7022f32014-08-21 16:32:192216 req->Start();
mmenkeed0498b2015-12-08 23:20:422217 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462218}
2219
2220// Make sure that URLRequest passes on its priority updates to its
2221// job.
2222TEST_F(URLRequestTest, SetJobPriority) {
2223 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362224 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362225 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462226
mmenkeed0498b2015-12-08 23:20:422227 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362228 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422229 req.get(), &default_network_delegate_, &job_priority));
2230 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462231
[email protected]f7022f32014-08-21 16:32:192232 req->SetPriority(LOW);
2233 req->Start();
mmenkeed0498b2015-12-08 23:20:422234 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462235
[email protected]f7022f32014-08-21 16:32:192236 req->SetPriority(MEDIUM);
2237 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422238 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462239}
2240
[email protected]bb1c4662013-11-14 00:00:072241// Setting the IGNORE_LIMITS load flag should be okay if the priority
2242// is MAXIMUM_PRIORITY.
2243TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2244 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362245 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362246 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192247 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072248
mmenkeed0498b2015-12-08 23:20:422249 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362250 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422251 req.get(), &default_network_delegate_, &job_priority));
2252 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072253
[email protected]f7022f32014-08-21 16:32:192254 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2255 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072256
[email protected]f7022f32014-08-21 16:32:192257 req->SetPriority(MAXIMUM_PRIORITY);
2258 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072259
[email protected]f7022f32014-08-21 16:32:192260 req->Start();
2261 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422262 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072263}
2264
nick5d570de92015-05-04 20:16:162265namespace {
2266
2267// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552268class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442269 public:
tommycli59a63432015-11-06 00:10:552270 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2271 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272272 }
tommycli59a63432015-11-06 00:10:552273
2274 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2275};
tommyclieae5f75f2015-11-05 19:07:272276
nick5d570de92015-05-04 20:16:162277} // namespace
2278
[email protected]f2f31b32013-01-16 23:24:092279TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442280 LocalHttpTestServer test_server;
2281 ASSERT_TRUE(test_server.Start());
2282
2283 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362284 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502285 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442286
2287 // Set up a cookie.
2288 {
2289 TestNetworkDelegate network_delegate;
2290 context.set_network_delegate(&network_delegate);
2291 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362292 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552293 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362294 &d));
[email protected]f7022f32014-08-21 16:32:192295 req->Start();
[email protected]255620da2013-08-19 13:14:292296 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442297 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2298 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2299 EXPECT_EQ(1, network_delegate.set_cookie_count());
2300 }
2301
2302 // Verify that the cookie is set.
2303 {
2304 TestNetworkDelegate network_delegate;
2305 context.set_network_delegate(&network_delegate);
2306 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362307 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552308 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192309 req->Start();
[email protected]255620da2013-08-19 13:14:292310 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442311
2312 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2313 != std::string::npos);
2314 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2315 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2316 }
2317}
2318
[email protected]f2f31b32013-01-16 23:24:092319TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442320 LocalHttpTestServer test_server;
2321 ASSERT_TRUE(test_server.Start());
2322
2323 // Set up a cookie.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362328 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552329 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362330 &d));
[email protected]f7022f32014-08-21 16:32:192331 req->Start();
[email protected]255620da2013-08-19 13:14:292332 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442333 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2334 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2335 }
2336
2337 // Verify that the cookie is set.
2338 {
2339 TestNetworkDelegate network_delegate;
2340 default_context_.set_network_delegate(&network_delegate);
2341 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362342 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552343 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192344 req->Start();
[email protected]255620da2013-08-19 13:14:292345 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442346
2347 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2348 != std::string::npos);
2349 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2350 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2351 }
2352
2353 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2354 {
2355 TestNetworkDelegate network_delegate;
2356 default_context_.set_network_delegate(&network_delegate);
2357 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362358 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552359 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192360 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2361 req->Start();
[email protected]255620da2013-08-19 13:14:292362 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442363
2364 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2365 == std::string::npos);
2366
2367 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2368 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2369 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2370 }
2371}
2372
2373TEST_F(URLRequestTest, DoNotSaveCookies) {
2374 LocalHttpTestServer test_server;
2375 ASSERT_TRUE(test_server.Start());
2376
2377 // Set up a cookie.
2378 {
2379 TestNetworkDelegate network_delegate;
2380 default_context_.set_network_delegate(&network_delegate);
2381 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362382 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552383 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362384 &d));
[email protected]f7022f32014-08-21 16:32:192385 req->Start();
[email protected]255620da2013-08-19 13:14:292386 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442387
2388 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2389 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2390 EXPECT_EQ(1, network_delegate.set_cookie_count());
2391 }
2392
2393 // Try to set-up another cookie and update the previous cookie.
2394 {
2395 TestNetworkDelegate network_delegate;
2396 default_context_.set_network_delegate(&network_delegate);
2397 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362398 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552399 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362400 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192401 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2402 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442403
[email protected]255620da2013-08-19 13:14:292404 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442405
2406 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2407 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2408 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2409 EXPECT_EQ(0, network_delegate.set_cookie_count());
2410 }
2411
2412 // Verify the cookies weren't saved or updated.
2413 {
2414 TestNetworkDelegate network_delegate;
2415 default_context_.set_network_delegate(&network_delegate);
2416 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362417 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552418 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192419 req->Start();
[email protected]255620da2013-08-19 13:14:292420 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442421
2422 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2423 == std::string::npos);
2424 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2425 != std::string::npos);
2426
2427 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2428 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2429 EXPECT_EQ(0, network_delegate.set_cookie_count());
2430 }
2431}
2432
2433TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2434 LocalHttpTestServer test_server;
2435 ASSERT_TRUE(test_server.Start());
2436
2437 // Set up a cookie.
2438 {
2439 TestNetworkDelegate network_delegate;
2440 default_context_.set_network_delegate(&network_delegate);
2441 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362442 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552443 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362444 &d));
[email protected]f7022f32014-08-21 16:32:192445 req->Start();
[email protected]255620da2013-08-19 13:14:292446 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442447
2448 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2449 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2450 }
2451
2452 // Verify that the cookie is set.
2453 {
2454 TestNetworkDelegate network_delegate;
2455 default_context_.set_network_delegate(&network_delegate);
2456 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362457 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552458 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192459 req->Start();
[email protected]255620da2013-08-19 13:14:292460 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442461
2462 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2463 != std::string::npos);
2464
2465 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2466 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2467 }
2468
2469 // Verify that the cookie isn't sent.
2470 {
2471 TestNetworkDelegate network_delegate;
2472 default_context_.set_network_delegate(&network_delegate);
2473 TestDelegate d;
2474 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362475 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552476 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192477 req->Start();
[email protected]255620da2013-08-19 13:14:292478 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442479
2480 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2481 == std::string::npos);
2482
[email protected]22e045f2013-09-20 03:54:032483 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442484 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2485 }
2486}
2487
marqf14fff8d2015-12-02 15:52:292488// TODO(crbug.com/564656) This test is flaky on iOS.
2489#if defined(OS_IOS)
2490#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2491#else
2492#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2493#endif
[email protected]316c1e5e2012-09-12 15:17:442494TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2495 LocalHttpTestServer test_server;
2496 ASSERT_TRUE(test_server.Start());
2497
2498 // Set up a cookie.
2499 {
2500 TestNetworkDelegate network_delegate;
2501 default_context_.set_network_delegate(&network_delegate);
2502 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362503 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552504 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362505 &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_EQ(0, network_delegate.blocked_get_cookies_count());
2510 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2511 }
2512
2513 // Try to set-up another cookie and update the previous cookie.
2514 {
2515 TestNetworkDelegate network_delegate;
2516 default_context_.set_network_delegate(&network_delegate);
2517 TestDelegate d;
2518 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362519 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552520 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362521 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192522 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442523
[email protected]255620da2013-08-19 13:14:292524 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442525
2526 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2527 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2528 }
2529
2530 // Verify the cookies weren't saved or updated.
2531 {
2532 TestNetworkDelegate network_delegate;
2533 default_context_.set_network_delegate(&network_delegate);
2534 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362535 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552536 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192537 req->Start();
[email protected]255620da2013-08-19 13:14:292538 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442539
2540 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2541 == std::string::npos);
2542 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2543 != std::string::npos);
2544
2545 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2546 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2547 }
2548}
2549
2550TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2551 LocalHttpTestServer test_server;
2552 ASSERT_TRUE(test_server.Start());
2553
2554 // Set up an empty cookie.
2555 {
2556 TestNetworkDelegate network_delegate;
2557 default_context_.set_network_delegate(&network_delegate);
2558 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362559 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552560 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192561 req->Start();
[email protected]255620da2013-08-19 13:14:292562 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442563
2564 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2565 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2566 EXPECT_EQ(0, network_delegate.set_cookie_count());
2567 }
2568}
2569
2570TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2571 LocalHttpTestServer test_server;
2572 ASSERT_TRUE(test_server.Start());
2573
2574 // Set up a cookie.
2575 {
2576 TestNetworkDelegate network_delegate;
2577 default_context_.set_network_delegate(&network_delegate);
2578 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362579 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552580 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362581 &d));
[email protected]f7022f32014-08-21 16:32:192582 req->Start();
[email protected]255620da2013-08-19 13:14:292583 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442584
2585 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2586 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2587 }
2588
2589 // Verify that the cookie is set.
2590 {
2591 TestNetworkDelegate network_delegate;
2592 default_context_.set_network_delegate(&network_delegate);
2593 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362594 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552595 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192596 req->Start();
[email protected]255620da2013-08-19 13:14:292597 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442598
2599 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2600 != std::string::npos);
2601
2602 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2603 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2604 }
2605
2606 // Verify that the cookie isn't sent.
2607 {
2608 TestNetworkDelegate network_delegate;
2609 default_context_.set_network_delegate(&network_delegate);
2610 TestDelegate d;
2611 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362612 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552613 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192614 req->Start();
[email protected]255620da2013-08-19 13:14:292615 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442616
2617 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2618 == std::string::npos);
2619
[email protected]22e045f2013-09-20 03:54:032620 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442621 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2622 }
2623}
2624
2625TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2626 LocalHttpTestServer test_server;
2627 ASSERT_TRUE(test_server.Start());
2628
2629 // Set up a cookie.
2630 {
2631 TestNetworkDelegate network_delegate;
2632 default_context_.set_network_delegate(&network_delegate);
2633 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362634 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552635 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362636 &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_EQ(0, network_delegate.blocked_get_cookies_count());
2641 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2642 }
2643
2644 // Try to set-up another cookie and update the previous cookie.
2645 {
2646 TestNetworkDelegate network_delegate;
2647 default_context_.set_network_delegate(&network_delegate);
2648 TestDelegate d;
2649 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362650 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552651 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362652 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192653 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442654
[email protected]255620da2013-08-19 13:14:292655 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442656
2657 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2658 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2659 }
2660
2661 // Verify the cookies weren't saved or updated.
2662 {
2663 TestNetworkDelegate network_delegate;
2664 default_context_.set_network_delegate(&network_delegate);
2665 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362666 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552667 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192668 req->Start();
[email protected]255620da2013-08-19 13:14:292669 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442670
2671 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2672 == std::string::npos);
2673 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2674 != std::string::npos);
2675
2676 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2677 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2678 }
2679}
2680
mkwstc5fa7762016-03-28 09:28:232681TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262682 LocalHttpTestServer test_server;
2683 ASSERT_TRUE(test_server.Start());
2684
mkwst202534e32016-01-15 16:07:152685 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152686 default_context_.set_network_delegate(&network_delegate);
2687
mkwstf71d0bd2016-03-21 14:15:242688 const std::string kHost = "example.test";
2689 const std::string kSubHost = "subdomain.example.test";
2690 const std::string kCrossHost = "cross-origin.test";
2691
2692 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262693 {
mkwst3f3daac2015-02-26 20:15:262694 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362695 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242696 test_server.GetURL(kHost,
2697 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2698 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362699 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262700 req->Start();
2701 base::RunLoop().Run();
2702 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2703 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242704 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262705 }
2706
mkwstf71d0bd2016-03-21 14:15:242707 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262708 {
mkwst3f3daac2015-02-26 20:15:262709 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362710 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242711 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2712 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2713 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262714 req->Start();
2715 base::RunLoop().Run();
2716
mkwstf71d0bd2016-03-21 14:15:242717 EXPECT_NE(std::string::npos,
2718 d.data_received().find("StrictSameSiteCookie=1"));
2719 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262720 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2721 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2722 }
2723
mkwstf71d0bd2016-03-21 14:15:242724 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262725 {
mkwst3f3daac2015-02-26 20:15:262726 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362727 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242728 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2729 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2730 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152731 req->Start();
2732 base::RunLoop().Run();
2733
mkwstf71d0bd2016-03-21 14:15:242734 EXPECT_NE(std::string::npos,
2735 d.data_received().find("StrictSameSiteCookie=1"));
2736 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152737 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739 }
2740
mkwstf71d0bd2016-03-21 14:15:242741 // Verify that neither cookie is not sent for cross-site requests.
2742 {
2743 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362744 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242745 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2746 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2747 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2748 req->Start();
2749 base::RunLoop().Run();
2750
2751 EXPECT_EQ(std::string::npos,
2752 d.data_received().find("StrictSameSiteCookie=1"));
2753 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2754 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2755 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2756 }
2757
2758 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152759 // method is "safe".
2760 {
2761 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362762 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242763 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2764 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2765 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2766 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152767 req->Start();
2768 base::RunLoop().Run();
2769
mkwstf71d0bd2016-03-21 14:15:242770 EXPECT_EQ(std::string::npos,
2771 d.data_received().find("StrictSameSiteCookie=1"));
2772 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152773 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2774 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2775 }
2776
mkwstf71d0bd2016-03-21 14:15:242777 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152778 // method is unsafe (e.g. POST).
2779 {
2780 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362781 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242782 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2783 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2784 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152785 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262786 req->Start();
2787 base::RunLoop().Run();
2788
mkwstf71d0bd2016-03-21 14:15:242789 EXPECT_EQ(std::string::npos,
2790 d.data_received().find("StrictSameSiteCookie=1"));
2791 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262792 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2793 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2794 }
2795}
2796
estark557a5eb82015-12-01 22:57:102797// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362798TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552799 EmbeddedTestServer http_server;
2800 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362801 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552802 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2803 https_server.AddDefaultHandlers(
2804 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2805 ASSERT_TRUE(http_server.Start());
2806 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362807
estarkb15166b2015-12-18 16:56:382808 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362809 TestURLRequestContext context(true);
2810 context.set_network_delegate(&network_delegate);
2811 context.Init();
2812
estarkb15166b2015-12-18 16:56:382813 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362814 {
2815 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362816 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102817 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362818 DEFAULT_PRIORITY, &d));
2819 req->Start();
2820 base::RunLoop().Run();
2821 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2822 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2823 }
2824
2825 // Verify that the cookie is not set.
2826 {
2827 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362828 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552829 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362830 req->Start();
2831 base::RunLoop().Run();
2832
jww79aceda2015-12-07 01:56:342833 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2834 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362835 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2836 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2837 }
2838}
2839
estarkb15166b2015-12-18 16:56:382840TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552841 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2842 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362843 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552844 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362845
2846 TestNetworkDelegate network_delegate;
2847 TestURLRequestContext context(true);
2848 context.set_network_delegate(&network_delegate);
2849 context.Init();
2850
estarkb15166b2015-12-18 16:56:382851 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362852 {
2853 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362854 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102855 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552856 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362857 req->Start();
2858 base::RunLoop().Run();
2859 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2860 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2861 }
2862
2863 // Verify that the cookie is not set.
2864 {
2865 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362866 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552867 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362868 req->Start();
2869 base::RunLoop().Run();
2870
jww79aceda2015-12-07 01:56:342871 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362872 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2873 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2874 }
2875}
2876
estarkb15166b2015-12-18 16:56:382877TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552878 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2879 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362880 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552881 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362882
estarkb15166b2015-12-18 16:56:382883 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362884 TestURLRequestContext context(true);
2885 context.set_network_delegate(&network_delegate);
2886 context.Init();
2887
estarkb15166b2015-12-18 16:56:382888 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362889 {
2890 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362891 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102892 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552893 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362894 req->Start();
2895 base::RunLoop().Run();
2896 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2897 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2898 }
2899
2900 // Verify that the cookie is set.
2901 {
2902 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362903 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552904 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362905 req->Start();
2906 base::RunLoop().Run();
2907
jww79aceda2015-12-07 01:56:342908 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2909 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2910 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2911 }
2912}
2913
2914// Tests that secure cookies can't be set on non-secure origins if strict secure
2915// cookies are enabled.
2916TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2917 EmbeddedTestServer http_server;
2918 http_server.AddDefaultHandlers(
2919 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2920 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2921 https_server.AddDefaultHandlers(
2922 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2923 ASSERT_TRUE(http_server.Start());
2924 ASSERT_TRUE(https_server.Start());
2925
2926 TestExperimentalFeaturesNetworkDelegate network_delegate;
2927 TestURLRequestContext context(true);
2928 context.set_network_delegate(&network_delegate);
2929 context.Init();
2930
2931 // Try to set a Secure cookie, with experimental features enabled.
2932 {
2933 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362934 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342935 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2936 DEFAULT_PRIORITY, &d));
2937 req->Start();
2938 base::RunLoop().Run();
2939 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2940 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2941 }
2942
2943 // Verify that the cookie is not set.
2944 {
2945 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362946 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342947 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2948 req->Start();
2949 base::RunLoop().Run();
2950
2951 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2952 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2953 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2954 }
2955}
2956
2957// Tests that secure cookies can be set on secure origins even if strict secure
2958// cookies are enabled.
2959TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2960 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2961 https_server.AddDefaultHandlers(
2962 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2963 ASSERT_TRUE(https_server.Start());
2964
2965 TestExperimentalFeaturesNetworkDelegate network_delegate;
2966 TestURLRequestContext context(true);
2967 context.set_network_delegate(&network_delegate);
2968 context.Init();
2969
2970 // Try to set a Secure cookie, with experimental features enabled.
2971 {
2972 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362973 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342974 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2975 DEFAULT_PRIORITY, &d));
2976 req->Start();
2977 base::RunLoop().Run();
2978 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2979 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2980 }
2981
2982 // Verify that the cookie is not set.
2983 {
2984 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362985 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342986 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2987 req->Start();
2988 base::RunLoop().Run();
2989
2990 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362991 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2992 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2993 }
2994}
2995
mmenkefb18c772015-09-30 22:22:502996// Tests that a request is cancelled while entering suspend mode. Uses mocks
2997// rather than a spawned test server because the connection used to talk to
2998// the test server is affected by entering suspend mode on Android.
2999TEST_F(URLRequestTest, CancelOnSuspend) {
3000 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363001 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503002
3003 URLRequestFailedJob::AddUrlHandler();
3004
3005 TestDelegate d;
3006 // Request that just hangs.
3007 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:363008 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:503009 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3010 r->Start();
3011
3012 power_monitor_source->Suspend();
3013 // Wait for the suspend notification to cause the request to fail.
3014 base::RunLoop().Run();
3015 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3016 EXPECT_TRUE(d.request_failed());
3017 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3018
3019 URLRequestFilter::GetInstance()->ClearHandlers();
3020
3021 // Shouldn't be needed, but just in case.
3022 power_monitor_source->Resume();
3023}
3024
[email protected]5095cd72012-11-01 10:29:163025// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3026// value for the |fixed_date| argument given to the constructor.
3027class FixedDateNetworkDelegate : public TestNetworkDelegate {
3028 public:
3029 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3030 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203031 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163032
[email protected]cba24642014-08-15 20:49:593033 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203034 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593035 URLRequest* request,
3036 const CompletionCallback& callback,
3037 const HttpResponseHeaders* original_response_headers,
3038 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133039 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163040
3041 private:
3042 std::string fixed_date_;
3043
3044 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3045};
3046
3047int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593048 URLRequest* request,
3049 const CompletionCallback& callback,
3050 const HttpResponseHeaders* original_response_headers,
3051 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163052 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593053 HttpResponseHeaders* new_response_headers =
3054 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163055
3056 new_response_headers->RemoveHeader("Date");
3057 new_response_headers->AddHeader("Date: " + fixed_date_);
3058
3059 *override_response_headers = new_response_headers;
3060 return TestNetworkDelegate::OnHeadersReceived(request,
3061 callback,
3062 original_response_headers,
[email protected]5f714132014-03-26 10:41:163063 override_response_headers,
3064 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163065}
3066
3067// Test that cookie expiration times are adjusted for server/client clock
3068// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3069// headers by defaulting to GMT. (crbug.com/135131)
3070TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3071 LocalHttpTestServer test_server;
3072 ASSERT_TRUE(test_server.Start());
3073
3074 // Set up an expired cookie.
3075 {
3076 TestNetworkDelegate network_delegate;
3077 default_context_.set_network_delegate(&network_delegate);
3078 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363079 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193080 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553081 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363082 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193083 req->Start();
[email protected]255620da2013-08-19 13:14:293084 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163085 }
3086 // Verify that the cookie is not set.
3087 {
3088 TestNetworkDelegate network_delegate;
3089 default_context_.set_network_delegate(&network_delegate);
3090 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363091 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553092 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193093 req->Start();
[email protected]255620da2013-08-19 13:14:293094 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163095
3096 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3097 }
3098 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3099 {
3100 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3101 default_context_.set_network_delegate(&network_delegate);
3102 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363103 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193104 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553105 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363106 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193107 req->Start();
[email protected]255620da2013-08-19 13:14:293108 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163109 }
3110 // Verify that the cookie is set.
3111 {
3112 TestNetworkDelegate network_delegate;
3113 default_context_.set_network_delegate(&network_delegate);
3114 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363115 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553116 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193117 req->Start();
[email protected]255620da2013-08-19 13:14:293118 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163119
3120 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3121 }
3122}
3123
3124
[email protected]316c1e5e2012-09-12 15:17:443125// Check that it is impossible to change the referrer in the extra headers of
3126// an URLRequest.
3127TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3128 LocalHttpTestServer test_server;
3129 ASSERT_TRUE(test_server.Start());
3130
3131 // If extra headers contain referer and the request contains a referer,
3132 // only the latter shall be respected.
3133 {
3134 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363135 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553136 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193137 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443138
3139 HttpRequestHeaders headers;
3140 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193141 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443142
[email protected]f7022f32014-08-21 16:32:193143 req->Start();
[email protected]255620da2013-08-19 13:14:293144 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443145
3146 EXPECT_EQ("http://foo.com/", d.data_received());
3147 }
3148
3149 // If extra headers contain a referer but the request does not, no referer
3150 // shall be sent in the header.
3151 {
3152 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363153 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553154 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443155
3156 HttpRequestHeaders headers;
3157 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193158 req->SetExtraRequestHeaders(headers);
3159 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443160
[email protected]f7022f32014-08-21 16:32:193161 req->Start();
[email protected]255620da2013-08-19 13:14:293162 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443163
3164 EXPECT_EQ("None", d.data_received());
3165 }
3166}
3167
[email protected]b89290212009-08-14 22:37:353168class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113169 public:
mmenke9f2ec60c2015-06-01 20:59:473170 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113171
[email protected]b89290212009-08-14 22:37:353172 protected:
[email protected]21184962011-10-26 00:50:303173 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3174 // |request_method| is the method to use for the initial request.
3175 // |redirect_method| is the method that is expected to be used for the second
3176 // request, after redirection.
3177 // If |include_data| is true, data is uploaded with the request. The
3178 // response body is expected to match it exactly, if and only if
3179 // |request_method| == |redirect_method|.
3180 void HTTPRedirectMethodTest(const GURL& redirect_url,
3181 const std::string& request_method,
3182 const std::string& redirect_method,
3183 bool include_data) {
3184 static const char kData[] = "hello world";
3185 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363186 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363187 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193188 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303189 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073190 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303191 HttpRequestHeaders headers;
3192 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513193 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543194 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193195 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303196 }
[email protected]f7022f32014-08-21 16:32:193197 req->Start();
[email protected]255620da2013-08-19 13:14:293198 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193199 EXPECT_EQ(redirect_method, req->method());
3200 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
robpercival214763f2016-07-01 23:27:013201 EXPECT_THAT(req->status().error(), IsOk());
[email protected]21184962011-10-26 00:50:303202 if (include_data) {
3203 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543204 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3205 HttpRequestHeaders::kContentLength));
3206 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3207 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303208 EXPECT_EQ(kData, d.data_received());
3209 } else {
svaldez5b3a8972015-10-09 23:23:543210 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3211 HttpRequestHeaders::kContentLength));
3212 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3213 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303214 EXPECT_NE(kData, d.data_received());
3215 }
3216 }
3217 if (HasFailure())
3218 LOG(WARNING) << "Request method was: " << request_method;
3219 }
3220
jww5fe460ff2015-03-28 00:22:513221 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3222 // |request_method| is the method to use for the initial request.
3223 // |redirect_method| is the method that is expected to be used for the second
3224 // request, after redirection.
3225 // |origin_value| is the expected value for the Origin header after
3226 // redirection. If empty, expects that there will be no Origin header.
3227 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3228 const std::string& request_method,
3229 const std::string& redirect_method,
3230 const std::string& origin_value) {
3231 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363232 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513233 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3234 req->set_method(request_method);
3235 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3236 redirect_url.GetOrigin().spec(), false);
3237 req->Start();
3238
3239 base::RunLoop().Run();
3240
3241 EXPECT_EQ(redirect_method, req->method());
3242 // Note that there is no check for request success here because, for
3243 // purposes of testing, the request very well may fail. For example, if the
3244 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3245 // origin, there is not an HTTPS server in this unit test framework, so the
3246 // request would fail. However, that's fine, as long as the request headers
3247 // are in order and pass the checks below.
3248 if (origin_value.empty()) {
3249 EXPECT_FALSE(
3250 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3251 } else {
3252 std::string origin_header;
3253 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3254 HttpRequestHeaders::kOrigin, &origin_header));
3255 EXPECT_EQ(origin_value, origin_header);
3256 }
3257 }
3258
[email protected]762d2db2010-01-11 19:03:013259 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013260 const int kMsgSize = 20000; // multiple of 10
3261 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483262 char* uploadBytes = new char[kMsgSize+1];
3263 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013264 char marker = 'a';
3265 for (int idx = 0; idx < kMsgSize/10; idx++) {
3266 memcpy(ptr, "----------", 10);
3267 ptr += 10;
3268 if (idx % 100 == 0) {
3269 ptr--;
3270 *ptr++ = marker;
3271 if (++marker > 'z')
3272 marker = 'a';
3273 }
3274 }
3275 uploadBytes[kMsgSize] = '\0';
3276
[email protected]762d2db2010-01-11 19:03:013277 for (int i = 0; i < kIterations; ++i) {
3278 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363279 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553280 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193281 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013282
mmenkecbc2b712014-10-09 20:29:073283 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013284
[email protected]f7022f32014-08-21 16:32:193285 r->Start();
3286 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013287
[email protected]255620da2013-08-19 13:14:293288 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013289
[email protected]329b68b2012-11-14 17:54:273290 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193291 << "request failed: " << r->status().status()
3292 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013293
3294 EXPECT_FALSE(d.received_data_before_response());
3295 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013296 }
3297 delete[] uploadBytes;
3298 }
3299
[email protected]ede03212012-09-07 12:52:263300 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343301 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363302 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553303 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363304 base::IntToString(num_cookies)),
3305 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343306
[email protected]f7022f32014-08-21 16:32:193307 r->Start();
3308 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343309
[email protected]255620da2013-08-19 13:14:293310 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343311
[email protected]f7022f32014-08-21 16:32:193312 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343313
tommycli59a63432015-11-06 00:10:553314 if (!is_success)
[email protected]f7022f32014-08-21 16:32:193315 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343316
3317 return is_success;
3318 }
3319
tommycli59a63432015-11-06 00:10:553320 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503321
tommycli59a63432015-11-06 00:10:553322 private:
[email protected]1700c6a2012-02-22 18:07:073323 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353324};
3325
tommycli59a63432015-11-06 00:10:553326namespace {
3327
danakj8522a25b2016-04-16 00:17:363328std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553329 const test_server::HttpRequest& request) {
3330 if (request.headers.find("Host") == request.headers.end() ||
3331 request.headers.at("Host") != "www.redirect.com" ||
3332 request.method != test_server::METHOD_CONNECT) {
3333 return nullptr;
3334 }
3335
danakj8522a25b2016-04-16 00:17:363336 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553337 new test_server::BasicHttpResponse);
3338 http_response->set_code(HTTP_FOUND);
3339 http_response->AddCustomHeader("Location",
3340 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483341 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553342}
3343
3344} // namespace
3345
nharperb7441ef2016-01-25 23:54:143346class TestSSLConfigService : public SSLConfigService {
3347 public:
3348 TestSSLConfigService(bool ev_enabled,
3349 bool online_rev_checking,
3350 bool rev_checking_required_local_anchors,
3351 bool token_binding_enabled)
3352 : ev_enabled_(ev_enabled),
3353 online_rev_checking_(online_rev_checking),
3354 rev_checking_required_local_anchors_(
3355 rev_checking_required_local_anchors),
3356 token_binding_enabled_(token_binding_enabled),
davidben5a312152016-06-27 22:11:473357 min_version_(kDefaultSSLVersionMin) {}
nharperb7441ef2016-01-25 23:54:143358
3359 void set_min_version(uint16_t version) { min_version_ = version; }
3360
nharperb7441ef2016-01-25 23:54:143361 // SSLConfigService:
3362 void GetSSLConfig(SSLConfig* config) override {
3363 *config = SSLConfig();
3364 config->rev_checking_enabled = online_rev_checking_;
3365 config->verify_ev_cert = ev_enabled_;
3366 config->rev_checking_required_local_anchors =
3367 rev_checking_required_local_anchors_;
nharperb7441ef2016-01-25 23:54:143368 if (min_version_) {
3369 config->version_min = min_version_;
3370 }
3371 if (token_binding_enabled_) {
3372 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3373 }
3374 }
3375
3376 protected:
3377 ~TestSSLConfigService() override {}
3378
3379 private:
3380 const bool ev_enabled_;
3381 const bool online_rev_checking_;
3382 const bool rev_checking_required_local_anchors_;
3383 const bool token_binding_enabled_;
3384 uint16_t min_version_;
nharperb7441ef2016-01-25 23:54:143385};
3386
3387// TODO(svaldez): Update tests to use EmbeddedTestServer.
3388#if !defined(OS_IOS)
3389class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3390 public:
3391 void SetUp() override {
3392 default_context_.set_ssl_config_service(
3393 new TestSSLConfigService(false, false, false, true));
3394 channel_id_service_.reset(new ChannelIDService(
3395 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3396 default_context_.set_channel_id_service(channel_id_service_.get());
3397 URLRequestTestHTTP::SetUp();
3398 }
3399
3400 protected:
danakj8522a25b2016-04-16 00:17:363401 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143402};
3403
3404TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3405 SpawnedTestServer::SSLOptions ssl_options;
3406 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3407 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3408 ssl_options,
3409 base::FilePath(kTestFilePath));
3410 ASSERT_TRUE(https_test_server.Start());
3411
3412 TestDelegate d;
3413 {
danakj8522a25b2016-04-16 00:17:363414 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143415 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3416 r->Start();
3417 EXPECT_TRUE(r->is_pending());
3418
3419 base::RunLoop().Run();
3420
3421 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3422
3423 HttpRequestHeaders headers;
3424 std::string token_binding_header, token_binding_message;
3425 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3426 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3427 &token_binding_header));
3428 EXPECT_TRUE(base::Base64UrlDecode(
3429 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3430 &token_binding_message));
nharperd6e65822016-03-30 23:05:483431 std::vector<TokenBinding> token_bindings;
3432 ASSERT_TRUE(
3433 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3434 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143435
3436 EXPECT_GT(d.bytes_received(), 0);
3437 std::string ekm = d.data_received();
3438
nharperd6e65822016-03-30 23:05:483439 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3440 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3441 token_bindings[0].signature, ekm));
nharperb7441ef2016-01-25 23:54:143442 }
3443}
nharperd6e65822016-03-30 23:05:483444
3445TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3446 SpawnedTestServer::SSLOptions ssl_options;
3447 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3448 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3449 ssl_options,
3450 base::FilePath(kTestFilePath));
3451 ASSERT_TRUE(https_test_server.Start());
3452
3453 TestDelegate d;
3454 {
3455 GURL redirect_url =
3456 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363457 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483458 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3459 r->Start();
3460 EXPECT_TRUE(r->is_pending());
3461
3462 base::RunLoop().Run();
3463
3464 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3465
3466 HttpRequestHeaders headers;
3467 std::string token_binding_header, token_binding_message;
3468 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3469 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3470 &token_binding_header));
3471 EXPECT_TRUE(base::Base64UrlDecode(
3472 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3473 &token_binding_message));
3474 std::vector<TokenBinding> token_bindings;
3475 ASSERT_TRUE(
3476 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3477 ASSERT_EQ(2ull, token_bindings.size());
3478
3479 EXPECT_GT(d.bytes_received(), 0);
3480 std::string ekm = d.data_received();
3481
3482 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3483 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3484 token_bindings[0].signature, ekm));
3485 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
3486 EXPECT_TRUE(VerifyEKMSignature(token_bindings[1].ec_point,
3487 token_bindings[1].signature, ekm));
3488 }
3489}
3490
3491// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3492// EmbeddedTestServer once crbug.com/599187 is resolved.
3493#if !defined(OS_ANDROID)
3494TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3495 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3496 SpawnedTestServer::kLocalhost,
3497 base::FilePath());
3498 ASSERT_TRUE(http_server.Start());
3499 SpawnedTestServer::SSLOptions ssl_options;
3500 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3501 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3502 ssl_options,
3503 base::FilePath(kTestFilePath));
3504 ASSERT_TRUE(https_test_server.Start());
3505
3506 TestDelegate d;
3507 {
3508 GURL redirect_url = http_server.GetURL(
3509 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363510 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483511 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3512 r->Start();
3513 EXPECT_TRUE(r->is_pending());
3514
3515 base::RunLoop().Run();
3516
3517 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3518
3519 HttpRequestHeaders headers;
3520 std::string token_binding_header, token_binding_message;
3521 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3522 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3523 &token_binding_header));
3524 EXPECT_TRUE(base::Base64UrlDecode(
3525 token_binding_header, base::Base64UrlDecodePolicy::REQUIRE_PADDING,
3526 &token_binding_message));
3527 std::vector<TokenBinding> token_bindings;
3528 ASSERT_TRUE(
3529 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3530 ASSERT_EQ(1ull, token_bindings.size());
3531
3532 EXPECT_GT(d.bytes_received(), 0);
3533 std::string ekm = d.data_received();
3534
3535 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
3536 EXPECT_TRUE(VerifyEKMSignature(token_bindings[0].ec_point,
3537 token_bindings[0].signature, ekm));
3538 }
3539}
3540
3541// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363542// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483543// support Token Binding, then we do not send a Sec-Token-Binding when following
3544// the redirect.
3545TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3546 SpawnedTestServer::SSLOptions ssl_options;
3547 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3548 ssl_options,
3549 base::FilePath(kTestFilePath));
3550 ASSERT_TRUE(https_test_server.Start());
3551 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3552 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3553 ssl_options,
3554 base::FilePath(kTestFilePath));
3555 ASSERT_TRUE(token_binding_test_server.Start());
3556
3557 TestDelegate d;
3558 {
3559 GURL redirect_url = token_binding_test_server.GetURL(
3560 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363561 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483562 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3563 r->Start();
3564 EXPECT_TRUE(r->is_pending());
3565
3566 base::RunLoop().Run();
3567
3568 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3569
3570 HttpRequestHeaders headers;
3571 std::string token_binding_header, token_binding_message;
3572 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3573 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3574 &token_binding_header));
3575 }
3576}
3577#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143578#endif // !defined(OS_IOS)
3579
3580// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113581// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553582// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113583// follow.
[email protected]f2f31b32013-01-16 23:24:093584TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553585 http_test_server()->RegisterRequestHandler(
3586 base::Bind(&HandleRedirectConnect));
3587 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113588
[email protected]ceefd7fd2012-11-29 00:36:243589 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043590 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553591 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503592
[email protected]d1ec59082009-02-11 02:48:153593 TestDelegate d;
3594 {
danakj8522a25b2016-04-16 00:17:363595 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363596 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193597 r->Start();
3598 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153599
[email protected]255620da2013-08-19 13:14:293600 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153601
[email protected]f7022f32014-08-21 16:32:193602 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153603 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193604 EXPECT_TRUE(r->proxy_server().IsEmpty());
robpercival214763f2016-07-01 23:27:013605 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]dc651782009-02-14 01:45:083606 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153607 // We should not have followed the redirect.
3608 EXPECT_EQ(0, d.received_redirect_count());
3609 }
3610}
3611
[email protected]8202d0c2011-02-23 08:31:143612// This is the same as the previous test, but checks that the network delegate
3613// registers the error.
[email protected]c044616e2013-02-20 02:01:263614TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553615 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143616
[email protected]ceefd7fd2012-11-29 00:36:243617 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043618 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553619 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503620
[email protected]8202d0c2011-02-23 08:31:143621 TestDelegate d;
3622 {
danakj8522a25b2016-04-16 00:17:363623 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363624 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193625 r->Start();
3626 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143627
[email protected]255620da2013-08-19 13:14:293628 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143629
[email protected]f7022f32014-08-21 16:32:193630 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153631 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193632 EXPECT_TRUE(r->proxy_server().IsEmpty());
robpercival214763f2016-07-01 23:27:013633 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143634 EXPECT_EQ(1, d.response_started_count());
3635 // We should not have followed the redirect.
3636 EXPECT_EQ(0, d.received_redirect_count());
3637
3638 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:013639 EXPECT_THAT(network_delegate.last_error(),
3640 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143641 }
3642}
3643
[email protected]dc5a5cf2012-09-26 02:49:303644// Tests that we can block and asynchronously return OK in various stages.
3645TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3646 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3647 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3648 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3649 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3650 };
3651 static const size_t blocking_stages_length = arraysize(blocking_stages);
3652
tommycli59a63432015-11-06 00:10:553653 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303654
3655 TestDelegate d;
3656 BlockingNetworkDelegate network_delegate(
3657 BlockingNetworkDelegate::USER_CALLBACK);
3658 network_delegate.set_block_on(
3659 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3660 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3661 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3662
3663 TestURLRequestContext context(true);
3664 context.set_network_delegate(&network_delegate);
3665 context.Init();
3666
3667 {
danakj8522a25b2016-04-16 00:17:363668 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553669 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303670
[email protected]f7022f32014-08-21 16:32:193671 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303672 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293673 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303674 EXPECT_EQ(blocking_stages[i],
3675 network_delegate.stage_blocked_for_callback());
3676 network_delegate.DoCallback(OK);
3677 }
[email protected]255620da2013-08-19 13:14:293678 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193679 EXPECT_EQ(200, r->GetResponseCode());
3680 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303681 EXPECT_EQ(1, network_delegate.created_requests());
3682 EXPECT_EQ(0, network_delegate.destroyed_requests());
3683 }
3684 EXPECT_EQ(1, network_delegate.destroyed_requests());
3685}
3686
[email protected]4c76d7c2011-04-15 19:14:123687// Tests that the network delegate can block and cancel a request.
3688TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553689 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123690
3691 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303692 BlockingNetworkDelegate network_delegate(
3693 BlockingNetworkDelegate::AUTO_CALLBACK);
3694 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3695 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123696
[email protected]d5a4dd62012-05-23 01:41:043697 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553698 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503699
[email protected]4c76d7c2011-04-15 19:14:123700 {
danakj8522a25b2016-04-16 00:17:363701 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553702 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123703
[email protected]f7022f32014-08-21 16:32:193704 r->Start();
[email protected]255620da2013-08-19 13:14:293705 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123706
[email protected]f7022f32014-08-21 16:32:193707 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153708 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193709 EXPECT_TRUE(r->proxy_server().IsEmpty());
robpercival214763f2016-07-01 23:27:013710 EXPECT_THAT(r->status().error(), IsError(ERR_EMPTY_RESPONSE));
[email protected]4c76d7c2011-04-15 19:14:123711 EXPECT_EQ(1, network_delegate.created_requests());
3712 EXPECT_EQ(0, network_delegate.destroyed_requests());
3713 }
3714 EXPECT_EQ(1, network_delegate.destroyed_requests());
3715}
3716
[email protected]b4438d32012-09-27 06:15:303717// Helper function for NetworkDelegateCancelRequestAsynchronously and
3718// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3719// delegate operating in |block_mode| and a request for |url|. It blocks the
3720// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3721void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3722 BlockingNetworkDelegate::Stage stage,
3723 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363724 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303725 BlockingNetworkDelegate network_delegate(block_mode);
3726 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3727 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363728
[email protected]b4438d32012-09-27 06:15:303729 TestURLRequestContext context(true);
3730 context.set_network_delegate(&network_delegate);
3731 context.Init();
[email protected]3cd384c602011-08-31 16:12:363732
3733 {
danakj8522a25b2016-04-16 00:17:363734 std::unique_ptr<URLRequest> r(
3735 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363736
[email protected]f7022f32014-08-21 16:32:193737 r->Start();
[email protected]255620da2013-08-19 13:14:293738 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363739
[email protected]f7022f32014-08-21 16:32:193740 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153741 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193742 EXPECT_TRUE(r->proxy_server().IsEmpty());
robpercival214763f2016-07-01 23:27:013743 EXPECT_THAT(r->status().error(), IsError(ERR_BLOCKED_BY_CLIENT));
[email protected]3cd384c602011-08-31 16:12:363744 EXPECT_EQ(1, network_delegate.created_requests());
3745 EXPECT_EQ(0, network_delegate.destroyed_requests());
3746 }
3747 EXPECT_EQ(1, network_delegate.destroyed_requests());
3748}
3749
[email protected]b4438d32012-09-27 06:15:303750// The following 3 tests check that the network delegate can cancel a request
3751// synchronously in various stages of the request.
3752TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553753 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303754 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
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, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553760 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303761 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
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, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553767 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303768 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3769 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553770 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303771}
3772
3773// The following 3 tests check that the network delegate can cancel a request
3774// asynchronously in various stages of the request.
3775TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553776 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303777 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3778 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553779 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303780}
3781
3782TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553783 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303784 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3785 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553786 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303787}
3788
3789TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553790 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303791 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3792 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553793 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303794}
3795
[email protected]4c76d7c2011-04-15 19:14:123796// Tests that the network delegate can block and redirect a request to a new
3797// URL.
3798TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553799 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123800
3801 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303802 BlockingNetworkDelegate network_delegate(
3803 BlockingNetworkDelegate::AUTO_CALLBACK);
3804 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553805 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123806 network_delegate.set_redirect_url(redirect_url);
3807
[email protected]d5a4dd62012-05-23 01:41:043808 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553809 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503810
[email protected]4c76d7c2011-04-15 19:14:123811 {
tommycli59a63432015-11-06 00:10:553812 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363813 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363814 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123815
[email protected]6be6fa92014-08-06 23:44:563816 // Quit after hitting the redirect, so can check the headers.
3817 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193818 r->Start();
[email protected]255620da2013-08-19 13:14:293819 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123820
[email protected]6be6fa92014-08-06 23:44:563821 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193822 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3823 EXPECT_EQ(307, r->GetResponseCode());
3824 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563825 std::string location;
[email protected]f7022f32014-08-21 16:32:193826 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3827 &location));
[email protected]6be6fa92014-08-06 23:44:563828 EXPECT_EQ(redirect_url, GURL(location));
3829
3830 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193831 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563832 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193833 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553834 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093835 // before_send_headers_with_proxy_count only increments for headers sent
3836 // through an untunneled proxy.
3837 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553838 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3839 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273840
[email protected]f7022f32014-08-21 16:32:193841 EXPECT_EQ(0, r->status().error());
3842 EXPECT_EQ(redirect_url, r->url());
3843 EXPECT_EQ(original_url, r->original_url());
3844 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123845 EXPECT_EQ(1, network_delegate.created_requests());
3846 EXPECT_EQ(0, network_delegate.destroyed_requests());
3847 }
3848 EXPECT_EQ(1, network_delegate.destroyed_requests());
3849}
3850
[email protected]b813ed72012-04-05 08:21:363851// Tests that the network delegate can block and redirect a request to a new
3852// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3853TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553854 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363855
3856 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303857 BlockingNetworkDelegate network_delegate(
3858 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553859 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363860 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363861
[email protected]d5a4dd62012-05-23 01:41:043862 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553863 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363864
3865 {
tommycli59a63432015-11-06 00:10:553866 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363867 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363868 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363869
[email protected]6be6fa92014-08-06 23:44:563870 // Quit after hitting the redirect, so can check the headers.
3871 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193872 r->Start();
[email protected]255620da2013-08-19 13:14:293873 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363874
[email protected]6be6fa92014-08-06 23:44:563875 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193876 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3877 EXPECT_EQ(307, r->GetResponseCode());
3878 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563879 std::string location;
[email protected]f7022f32014-08-21 16:32:193880 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3881 &location));
[email protected]6be6fa92014-08-06 23:44:563882 EXPECT_EQ(redirect_url, GURL(location));
3883
3884 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193885 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563886 base::RunLoop().Run();
3887
[email protected]f7022f32014-08-21 16:32:193888 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553889 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093890 // before_send_headers_with_proxy_count only increments for headers sent
3891 // through an untunneled proxy.
3892 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553893 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3894 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193895 EXPECT_EQ(0, r->status().error());
3896 EXPECT_EQ(redirect_url, r->url());
3897 EXPECT_EQ(original_url, r->original_url());
3898 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363899 EXPECT_EQ(1, network_delegate.created_requests());
3900 EXPECT_EQ(0, network_delegate.destroyed_requests());
3901 }
3902 EXPECT_EQ(1, network_delegate.destroyed_requests());
3903}
3904
[email protected]3c5ca8c2011-09-29 01:14:513905// Tests that redirects caused by the network delegate preserve POST data.
3906TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553907 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513908
3909 const char kData[] = "hello world";
3910
3911 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303912 BlockingNetworkDelegate network_delegate(
3913 BlockingNetworkDelegate::AUTO_CALLBACK);
3914 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553915 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513916 network_delegate.set_redirect_url(redirect_url);
3917
[email protected]ef2bf422012-05-11 03:27:093918 TestURLRequestContext context(true);
3919 context.set_network_delegate(&network_delegate);
3920 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513921
3922 {
tommycli59a63432015-11-06 00:10:553923 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363924 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363925 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193926 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073927 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513928 HttpRequestHeaders headers;
3929 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513930 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193931 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563932
3933 // Quit after hitting the redirect, so can check the headers.
3934 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193935 r->Start();
[email protected]255620da2013-08-19 13:14:293936 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513937
[email protected]6be6fa92014-08-06 23:44:563938 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193939 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3940 EXPECT_EQ(307, r->GetResponseCode());
3941 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563942 std::string location;
[email protected]f7022f32014-08-21 16:32:193943 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3944 &location));
[email protected]6be6fa92014-08-06 23:44:563945 EXPECT_EQ(redirect_url, GURL(location));
3946
3947 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193948 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563949 base::RunLoop().Run();
3950
[email protected]f7022f32014-08-21 16:32:193951 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3952 EXPECT_EQ(0, r->status().error());
3953 EXPECT_EQ(redirect_url, r->url());
3954 EXPECT_EQ(original_url, r->original_url());
3955 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513956 EXPECT_EQ(1, network_delegate.created_requests());
3957 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193958 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513959 EXPECT_EQ(kData, d.data_received());
3960 }
3961 EXPECT_EQ(1, network_delegate.destroyed_requests());
3962}
3963
[email protected]5f714132014-03-26 10:41:163964// Tests that the network delegate can block and redirect a request to a new
3965// URL during OnHeadersReceived.
3966TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553967 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163968
3969 TestDelegate d;
3970 BlockingNetworkDelegate network_delegate(
3971 BlockingNetworkDelegate::AUTO_CALLBACK);
3972 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553973 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163974 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3975
3976 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553977 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163978
3979 {
tommycli59a63432015-11-06 00:10:553980 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363981 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363982 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163983
[email protected]f7022f32014-08-21 16:32:193984 r->Start();
[email protected]5f714132014-03-26 10:41:163985 base::RunLoop().Run();
3986
[email protected]f7022f32014-08-21 16:32:193987 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
tommycli59a63432015-11-06 00:10:553988 EXPECT_TRUE(r->proxy_server().Equals(http_test_server()->host_port_pair()));
ryansturm49a8cb12016-06-15 16:51:093989 // before_send_headers_with_proxy_count only increments for headers sent
3990 // through an untunneled proxy.
3991 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553992 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3993 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193994
robpercival214763f2016-07-01 23:27:013995 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:193996 EXPECT_EQ(redirect_url, r->url());
3997 EXPECT_EQ(original_url, r->original_url());
3998 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163999 EXPECT_EQ(2, network_delegate.created_requests());
4000 EXPECT_EQ(0, network_delegate.destroyed_requests());
4001 }
4002 EXPECT_EQ(1, network_delegate.destroyed_requests());
4003}
4004
[email protected]c2911d72011-10-03 22:16:364005// Tests that the network delegate can synchronously complete OnAuthRequired
4006// by taking no action. This indicates that the NetworkDelegate does not want to
4007// handle the challenge, and is passing the buck along to the
4008// URLRequest::Delegate.
4009TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554010 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364011
4012 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304013 BlockingNetworkDelegate network_delegate(
4014 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364015
[email protected]ef2bf422012-05-11 03:27:094016 TestURLRequestContext context(true);
4017 context.set_network_delegate(&network_delegate);
4018 context.Init();
[email protected]c2911d72011-10-03 22:16:364019
[email protected]f3cf9802011-10-28 18:44:584020 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364021
4022 {
tommycli59a63432015-11-06 00:10:554023 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364024 std::unique_ptr<URLRequest> r(
4025 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194026 r->Start();
[email protected]79e1fd62013-06-20 06:50:044027
[email protected]255620da2013-08-19 13:14:294028 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044029
[email protected]f7022f32014-08-21 16:32:194030 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4031 EXPECT_EQ(0, r->status().error());
4032 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044033 EXPECT_TRUE(d.auth_required_called());
4034 EXPECT_EQ(1, network_delegate.created_requests());
4035 EXPECT_EQ(0, network_delegate.destroyed_requests());
4036 }
4037 EXPECT_EQ(1, network_delegate.destroyed_requests());
4038}
4039
4040TEST_F(URLRequestTestHTTP,
4041 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554042 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044043
4044 TestDelegate d;
4045 BlockingNetworkDelegate network_delegate(
4046 BlockingNetworkDelegate::SYNCHRONOUS);
4047
4048 TestURLRequestContext context(true);
4049 context.set_network_delegate(&network_delegate);
4050 context.Init();
4051
4052 d.set_credentials(AuthCredentials(kUser, kSecret));
4053
4054 {
tommycli59a63432015-11-06 00:10:554055 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364056 std::unique_ptr<URLRequest> r(
4057 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194058 r->Start();
[email protected]79e1fd62013-06-20 06:50:044059
4060 {
4061 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194062 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044063 EXPECT_FALSE(headers.HasHeader("Authorization"));
4064 }
4065
[email protected]255620da2013-08-19 13:14:294066 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364067
[email protected]f7022f32014-08-21 16:32:194068 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4069 EXPECT_EQ(0, r->status().error());
4070 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364071 EXPECT_TRUE(d.auth_required_called());
4072 EXPECT_EQ(1, network_delegate.created_requests());
4073 EXPECT_EQ(0, network_delegate.destroyed_requests());
4074 }
4075 EXPECT_EQ(1, network_delegate.destroyed_requests());
4076}
4077
4078// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404079// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364080TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554081 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364082
4083 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304084 BlockingNetworkDelegate network_delegate(
4085 BlockingNetworkDelegate::SYNCHRONOUS);
4086 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364087 network_delegate.set_auth_retval(
4088 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4089
[email protected]f3cf9802011-10-28 18:44:584090 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364091
[email protected]ef2bf422012-05-11 03:27:094092 TestURLRequestContext context(true);
4093 context.set_network_delegate(&network_delegate);
4094 context.Init();
[email protected]c2911d72011-10-03 22:16:364095
4096 {
tommycli59a63432015-11-06 00:10:554097 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364098 std::unique_ptr<URLRequest> r(
4099 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194100 r->Start();
[email protected]255620da2013-08-19 13:14:294101 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364102
[email protected]f7022f32014-08-21 16:32:194103 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4104 EXPECT_EQ(0, r->status().error());
4105 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364106 EXPECT_FALSE(d.auth_required_called());
4107 EXPECT_EQ(1, network_delegate.created_requests());
4108 EXPECT_EQ(0, network_delegate.destroyed_requests());
4109 }
4110 EXPECT_EQ(1, network_delegate.destroyed_requests());
4111}
4112
[email protected]79e1fd62013-06-20 06:50:044113// Same as above, but also tests that GetFullRequestHeaders returns the proper
4114// headers (for the first or second request) when called at the proper times.
4115TEST_F(URLRequestTestHTTP,
4116 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554117 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044118
4119 TestDelegate d;
4120 BlockingNetworkDelegate network_delegate(
4121 BlockingNetworkDelegate::SYNCHRONOUS);
4122 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4123 network_delegate.set_auth_retval(
4124 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4125
4126 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4127
4128 TestURLRequestContext context(true);
4129 context.set_network_delegate(&network_delegate);
4130 context.Init();
4131
4132 {
tommycli59a63432015-11-06 00:10:554133 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364134 std::unique_ptr<URLRequest> r(
4135 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194136 r->Start();
[email protected]255620da2013-08-19 13:14:294137 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044138
[email protected]f7022f32014-08-21 16:32:194139 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4140 EXPECT_EQ(0, r->status().error());
4141 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044142 EXPECT_FALSE(d.auth_required_called());
4143 EXPECT_EQ(1, network_delegate.created_requests());
4144 EXPECT_EQ(0, network_delegate.destroyed_requests());
4145
4146 {
4147 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194148 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044149 EXPECT_TRUE(headers.HasHeader("Authorization"));
4150 }
4151 }
4152 EXPECT_EQ(1, network_delegate.destroyed_requests());
4153}
4154
[email protected]c2911d72011-10-03 22:16:364155// Tests that the network delegate can synchronously complete OnAuthRequired
4156// by cancelling authentication.
4157TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554158 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364159
4160 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304161 BlockingNetworkDelegate network_delegate(
4162 BlockingNetworkDelegate::SYNCHRONOUS);
4163 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364164 network_delegate.set_auth_retval(
4165 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4166
[email protected]ef2bf422012-05-11 03:27:094167 TestURLRequestContext context(true);
4168 context.set_network_delegate(&network_delegate);
4169 context.Init();
[email protected]c2911d72011-10-03 22:16:364170
4171 {
tommycli59a63432015-11-06 00:10:554172 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364173 std::unique_ptr<URLRequest> r(
4174 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194175 r->Start();
[email protected]255620da2013-08-19 13:14:294176 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364177
[email protected]f7022f32014-08-21 16:32:194178 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:014179 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:194180 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364181 EXPECT_FALSE(d.auth_required_called());
4182 EXPECT_EQ(1, network_delegate.created_requests());
4183 EXPECT_EQ(0, network_delegate.destroyed_requests());
4184 }
4185 EXPECT_EQ(1, network_delegate.destroyed_requests());
4186}
4187
4188// Tests that the network delegate can asynchronously complete OnAuthRequired
4189// by taking no action. This indicates that the NetworkDelegate does not want
4190// to handle the challenge, and is passing the buck along to the
4191// URLRequest::Delegate.
4192TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554193 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364194
4195 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304196 BlockingNetworkDelegate network_delegate(
4197 BlockingNetworkDelegate::AUTO_CALLBACK);
4198 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364199
[email protected]ef2bf422012-05-11 03:27:094200 TestURLRequestContext context(true);
4201 context.set_network_delegate(&network_delegate);
4202 context.Init();
[email protected]c2911d72011-10-03 22:16:364203
[email protected]f3cf9802011-10-28 18:44:584204 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364205
4206 {
tommycli59a63432015-11-06 00:10:554207 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364208 std::unique_ptr<URLRequest> r(
4209 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194210 r->Start();
[email protected]255620da2013-08-19 13:14:294211 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364212
[email protected]f7022f32014-08-21 16:32:194213 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4214 EXPECT_EQ(0, r->status().error());
4215 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364216 EXPECT_TRUE(d.auth_required_called());
4217 EXPECT_EQ(1, network_delegate.created_requests());
4218 EXPECT_EQ(0, network_delegate.destroyed_requests());
4219 }
4220 EXPECT_EQ(1, network_delegate.destroyed_requests());
4221}
4222
4223// Tests that the network delegate can asynchronously complete OnAuthRequired
4224// by setting credentials.
4225TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554226 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364227
4228 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304229 BlockingNetworkDelegate network_delegate(
4230 BlockingNetworkDelegate::AUTO_CALLBACK);
4231 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364232 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364233 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4234
[email protected]f3cf9802011-10-28 18:44:584235 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364236 network_delegate.set_auth_credentials(auth_credentials);
4237
[email protected]ef2bf422012-05-11 03:27:094238 TestURLRequestContext context(true);
4239 context.set_network_delegate(&network_delegate);
4240 context.Init();
[email protected]c2911d72011-10-03 22:16:364241
4242 {
tommycli59a63432015-11-06 00:10:554243 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364244 std::unique_ptr<URLRequest> r(
4245 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194246 r->Start();
[email protected]255620da2013-08-19 13:14:294247 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364248
[email protected]f7022f32014-08-21 16:32:194249 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
4250 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:364251
[email protected]f7022f32014-08-21 16:32:194252 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364253 EXPECT_FALSE(d.auth_required_called());
4254 EXPECT_EQ(1, network_delegate.created_requests());
4255 EXPECT_EQ(0, network_delegate.destroyed_requests());
4256 }
4257 EXPECT_EQ(1, network_delegate.destroyed_requests());
4258}
4259
4260// Tests that the network delegate can asynchronously complete OnAuthRequired
4261// by cancelling authentication.
4262TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554263 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364264
4265 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304266 BlockingNetworkDelegate network_delegate(
4267 BlockingNetworkDelegate::AUTO_CALLBACK);
4268 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364269 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364270 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4271
[email protected]ef2bf422012-05-11 03:27:094272 TestURLRequestContext context(true);
4273 context.set_network_delegate(&network_delegate);
4274 context.Init();
[email protected]c2911d72011-10-03 22:16:364275
4276 {
tommycli59a63432015-11-06 00:10:554277 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364278 std::unique_ptr<URLRequest> r(
4279 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194280 r->Start();
[email protected]255620da2013-08-19 13:14:294281 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364282
[email protected]f7022f32014-08-21 16:32:194283 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:014284 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:194285 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364286 EXPECT_FALSE(d.auth_required_called());
4287 EXPECT_EQ(1, network_delegate.created_requests());
4288 EXPECT_EQ(0, network_delegate.destroyed_requests());
4289 }
4290 EXPECT_EQ(1, network_delegate.destroyed_requests());
4291}
4292
[email protected]9045b8822012-01-13 20:35:354293// Tests that we can handle when a network request was canceled while we were
4294// waiting for the network delegate.
4295// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4296TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554297 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354298
4299 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304300 BlockingNetworkDelegate network_delegate(
4301 BlockingNetworkDelegate::USER_CALLBACK);
4302 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354303
[email protected]ef2bf422012-05-11 03:27:094304 TestURLRequestContext context(true);
4305 context.set_network_delegate(&network_delegate);
4306 context.Init();
[email protected]9045b8822012-01-13 20:35:354307
4308 {
danakj8522a25b2016-04-16 00:17:364309 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554310 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354311
[email protected]f7022f32014-08-21 16:32:194312 r->Start();
[email protected]255620da2013-08-19 13:14:294313 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304314 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4315 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354316 EXPECT_EQ(0, network_delegate.completed_requests());
4317 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194318 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354319 // Ensure that network delegate is notified.
4320 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194321 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
robpercival214763f2016-07-01 23:27:014322 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354323 EXPECT_EQ(1, network_delegate.created_requests());
4324 EXPECT_EQ(0, network_delegate.destroyed_requests());
4325 }
4326 EXPECT_EQ(1, network_delegate.destroyed_requests());
4327}
4328
4329// Tests that we can handle when a network request was canceled while we were
4330// waiting for the network delegate.
ryansturm2343cb62016-06-15 01:09:004331// Part 2: Request is cancelled while waiting for OnBeforeStartTransaction
4332// callback.
[email protected]9045b8822012-01-13 20:35:354333TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
tommycli59a63432015-11-06 00:10:554334 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354335
4336 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304337 BlockingNetworkDelegate network_delegate(
4338 BlockingNetworkDelegate::USER_CALLBACK);
4339 network_delegate.set_block_on(
4340 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354341
[email protected]ef2bf422012-05-11 03:27:094342 TestURLRequestContext context(true);
4343 context.set_network_delegate(&network_delegate);
4344 context.Init();
[email protected]9045b8822012-01-13 20:35:354345
4346 {
danakj8522a25b2016-04-16 00:17:364347 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554348 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354349
[email protected]f7022f32014-08-21 16:32:194350 r->Start();
[email protected]255620da2013-08-19 13:14:294351 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304352 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4353 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354354 EXPECT_EQ(0, network_delegate.completed_requests());
4355 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194356 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354357 // Ensure that network delegate is notified.
4358 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194359 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
robpercival214763f2016-07-01 23:27:014360 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354361 EXPECT_EQ(1, network_delegate.created_requests());
4362 EXPECT_EQ(0, network_delegate.destroyed_requests());
4363 }
4364 EXPECT_EQ(1, network_delegate.destroyed_requests());
4365}
4366
4367// Tests that we can handle when a network request was canceled while we were
4368// waiting for the network delegate.
4369// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4370TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554371 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354372
4373 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304374 BlockingNetworkDelegate network_delegate(
4375 BlockingNetworkDelegate::USER_CALLBACK);
4376 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354377
[email protected]ef2bf422012-05-11 03:27:094378 TestURLRequestContext context(true);
4379 context.set_network_delegate(&network_delegate);
4380 context.Init();
[email protected]9045b8822012-01-13 20:35:354381
4382 {
danakj8522a25b2016-04-16 00:17:364383 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554384 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354385
[email protected]f7022f32014-08-21 16:32:194386 r->Start();
[email protected]255620da2013-08-19 13:14:294387 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304388 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4389 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354390 EXPECT_EQ(0, network_delegate.completed_requests());
4391 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194392 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354393 // Ensure that network delegate is notified.
4394 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194395 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
robpercival214763f2016-07-01 23:27:014396 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354397 EXPECT_EQ(1, network_delegate.created_requests());
4398 EXPECT_EQ(0, network_delegate.destroyed_requests());
4399 }
4400 EXPECT_EQ(1, network_delegate.destroyed_requests());
4401}
4402
4403// Tests that we can handle when a network request was canceled while we were
4404// waiting for the network delegate.
4405// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024406TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554407 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354408
4409 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304410 BlockingNetworkDelegate network_delegate(
4411 BlockingNetworkDelegate::USER_CALLBACK);
4412 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354413
[email protected]ef2bf422012-05-11 03:27:094414 TestURLRequestContext context(true);
4415 context.set_network_delegate(&network_delegate);
4416 context.Init();
[email protected]9045b8822012-01-13 20:35:354417
4418 {
danakj8522a25b2016-04-16 00:17:364419 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554420 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354421
[email protected]f7022f32014-08-21 16:32:194422 r->Start();
[email protected]255620da2013-08-19 13:14:294423 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304424 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4425 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354426 EXPECT_EQ(0, network_delegate.completed_requests());
4427 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194428 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354429 // Ensure that network delegate is notified.
4430 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194431 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
robpercival214763f2016-07-01 23:27:014432 EXPECT_THAT(r->status().error(), IsError(ERR_ABORTED));
[email protected]9045b8822012-01-13 20:35:354433 EXPECT_EQ(1, network_delegate.created_requests());
4434 EXPECT_EQ(0, network_delegate.destroyed_requests());
4435 }
4436 EXPECT_EQ(1, network_delegate.destroyed_requests());
4437}
4438
tommycli59a63432015-11-06 00:10:554439namespace {
4440
danakj8522a25b2016-04-16 00:17:364441std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554442 const test_server::HttpRequest& request) {
4443 if (request.headers.find("Host") == request.headers.end() ||
4444 request.headers.at("Host") != "www.server-auth.com" ||
4445 request.method != test_server::METHOD_CONNECT) {
4446 return nullptr;
4447 }
4448
danakj8522a25b2016-04-16 00:17:364449 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554450 new test_server::BasicHttpResponse);
4451 http_response->set_code(HTTP_UNAUTHORIZED);
4452 http_response->AddCustomHeader("WWW-Authenticate",
4453 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484454 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554455}
4456
4457} // namespace
4458
4459// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114460// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554461// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354462TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554463 http_test_server()->RegisterRequestHandler(
4464 base::Bind(&HandleServerAuthConnect));
4465 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114466
[email protected]ceefd7fd2012-11-29 00:36:244467 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044468 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554469 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504470
[email protected]dc651782009-02-14 01:45:084471 TestDelegate d;
4472 {
danakj8522a25b2016-04-16 00:17:364473 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364474 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084475
[email protected]f7022f32014-08-21 16:32:194476 r->Start();
4477 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084478
[email protected]255620da2013-08-19 13:14:294479 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084480
[email protected]f7022f32014-08-21 16:32:194481 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154482 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194483 EXPECT_TRUE(r->proxy_server().IsEmpty());
robpercival214763f2016-07-01 23:27:014484 EXPECT_THAT(r->status().error(), IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]dc651782009-02-14 01:45:084485 }
4486}
4487
[email protected]b89290212009-08-14 22:37:354488TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554489 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114490
initial.commit586acc5fe2008-07-26 22:42:524491 TestDelegate d;
4492 {
danakj8522a25b2016-04-16 00:17:364493 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554494 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524495
[email protected]f7022f32014-08-21 16:32:194496 r->Start();
4497 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524498
[email protected]255620da2013-08-19 13:14:294499 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524500
4501 EXPECT_EQ(1, d.response_started_count());
4502 EXPECT_FALSE(d.received_data_before_response());
4503 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554504 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194505 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554506 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194507 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164508
[email protected]9e743cd2010-03-16 07:03:534509 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524510 }
initial.commit586acc5fe2008-07-26 22:42:524511}
4512
[email protected]263163f2012-06-14 22:40:344513// This test has the server send a large number of cookies to the client.
4514// To ensure that no number of cookies causes a crash, a galloping binary
4515// search is used to estimate that maximum number of cookies that are accepted
4516// by the browser. Beyond the maximum number, the request will fail with
4517// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304518#if defined(OS_WIN)
4519// http://crbug.com/177916
4520#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4521#else
4522#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4523#endif // defined(OS_WIN)
4524TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554525 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344526
4527 int lower_bound = 0;
4528 int upper_bound = 1;
4529
4530 // Double the number of cookies until the response header limits are
4531 // exceeded.
4532 while (DoManyCookiesRequest(upper_bound)) {
4533 lower_bound = upper_bound;
4534 upper_bound *= 2;
4535 ASSERT_LT(upper_bound, 1000000);
4536 }
4537
pkasting6b68a162014-12-01 22:10:294538 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344539 if (tolerance < 2)
4540 tolerance = 2;
4541
4542 // Perform a binary search to find the highest possible number of cookies,
4543 // within the desired tolerance.
4544 while (upper_bound - lower_bound >= tolerance) {
4545 int num_cookies = (lower_bound + upper_bound) / 2;
4546
4547 if (DoManyCookiesRequest(num_cookies))
4548 lower_bound = num_cookies;
4549 else
4550 upper_bound = num_cookies;
4551 }
4552 // Success: the test did not crash.
4553}
4554
[email protected]b89290212009-08-14 22:37:354555TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554556 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114557
initial.commit586acc5fe2008-07-26 22:42:524558 TestDelegate d;
4559 {
danakj8522a25b2016-04-16 00:17:364560 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554561 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524562
[email protected]f7022f32014-08-21 16:32:194563 r->Start();
4564 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524565
[email protected]255620da2013-08-19 13:14:294566 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524567
4568 EXPECT_EQ(1, d.response_started_count());
4569 EXPECT_FALSE(d.received_data_before_response());
4570 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554571 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194572 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554573 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194574 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524575 }
[email protected]5d7b373e2009-09-02 07:19:034576}
4577
[email protected]79e1fd62013-06-20 06:50:044578TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554579 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044580
4581 TestDelegate d;
4582 {
tommycli59a63432015-11-06 00:10:554583 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364584 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364585 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044586
4587 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194588 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044589
[email protected]f7022f32014-08-21 16:32:194590 r->Start();
4591 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044592
[email protected]255620da2013-08-19 13:14:294593 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044594
4595 EXPECT_EQ(1, d.response_started_count());
4596 EXPECT_FALSE(d.received_data_before_response());
4597 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554598 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194599 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554600 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194601 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044602
4603 EXPECT_TRUE(d.have_full_request_headers());
4604 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4605 }
4606}
4607
[email protected]58e32bb2013-01-21 18:23:254608TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554609 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254610
4611 TestDelegate d;
4612 {
danakj8522a25b2016-04-16 00:17:364613 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554614 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254615
[email protected]f7022f32014-08-21 16:32:194616 r->Start();
4617 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254618
[email protected]255620da2013-08-19 13:14:294619 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254620
4621 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194622 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254623 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4624
4625 EXPECT_EQ(1, d.response_started_count());
4626 EXPECT_FALSE(d.received_data_before_response());
4627 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554628 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194629 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554630 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194631 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254632 }
4633}
4634
tommycli59a63432015-11-06 00:10:554635// TODO(svaldez): Update tests to use EmbeddedTestServer.
4636#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394637TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554638 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4639 SpawnedTestServer::kLocalhost,
4640 base::FilePath(kTestFilePath));
4641
4642 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394643
4644 // Parameter that specifies the Content-Length field in the response:
4645 // C - Compressed length.
4646 // U - Uncompressed length.
4647 // L - Large length (larger than both C & U).
4648 // M - Medium length (between C & U).
4649 // S - Small length (smaller than both C & U).
4650 const char test_parameters[] = "CULMS";
4651 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4652 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444653 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394654 // S has too little data, but we seem to accept it.
4655 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374656 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394657
xunjielifb4da222016-07-14 18:38:594658 base::FilePath file_path;
4659 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
4660 file_path = file_path.Append(kTestFilePath);
4661 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
4662 std::string expected_content;
4663 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
4664
4665 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:394666 TestDelegate d;
4667 {
tommycli59a63432015-11-06 00:10:554668 std::string test_file = base::StringPrintf(
4669 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394670
[email protected]ceefd7fd2012-11-29 00:36:244671 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094672 TestURLRequestContext context(true);
4673 context.set_network_delegate(&network_delegate);
4674 context.Init();
[email protected]87a09a92011-07-14 15:50:504675
danakj8522a25b2016-04-16 00:17:364676 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554677 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194678 r->Start();
4679 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394680
[email protected]255620da2013-08-19 13:14:294681 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394682
4683 EXPECT_EQ(1, d.response_started_count());
4684 EXPECT_FALSE(d.received_data_before_response());
4685 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194686 << " status = " << r->status().status()
4687 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394688 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194689 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394690 << " Parameter = \"" << test_file << "\"";
xunjielifb4da222016-07-14 18:38:594691 if (test_parameters[i] == 'S') {
4692 // When content length is smaller than both compressed length and
4693 // uncompressed length, HttpStreamParser might not read the full
4694 // response body.
4695 continue;
4696 }
4697 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:394698 } else {
[email protected]f7022f32014-08-21 16:32:194699 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4700 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394701 << " Parameter = \"" << test_file << "\"";
4702 }
4703 }
4704 }
4705}
tommycli59a63432015-11-06 00:10:554706#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394707
[email protected]58e32bb2013-01-21 18:23:254708TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554709 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254710
tommycli59a63432015-11-06 00:10:554711 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454712 GURL original_url =
tommycli59a63432015-11-06 00:10:554713 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254714 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364715 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364716 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194717 req->Start();
[email protected]255620da2013-08-19 13:14:294718 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254719
4720 EXPECT_EQ(1, d.response_started_count());
4721 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194722 EXPECT_EQ(destination_url, req->url());
4723 EXPECT_EQ(original_url, req->original_url());
4724 ASSERT_EQ(2U, req->url_chain().size());
4725 EXPECT_EQ(original_url, req->url_chain()[0]);
4726 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254727
4728 LoadTimingInfo load_timing_info_before_redirect;
4729 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4730 &load_timing_info_before_redirect));
4731 TestLoadTimingNotReused(load_timing_info_before_redirect,
4732 CONNECT_TIMING_HAS_DNS_TIMES);
4733
4734 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194735 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254736 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4737
4738 // Check that a new socket was used on redirect, since the server does not
4739 // supposed keep-alive sockets, and that the times before the redirect are
4740 // before the ones recorded for the second request.
4741 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4742 load_timing_info.socket_log_id);
4743 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4744 load_timing_info.connect_timing.connect_start);
4745}
4746
[email protected]8f1ac082011-04-19 21:14:134747TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554748 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134749
tommycli59a63432015-11-06 00:10:554750 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454751 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554752 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4753 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4754 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134755 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364756 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364757 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194758 req->Start();
[email protected]255620da2013-08-19 13:14:294759 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134760
4761 EXPECT_EQ(1, d.response_started_count());
4762 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194763 EXPECT_EQ(destination_url, req->url());
4764 EXPECT_EQ(original_url, req->original_url());
4765 ASSERT_EQ(3U, req->url_chain().size());
4766 EXPECT_EQ(original_url, req->url_chain()[0]);
4767 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4768 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134769}
4770
[email protected]abe1c4a2013-10-25 19:28:514771// First and second pieces of information logged by delegates to URLRequests.
4772const char kFirstDelegateInfo[] = "Wonderful delegate";
4773const char kSecondDelegateInfo[] = "Exciting delegate";
4774
4775// Logs delegate information to a URLRequest. The first string is logged
4776// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4777// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4778// another asynchronous call is used to clear the delegate information
4779// before calling a callback. The object then deletes itself.
4780class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4781 public:
4782 typedef base::Callback<void()> Callback;
4783
4784 // Each time delegate information is added to the URLRequest, the resulting
4785 // load state is checked. The expected load state after each request is
4786 // passed in as an argument.
4787 static void Run(URLRequest* url_request,
4788 LoadState expected_first_load_state,
4789 LoadState expected_second_load_state,
4790 LoadState expected_third_load_state,
4791 const Callback& callback) {
4792 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4793 url_request,
4794 expected_first_load_state,
4795 expected_second_load_state,
4796 expected_third_load_state,
4797 callback);
4798 logger->Start();
4799 }
4800
4801 // Checks that the log entries, starting with log_position, contain the
4802 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4803 // recorded. Returns the index of entry after the expected number of
4804 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464805 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514806 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514807 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4808 if (log_position + 3 >= entries.size()) {
4809 ADD_FAILURE() << "Not enough log entries";
4810 return entries.size();
4811 }
4812 std::string delegate_info;
4813 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4814 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4815 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4816 &delegate_info));
4817 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4818
4819 ++log_position;
4820 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4821 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4822
4823 ++log_position;
4824 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4825 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4826 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4827 &delegate_info));
4828 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4829
4830 ++log_position;
4831 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4832 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4833
4834 return log_position + 1;
4835 }
4836
4837 private:
4838 friend class base::RefCounted<AsyncDelegateLogger>;
4839
4840 AsyncDelegateLogger(URLRequest* url_request,
4841 LoadState expected_first_load_state,
4842 LoadState expected_second_load_state,
4843 LoadState expected_third_load_state,
4844 const Callback& callback)
4845 : url_request_(url_request),
4846 expected_first_load_state_(expected_first_load_state),
4847 expected_second_load_state_(expected_second_load_state),
4848 expected_third_load_state_(expected_third_load_state),
4849 callback_(callback) {
4850 }
4851
4852 ~AsyncDelegateLogger() {}
4853
4854 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534855 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514856 LoadStateWithParam load_state = url_request_->GetLoadState();
4857 EXPECT_EQ(expected_first_load_state_, load_state.state);
4858 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454859 base::ThreadTaskRunnerHandle::Get()->PostTask(
4860 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514861 }
4862
4863 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534864 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514865 LoadStateWithParam load_state = url_request_->GetLoadState();
4866 EXPECT_EQ(expected_second_load_state_, load_state.state);
4867 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4868 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4869 } else {
4870 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4871 }
skyostil4891b25b2015-06-11 11:43:454872 base::ThreadTaskRunnerHandle::Get()->PostTask(
4873 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514874 }
4875
4876 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534877 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514878 LoadStateWithParam load_state = url_request_->GetLoadState();
4879 EXPECT_EQ(expected_third_load_state_, load_state.state);
4880 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084881 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514882 callback_.Run();
4883 }
4884
4885 URLRequest* url_request_;
4886 const int expected_first_load_state_;
4887 const int expected_second_load_state_;
4888 const int expected_third_load_state_;
4889 const Callback callback_;
4890
4891 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4892};
4893
4894// NetworkDelegate that logs delegate information before a request is started,
4895// before headers are sent, when headers are read, and when auth information
4896// is requested. Uses AsyncDelegateLogger.
4897class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4898 public:
4899 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204900 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514901
4902 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204903 int OnBeforeURLRequest(URLRequest* request,
4904 const CompletionCallback& callback,
4905 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514906 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4907 return RunCallbackAsynchronously(request, callback);
4908 }
4909
ryansturm2343cb62016-06-15 01:09:004910 int OnBeforeStartTransaction(URLRequest* request,
4911 const CompletionCallback& callback,
4912 HttpRequestHeaders* headers) override {
4913 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514914 return RunCallbackAsynchronously(request, callback);
4915 }
4916
dchengb03027d2014-10-21 12:00:204917 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514918 URLRequest* request,
4919 const CompletionCallback& callback,
4920 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164921 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134922 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164923 TestNetworkDelegate::OnHeadersReceived(request,
4924 callback,
[email protected]abe1c4a2013-10-25 19:28:514925 original_response_headers,
[email protected]5f714132014-03-26 10:41:164926 override_response_headers,
4927 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514928 return RunCallbackAsynchronously(request, callback);
4929 }
4930
dchengb03027d2014-10-21 12:00:204931 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514932 URLRequest* request,
4933 const AuthChallengeInfo& auth_info,
4934 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134935 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514936 AsyncDelegateLogger::Run(
4937 request,
4938 LOAD_STATE_WAITING_FOR_DELEGATE,
4939 LOAD_STATE_WAITING_FOR_DELEGATE,
4940 LOAD_STATE_WAITING_FOR_DELEGATE,
4941 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4942 callback, credentials));
4943 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4944 }
4945
4946 private:
4947 static int RunCallbackAsynchronously(
4948 URLRequest* request,
4949 const CompletionCallback& callback) {
4950 AsyncDelegateLogger::Run(
4951 request,
4952 LOAD_STATE_WAITING_FOR_DELEGATE,
4953 LOAD_STATE_WAITING_FOR_DELEGATE,
4954 LOAD_STATE_WAITING_FOR_DELEGATE,
4955 base::Bind(callback, OK));
4956 return ERR_IO_PENDING;
4957 }
4958
4959 static void SetAuthAndResume(const AuthCallback& callback,
4960 AuthCredentials* credentials) {
4961 *credentials = AuthCredentials(kUser, kSecret);
4962 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4963 }
4964
4965 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4966};
4967
4968// URLRequest::Delegate that logs delegate information when the headers
4969// are received, when each read completes, and during redirects. Uses
4970// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4971//
4972// Inherits from TestDelegate to reuse the TestDelegate code to handle
4973// advancing to the next step in most cases, as well as cancellation.
4974class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4975 public:
4976 enum CancelStage {
4977 NO_CANCEL = 0,
4978 CANCEL_ON_RECEIVED_REDIRECT,
4979 CANCEL_ON_RESPONSE_STARTED,
4980 CANCEL_ON_READ_COMPLETED
4981 };
4982
4983 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4984 : cancel_stage_(cancel_stage) {
4985 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4986 set_cancel_in_received_redirect(true);
4987 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4988 set_cancel_in_response_started(true);
4989 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4990 set_cancel_in_received_data(true);
4991 }
dchengb03027d2014-10-21 12:00:204992 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514993
4994 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204995 void OnReceivedRedirect(URLRequest* request,
4996 const RedirectInfo& redirect_info,
4997 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514998 *defer_redirect = true;
4999 AsyncDelegateLogger::Run(
5000 request,
5001 LOAD_STATE_WAITING_FOR_DELEGATE,
5002 LOAD_STATE_WAITING_FOR_DELEGATE,
5003 LOAD_STATE_WAITING_FOR_DELEGATE,
5004 base::Bind(
5005 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595006 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515007 }
5008
dchengb03027d2014-10-21 12:00:205009 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:515010 AsyncDelegateLogger::Run(
5011 request,
5012 LOAD_STATE_WAITING_FOR_DELEGATE,
5013 LOAD_STATE_WAITING_FOR_DELEGATE,
5014 LOAD_STATE_WAITING_FOR_DELEGATE,
5015 base::Bind(
5016 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5017 base::Unretained(this), request));
5018 }
5019
dchengb03027d2014-10-21 12:00:205020 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515021 AsyncDelegateLogger::Run(
5022 request,
5023 LOAD_STATE_IDLE,
5024 LOAD_STATE_IDLE,
5025 LOAD_STATE_IDLE,
5026 base::Bind(
5027 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5028 base::Unretained(this), request, bytes_read));
5029 }
5030
5031 private:
5032 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595033 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515034 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595035 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515036 // FollowDeferredRedirect should not be called after cancellation.
5037 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5038 return;
5039 if (!defer_redirect)
5040 request->FollowDeferredRedirect();
5041 }
5042
5043 void OnResponseStartedLoggingComplete(URLRequest* request) {
5044 // The parent class continues the request.
5045 TestDelegate::OnResponseStarted(request);
5046 }
5047
5048 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5049 // The parent class continues the request.
5050 TestDelegate::OnReadCompleted(request, bytes_read);
5051 }
5052
5053 const CancelStage cancel_stage_;
5054
5055 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5056};
5057
5058// Tests handling of delegate info before a request starts.
5059TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555060 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515061
5062 TestDelegate request_delegate;
5063 TestURLRequestContext context(true);
5064 context.set_network_delegate(NULL);
5065 context.set_net_log(&net_log_);
5066 context.Init();
5067
5068 {
danakj8522a25b2016-04-16 00:17:365069 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555070 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365071 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195072 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515073 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085074 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515075
5076 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195077 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515078 LOAD_STATE_WAITING_FOR_DELEGATE,
5079 LOAD_STATE_WAITING_FOR_DELEGATE,
5080 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195081 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515082
5083 base::RunLoop().Run();
5084
[email protected]f7022f32014-08-21 16:32:195085 EXPECT_EQ(200, r->GetResponseCode());
5086 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515087 }
5088
mmenke43758e62015-05-04 21:09:465089 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515090 net_log_.GetEntries(&entries);
5091 size_t log_position = ExpectLogContainsSomewhereAfter(
5092 entries,
5093 0,
5094 NetLog::TYPE_DELEGATE_INFO,
5095 NetLog::PHASE_BEGIN);
5096
5097 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5098
5099 // Nothing else should add any delegate info to the request.
5100 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5101 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5102}
5103
5104// Tests handling of delegate info from a network delegate.
5105TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555106 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515107
5108 TestDelegate request_delegate;
5109 AsyncLoggingNetworkDelegate network_delegate;
5110 TestURLRequestContext context(true);
5111 context.set_network_delegate(&network_delegate);
5112 context.set_net_log(&net_log_);
5113 context.Init();
5114
5115 {
danakj8522a25b2016-04-16 00:17:365116 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555117 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365118 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195119 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515120 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085121 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515122
[email protected]f7022f32014-08-21 16:32:195123 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515124 base::RunLoop().Run();
5125
[email protected]f7022f32014-08-21 16:32:195126 EXPECT_EQ(200, r->GetResponseCode());
5127 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515128 EXPECT_EQ(1, network_delegate.created_requests());
5129 EXPECT_EQ(0, network_delegate.destroyed_requests());
5130 }
5131 EXPECT_EQ(1, network_delegate.destroyed_requests());
5132
5133 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465134 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515135 net_log_.GetEntries(&entries);
5136 for (size_t i = 0; i < 3; ++i) {
5137 log_position = ExpectLogContainsSomewhereAfter(
5138 entries,
5139 log_position + 1,
5140 NetLog::TYPE_URL_REQUEST_DELEGATE,
5141 NetLog::PHASE_BEGIN);
5142
5143 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5144 log_position + 1);
5145
5146 ASSERT_LT(log_position, entries.size());
5147 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5148 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5149 }
5150
5151 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5152 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5153}
5154
5155// Tests handling of delegate info from a network delegate in the case of an
5156// HTTP redirect.
5157TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555158 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515159
5160 TestDelegate request_delegate;
5161 AsyncLoggingNetworkDelegate network_delegate;
5162 TestURLRequestContext context(true);
5163 context.set_network_delegate(&network_delegate);
5164 context.set_net_log(&net_log_);
5165 context.Init();
5166
5167 {
danakj8522a25b2016-04-16 00:17:365168 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555169 http_test_server()->GetURL("/server-redirect?simple.html"),
5170 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195171 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515172 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085173 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515174
[email protected]f7022f32014-08-21 16:32:195175 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515176 base::RunLoop().Run();
5177
[email protected]f7022f32014-08-21 16:32:195178 EXPECT_EQ(200, r->GetResponseCode());
5179 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515180 EXPECT_EQ(2, network_delegate.created_requests());
5181 EXPECT_EQ(0, network_delegate.destroyed_requests());
5182 }
5183 EXPECT_EQ(1, network_delegate.destroyed_requests());
5184
5185 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465186 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515187 net_log_.GetEntries(&entries);
5188 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005189 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515190 for (size_t i = 0; i < 3; ++i) {
5191 log_position = ExpectLogContainsSomewhereAfter(
5192 entries,
5193 log_position + 1,
5194 NetLog::TYPE_URL_REQUEST_DELEGATE,
5195 NetLog::PHASE_BEGIN);
5196
5197 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5198 log_position + 1);
5199
5200 ASSERT_LT(log_position, entries.size());
5201 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5202 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5203 }
5204
5205 // The URLRequest::Delegate then gets informed about the redirect.
5206 log_position = ExpectLogContainsSomewhereAfter(
5207 entries,
5208 log_position + 1,
5209 NetLog::TYPE_URL_REQUEST_DELEGATE,
5210 NetLog::PHASE_BEGIN);
5211
5212 // The NetworkDelegate logged information in the same three events as before.
5213 for (size_t i = 0; i < 3; ++i) {
5214 log_position = ExpectLogContainsSomewhereAfter(
5215 entries,
5216 log_position + 1,
5217 NetLog::TYPE_URL_REQUEST_DELEGATE,
5218 NetLog::PHASE_BEGIN);
5219
5220 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5221 log_position + 1);
5222
5223 ASSERT_LT(log_position, entries.size());
5224 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5225 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5226 }
5227
5228 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5229 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5230}
5231
5232// Tests handling of delegate info from a network delegate in the case of HTTP
5233// AUTH.
5234TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555235 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515236
5237 TestDelegate request_delegate;
5238 AsyncLoggingNetworkDelegate network_delegate;
5239 TestURLRequestContext context(true);
5240 context.set_network_delegate(&network_delegate);
5241 context.set_net_log(&net_log_);
5242 context.Init();
5243
5244 {
danakj8522a25b2016-04-16 00:17:365245 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555246 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365247 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195248 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515249 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085250 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515251
[email protected]f7022f32014-08-21 16:32:195252 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515253 base::RunLoop().Run();
5254
[email protected]f7022f32014-08-21 16:32:195255 EXPECT_EQ(200, r->GetResponseCode());
5256 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515257 EXPECT_EQ(1, network_delegate.created_requests());
5258 EXPECT_EQ(0, network_delegate.destroyed_requests());
5259 }
5260 EXPECT_EQ(1, network_delegate.destroyed_requests());
5261
5262 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465263 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515264 net_log_.GetEntries(&entries);
5265 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005266 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5267 // in
5268 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515269 for (size_t i = 0; i < 6; ++i) {
5270 log_position = ExpectLogContainsSomewhereAfter(
5271 entries,
5272 log_position + 1,
5273 NetLog::TYPE_URL_REQUEST_DELEGATE,
5274 NetLog::PHASE_BEGIN);
5275
5276 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5277 log_position + 1);
5278
5279 ASSERT_LT(log_position, entries.size());
5280 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5281 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5282 }
5283
5284 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5285 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5286}
5287
tommycli59a63432015-11-06 00:10:555288// TODO(svaldez): Update tests to use EmbeddedTestServer.
5289#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515290// Tests handling of delegate info from a URLRequest::Delegate.
5291TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555292 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5293 SpawnedTestServer::kLocalhost,
5294 base::FilePath(kTestFilePath));
5295
5296 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515297
5298 AsyncLoggingUrlRequestDelegate request_delegate(
5299 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5300 TestURLRequestContext context(true);
5301 context.set_network_delegate(NULL);
5302 context.set_net_log(&net_log_);
5303 context.Init();
5304
5305 {
5306 // A chunked response with delays between chunks is used to make sure that
5307 // attempts by the URLRequest delegate to log information while reading the
5308 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485309 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515310 // that it occurs.
danakj8522a25b2016-04-16 00:17:365311 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555312 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365313 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195314 LoadStateWithParam load_state = r->GetLoadState();
5315 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515316 base::RunLoop().Run();
5317
[email protected]f7022f32014-08-21 16:32:195318 EXPECT_EQ(200, r->GetResponseCode());
5319 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515320 }
5321
mmenke43758e62015-05-04 21:09:465322 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515323 net_log_.GetEntries(&entries);
5324
[email protected]1826a402014-01-08 15:40:485325 size_t log_position = 0;
5326
[email protected]abe1c4a2013-10-25 19:28:515327 // The delegate info should only have been logged on header complete. Other
5328 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485329 log_position =
5330 ExpectLogContainsSomewhereAfter(entries,
5331 log_position + 1,
5332 NetLog::TYPE_URL_REQUEST_DELEGATE,
5333 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515334
5335 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5336 log_position + 1);
5337
5338 ASSERT_LT(log_position, entries.size());
5339 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5340 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5341
5342 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5343 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5344 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5345 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5346}
tommycli59a63432015-11-06 00:10:555347#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515348
5349// Tests handling of delegate info from a URLRequest::Delegate in the case of
5350// an HTTP redirect.
5351TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555352 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515353
5354 AsyncLoggingUrlRequestDelegate request_delegate(
5355 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5356 TestURLRequestContext context(true);
5357 context.set_network_delegate(NULL);
5358 context.set_net_log(&net_log_);
5359 context.Init();
5360
5361 {
danakj8522a25b2016-04-16 00:17:365362 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555363 http_test_server()->GetURL("/server-redirect?simple.html"),
5364 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195365 LoadStateWithParam load_state = r->GetLoadState();
5366 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515367 base::RunLoop().Run();
5368
[email protected]f7022f32014-08-21 16:32:195369 EXPECT_EQ(200, r->GetResponseCode());
5370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515371 }
5372
mmenke43758e62015-05-04 21:09:465373 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515374 net_log_.GetEntries(&entries);
5375
5376 // Delegate info should only have been logged in OnReceivedRedirect and
5377 // OnResponseStarted.
5378 size_t log_position = 0;
5379 for (int i = 0; i < 2; ++i) {
5380 log_position = ExpectLogContainsSomewhereAfter(
5381 entries,
5382 log_position,
5383 NetLog::TYPE_URL_REQUEST_DELEGATE,
5384 NetLog::PHASE_BEGIN);
5385
5386 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5387 log_position + 1);
5388
5389 ASSERT_LT(log_position, entries.size());
5390 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5391 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5392 }
5393
5394 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5395 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5396 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5397 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5398}
5399
5400// Tests handling of delegate info from a URLRequest::Delegate in the case of
5401// an HTTP redirect, with cancellation at various points.
5402TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555403 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515404
5405 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5406 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5407 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5408 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5409 };
5410
5411 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5412 ++test_case) {
5413 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5414 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515415 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515416 context.set_network_delegate(NULL);
5417 context.set_net_log(&net_log);
5418 context.Init();
5419
5420 {
danakj8522a25b2016-04-16 00:17:365421 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555422 http_test_server()->GetURL("/server-redirect?simple.html"),
5423 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195424 LoadStateWithParam load_state = r->GetLoadState();
5425 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515426 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195427 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515428 }
5429
mmenke43758e62015-05-04 21:09:465430 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515431 net_log.GetEntries(&entries);
5432
5433 // Delegate info is always logged in both OnReceivedRedirect and
5434 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5435 // OnResponseStarted delegate call is after cancellation, but logging is
5436 // still currently supported in that call.
5437 size_t log_position = 0;
5438 for (int i = 0; i < 2; ++i) {
5439 log_position = ExpectLogContainsSomewhereAfter(
5440 entries,
5441 log_position,
5442 NetLog::TYPE_URL_REQUEST_DELEGATE,
5443 NetLog::PHASE_BEGIN);
5444
5445 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5446 log_position + 1);
5447
5448 ASSERT_LT(log_position, entries.size());
5449 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5450 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5451 }
5452
5453 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5454 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5455 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5456 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5457 }
5458}
5459
[email protected]847c0fa92012-11-06 16:37:425460namespace {
5461
5462const char kExtraHeader[] = "Allow-Snafu";
5463const char kExtraValue[] = "fubar";
5464
5465class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205466 void OnReceivedRedirect(URLRequest* request,
5467 const RedirectInfo& redirect_info,
5468 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595469 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425470 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5471 }
5472};
5473
5474} // namespace
5475
5476TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555477 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425478
tommycli59a63432015-11-06 00:10:555479 GURL destination_url =
5480 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5481 GURL original_url =
5482 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425483 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365484 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365485 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195486 req->Start();
[email protected]255620da2013-08-19 13:14:295487 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425488
5489 std::string value;
[email protected]f7022f32014-08-21 16:32:195490 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425491 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5492 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195493 EXPECT_FALSE(req->is_pending());
5494 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425495 EXPECT_EQ(kExtraValue, d.data_received());
5496}
5497
[email protected]251a1b92012-11-13 11:01:095498namespace {
5499
5500const char kExtraHeaderToRemove[] = "To-Be-Removed";
5501
5502class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205503 void OnReceivedRedirect(URLRequest* request,
5504 const RedirectInfo& redirect_info,
5505 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595506 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095507 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5508 }
5509};
5510
5511} // namespace
5512
5513TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555514 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095515
tommycli59a63432015-11-06 00:10:555516 GURL destination_url = http_test_server()->GetURL(
5517 "/echoheader?" + std::string(kExtraHeaderToRemove));
5518 GURL original_url =
5519 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095520 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365521 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365522 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195523 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5524 req->Start();
[email protected]255620da2013-08-19 13:14:295525 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095526
5527 std::string value;
[email protected]f7022f32014-08-21 16:32:195528 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095529 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195530 EXPECT_FALSE(req->is_pending());
5531 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095532 EXPECT_EQ("None", d.data_received());
5533}
5534
[email protected]316c1e5e2012-09-12 15:17:445535TEST_F(URLRequestTestHTTP, CancelTest) {
5536 TestDelegate d;
5537 {
danakj8522a25b2016-04-16 00:17:365538 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365539 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445540
[email protected]f7022f32014-08-21 16:32:195541 r->Start();
5542 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445543
[email protected]f7022f32014-08-21 16:32:195544 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445545
[email protected]255620da2013-08-19 13:14:295546 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445547
5548 // We expect to receive OnResponseStarted even though the request has been
5549 // cancelled.
5550 EXPECT_EQ(1, d.response_started_count());
5551 EXPECT_EQ(0, d.bytes_received());
5552 EXPECT_FALSE(d.received_data_before_response());
5553 }
5554}
5555
5556TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555557 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445558
5559 TestDelegate d;
5560 {
danakj8522a25b2016-04-16 00:17:365561 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555562 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445563
5564 d.set_cancel_in_response_started(true);
5565
[email protected]f7022f32014-08-21 16:32:195566 r->Start();
5567 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445568
[email protected]255620da2013-08-19 13:14:295569 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445570
5571 EXPECT_EQ(1, d.response_started_count());
5572 EXPECT_EQ(0, d.bytes_received());
5573 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195574 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445575 }
5576}
5577
5578TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555579 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445580
5581 TestDelegate d;
5582 {
danakj8522a25b2016-04-16 00:17:365583 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555584 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445585
5586 d.set_cancel_in_received_data(true);
5587
[email protected]f7022f32014-08-21 16:32:195588 r->Start();
5589 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445590
[email protected]255620da2013-08-19 13:14:295591 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445592
5593 EXPECT_EQ(1, d.response_started_count());
5594 // There is no guarantee about how much data was received
5595 // before the cancel was issued. It could have been 0 bytes,
5596 // or it could have been all the bytes.
5597 // EXPECT_EQ(0, d.bytes_received());
5598 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195599 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445600 }
5601}
5602
5603TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555604 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445605
5606 TestDelegate d;
5607 {
danakj8522a25b2016-04-16 00:17:365608 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555609 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445610
[email protected]f7022f32014-08-21 16:32:195611 r->Start();
5612 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445613
5614 // The request will be implicitly canceled when it is destroyed. The
5615 // test delegate must not post a quit message when this happens because
5616 // this test doesn't actually have a message loop. The quit message would
5617 // get put on this thread's message queue and the next test would exit
5618 // early, causing problems.
5619 d.set_quit_on_complete(false);
5620 }
5621 // expect things to just cleanup properly.
5622
kimwjdalsl2bb4ff02015-12-16 22:06:025623 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445624 // message loop
5625 EXPECT_FALSE(d.received_data_before_response());
5626 EXPECT_EQ(0, d.bytes_received());
5627}
5628
5629TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555630 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445631
5632 // populate cache
5633 {
5634 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365635 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555636 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195637 r->Start();
[email protected]255620da2013-08-19 13:14:295638 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195639 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445640 }
5641
5642 // cancel read from cache (see bug 990242)
5643 {
5644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365645 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555646 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195647 r->Start();
5648 r->Cancel();
[email protected]255620da2013-08-19 13:14:295649 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445650
[email protected]f7022f32014-08-21 16:32:195651 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445652 EXPECT_EQ(1, d.response_started_count());
5653 EXPECT_EQ(0, d.bytes_received());
5654 EXPECT_FALSE(d.received_data_before_response());
5655 }
5656}
5657
5658TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555659 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445660 HTTPUploadDataOperationTest("POST");
5661}
5662
5663TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555664 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445665 HTTPUploadDataOperationTest("PUT");
5666}
5667
5668TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555669 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445670
5671 TestDelegate d;
5672 {
danakj8522a25b2016-04-16 00:17:365673 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555674 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195675 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445676
[email protected]f7022f32014-08-21 16:32:195677 r->Start();
5678 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445679
[email protected]255620da2013-08-19 13:14:295680 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445681
[email protected]329b68b2012-11-14 17:54:275682 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195683 << "request failed: " << r->status().status()
5684 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445685
5686 EXPECT_FALSE(d.received_data_before_response());
5687 EXPECT_TRUE(d.data_received().empty());
5688 }
5689}
5690
5691TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555692 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445693
5694 TestDelegate d;
5695 {
danakj8522a25b2016-04-16 00:17:365696 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555697 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195698 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445699
[email protected]6cdfd7f2013-02-08 20:40:155700 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445701 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025702 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445703
danakj8522a25b2016-04-16 00:17:365704 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445705
[email protected]6cdfd7f2013-02-08 20:40:155706 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445707 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475708 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445709 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
danakj8522a25b2016-04-16 00:17:365710 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
avibf0746c2015-12-09 19:53:145711 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
5712 std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365713 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225714 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445715
[email protected]f7022f32014-08-21 16:32:195716 r->Start();
5717 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445718
[email protected]255620da2013-08-19 13:14:295719 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445720
avibf0746c2015-12-09 19:53:145721 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295722 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5723 ASSERT_LE(size64, std::numeric_limits<int>::max());
5724 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365725 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445726
[email protected]7600d0b2013-12-08 21:43:305727 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445728
[email protected]329b68b2012-11-14 17:54:275729 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195730 << "request failed: " << r->status().status()
5731 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445732
5733 EXPECT_FALSE(d.received_data_before_response());
5734
[email protected]329b68b2012-11-14 17:54:275735 EXPECT_EQ(size, d.bytes_received());
5736 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445737 }
5738}
5739
[email protected]999dd8c2013-11-12 06:45:545740TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555741 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545742
5743 TestDelegate d;
5744 {
danakj8522a25b2016-04-16 00:17:365745 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555746 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195747 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545748
danakj8522a25b2016-04-16 00:17:365749 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545750
danakj8522a25b2016-04-16 00:17:365751 element_readers.push_back(base::WrapUnique(new UploadFileElementReader(
skyostil4891b25b2015-06-11 11:43:455752 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545753 base::FilePath(FILE_PATH_LITERAL(
5754 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
avibf0746c2015-12-09 19:53:145755 0, std::numeric_limits<uint64_t>::max(), base::Time())));
danakj8522a25b2016-04-16 00:17:365756 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225757 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545758
[email protected]f7022f32014-08-21 16:32:195759 r->Start();
5760 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545761
5762 base::RunLoop().Run();
5763
[email protected]999dd8c2013-11-12 06:45:545764 EXPECT_TRUE(d.request_failed());
5765 EXPECT_FALSE(d.received_data_before_response());
5766 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195767 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
robpercival214763f2016-07-01 23:27:015768 EXPECT_THAT(r->status().error(), IsError(ERR_FILE_NOT_FOUND));
[email protected]999dd8c2013-11-12 06:45:545769 }
5770}
5771
mmenke56b0cbb912016-03-28 21:34:535772namespace {
5773
5774// Adds a standard set of data to an upload for chunked upload integration
5775// tests.
5776void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5777 writer->AppendData("a", 1, false);
5778 writer->AppendData("bcd", 3, false);
5779 writer->AppendData("this is a longer chunk than before.", 35, false);
5780 writer->AppendData("\r\n\r\n", 4, false);
5781 writer->AppendData("0", 1, false);
5782 writer->AppendData("2323", 4, true);
5783}
5784
5785// Checks that the upload data added in AddChunksToUpload() was echoed back from
5786// the server.
5787void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5788 // This should match the chunks sent by AddChunksToUpload().
5789 const std::string expected_data =
5790 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5791
5792 ASSERT_EQ(1, d->response_started_count())
5793 << "request failed: " << r->status().status()
5794 << ", os error: " << r->status().error();
5795
5796 EXPECT_FALSE(d->received_data_before_response());
5797
5798 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5799 EXPECT_EQ(expected_data, d->data_received());
5800}
5801
5802} // namespace
5803
[email protected]316c1e5e2012-09-12 15:17:445804TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555805 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445806
5807 TestDelegate d;
5808 {
danakj8522a25b2016-04-16 00:17:365809 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555810 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365811 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535812 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365813 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535814 upload_data_stream->CreateWriter();
5815 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195816 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535817 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195818 r->Start();
5819 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445820
[email protected]255620da2013-08-19 13:14:295821 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445822
[email protected]f7022f32014-08-21 16:32:195823 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445824 }
5825}
5826
[email protected]329b68b2012-11-14 17:54:275827TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555828 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275829
5830 TestDelegate d;
5831 {
danakj8522a25b2016-04-16 00:17:365832 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555833 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365834 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535835 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365836 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535837 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365838 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195839 r->set_method("POST");
5840 r->Start();
5841 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535842 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295843 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275844
[email protected]f7022f32014-08-21 16:32:195845 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275846 }
5847}
5848
[email protected]316c1e5e2012-09-12 15:17:445849TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555850 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445851
5852 TestDelegate d;
5853 {
danakj8522a25b2016-04-16 00:17:365854 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555855 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365856 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535857 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365858 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535859 upload_data_stream->CreateWriter();
5860 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195861 r->set_method("POST");
5862 r->Start();
5863 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445864
[email protected]255620da2013-08-19 13:14:295865 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535866 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295867 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445868
[email protected]f7022f32014-08-21 16:32:195869 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445870 }
5871}
5872
5873TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555874 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445875
5876 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365877 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555878 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195879 req->Start();
[email protected]255620da2013-08-19 13:14:295880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445881
[email protected]f7022f32014-08-21 16:32:195882 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445883
5884 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195885 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445886
5887 std::string header;
5888 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5889 EXPECT_EQ("private", header);
5890
5891 header.clear();
5892 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5893 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5894
5895 // The response has two "X-Multiple-Entries" headers.
5896 // This verfies our output has them concatenated together.
5897 header.clear();
5898 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5899 EXPECT_EQ("a, b", header);
5900}
5901
tommycli59a63432015-11-06 00:10:555902// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5903// security state. (see http://crbug.com/550977).
5904#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465905TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555906 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5907 https_test_server.SetSSLConfig(
5908 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5909 https_test_server.ServeFilesFromSourceDirectory(
5910 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465911 ASSERT_TRUE(https_test_server.Start());
5912
tommycli59a63432015-11-06 00:10:555913 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465914 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365915 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555916 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195917 request->Start();
[email protected]255620da2013-08-19 13:14:295918 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465919
5920 TransportSecurityState* security_state =
5921 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405922 TransportSecurityState::STSState sts_state;
5923 TransportSecurityState::PKPState pkp_state;
5924 EXPECT_TRUE(
5925 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5926 EXPECT_FALSE(
5927 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5928 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5929 sts_state.upgrade_mode);
5930 EXPECT_TRUE(sts_state.include_subdomains);
5931 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035932#if defined(OS_ANDROID)
5933 // Android's CertVerifyProc does not (yet) handle pins.
5934#else
martijnc0d6b622015-06-30 19:14:405935 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035936#endif
[email protected]37fd55fb2013-06-29 13:13:275937}
5938
estarka5da76702015-04-09 04:00:165939TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555940 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5941 https_test_server.ServeFilesFromSourceDirectory(
5942 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165943 ASSERT_TRUE(https_test_server.Start());
5944 // Make sure this test fails if the test server is changed to not
5945 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555946 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5947 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165948
5949 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365950 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555951 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165952 request->Start();
5953 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165954 TransportSecurityState* security_state =
5955 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405956 TransportSecurityState::STSState sts_state;
5957 EXPECT_FALSE(
5958 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165959}
5960
estark06e0dac2015-08-07 21:56:015961namespace {
estark1614475f2016-03-10 03:46:475962const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
estark06e0dac2015-08-07 21:56:015963const char kHPKPReportUri[] = "https://hpkp-report.test";
5964} // namespace
5965
[email protected]37fd55fb2013-06-29 13:13:275966// Tests that enabling HPKP on a domain does not affect the HSTS
5967// validity/expiration.
dadrian2faf2062016-07-16 00:03:175968TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:015969 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555970 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5971 https_test_server.SetSSLConfig(
5972 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5973 https_test_server.ServeFilesFromSourceDirectory(
5974 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275975 ASSERT_TRUE(https_test_server.Start());
5976
tommycli59a63432015-11-06 00:10:555977 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165978
[email protected]37fd55fb2013-06-29 13:13:275979 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365980 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555981 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195982 request->Start();
[email protected]255620da2013-08-19 13:14:295983 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275984 TransportSecurityState* security_state =
5985 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405986 TransportSecurityState::STSState sts_state;
5987 TransportSecurityState::PKPState pkp_state;
5988 EXPECT_FALSE(
5989 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5990 EXPECT_TRUE(
5991 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5992 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5993 sts_state.upgrade_mode);
5994 EXPECT_FALSE(sts_state.include_subdomains);
5995 EXPECT_FALSE(pkp_state.include_subdomains);
5996 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015997 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405998 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465999}
6000
estark06e0dac2015-08-07 21:56:016001// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:176002TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:016003 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556004 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6005 https_test_server.SetSSLConfig(
6006 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6007 https_test_server.ServeFilesFromSourceDirectory(
6008 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016009 ASSERT_TRUE(https_test_server.Start());
6010
tommycli59a63432015-11-06 00:10:556011 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016012
6013 // Set up a pin for |test_server_hostname|.
6014 TransportSecurityState security_state;
6015 const base::Time current_time(base::Time::Now());
6016 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
6017 HashValueVector hashes;
6018 HashValue hash1;
6019 HashValue hash2;
6020 // The values here don't matter, as long as they are different from
6021 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:446022 ASSERT_TRUE(
6023 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6024 ASSERT_TRUE(
6025 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016026 hashes.push_back(hash1);
6027 hashes.push_back(hash2);
6028 security_state.AddHPKP(test_server_hostname, expiry,
6029 false, /* include subdomains */
6030 hashes, report_uri);
6031
6032 MockCertificateReportSender mock_report_sender;
6033 security_state.SetReportSender(&mock_report_sender);
6034
6035 // Set up a MockCertVerifier to trigger a violation of the previously
6036 // set pin.
6037 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6038 ASSERT_TRUE(cert);
6039
6040 MockCertVerifier cert_verifier;
6041 CertVerifyResult verify_result;
6042 verify_result.verified_cert = cert;
6043 verify_result.is_issued_by_known_root = true;
6044 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446045 ASSERT_TRUE(
6046 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016047 verify_result.public_key_hashes.push_back(hash3);
6048 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6049
6050 TestNetworkDelegate network_delegate;
6051 TestURLRequestContext context(true);
6052 context.set_transport_security_state(&security_state);
6053 context.set_network_delegate(&network_delegate);
6054 context.set_cert_verifier(&cert_verifier);
6055 context.Init();
6056
6057 // Now send a request to trigger the violation.
6058 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366059 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556060 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016061 violating_request->Start();
6062 base::RunLoop().Run();
6063
6064 // Check that a report was sent.
6065 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6066 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366067 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016068 base::JSONReader::Read(mock_report_sender.latest_report()));
6069 ASSERT_TRUE(value);
6070 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6071 base::DictionaryValue* report_dict;
6072 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6073 std::string report_hostname;
6074 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6075 EXPECT_EQ(test_server_hostname, report_hostname);
6076}
6077
6078// Tests that reports get sent on requests with
6079// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176080TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016081 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556082 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6083 https_test_server.SetSSLConfig(
6084 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6085 https_test_server.ServeFilesFromSourceDirectory(
6086 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016087 ASSERT_TRUE(https_test_server.Start());
6088
tommycli59a63432015-11-06 00:10:556089 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016090
6091 TransportSecurityState security_state;
6092 MockCertificateReportSender mock_report_sender;
6093 security_state.SetReportSender(&mock_report_sender);
6094
6095 // Set up a MockCertVerifier to violate the pin in the Report-Only
6096 // header.
6097 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6098 ASSERT_TRUE(cert);
6099
6100 MockCertVerifier cert_verifier;
6101 CertVerifyResult verify_result;
6102 verify_result.verified_cert = cert;
6103 verify_result.is_issued_by_known_root = true;
6104 HashValue hash;
6105 // This value doesn't matter, as long as it is different from the pins
6106 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446107 ASSERT_TRUE(
6108 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016109 verify_result.public_key_hashes.push_back(hash);
6110 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6111
6112 TestNetworkDelegate network_delegate;
6113 TestURLRequestContext context(true);
6114 context.set_transport_security_state(&security_state);
6115 context.set_network_delegate(&network_delegate);
6116 context.set_cert_verifier(&cert_verifier);
6117 context.Init();
6118
6119 // Now send a request to trigger the violation.
6120 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366121 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556122 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016123 DEFAULT_PRIORITY, &d));
6124 violating_request->Start();
6125 base::RunLoop().Run();
6126
6127 // Check that a report was sent.
6128 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6129 ASSERT_FALSE(mock_report_sender.latest_report().empty());
danakj8522a25b2016-04-16 00:17:366130 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016131 base::JSONReader::Read(mock_report_sender.latest_report()));
6132 ASSERT_TRUE(value);
6133 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6134 base::DictionaryValue* report_dict;
6135 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6136 std::string report_hostname;
6137 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6138 EXPECT_EQ(test_server_hostname, report_hostname);
6139}
6140
6141// Tests that reports do not get sent on requests with
6142// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176143TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016144 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556145 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6146 https_test_server.SetSSLConfig(
6147 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6148 https_test_server.ServeFilesFromSourceDirectory(
6149 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016150 ASSERT_TRUE(https_test_server.Start());
6151
tommycli59a63432015-11-06 00:10:556152 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016153
6154 TransportSecurityState security_state;
6155 MockCertificateReportSender mock_report_sender;
6156 security_state.SetReportSender(&mock_report_sender);
6157
6158 TestNetworkDelegate network_delegate;
6159 MockCertVerifier mock_cert_verifier;
6160 TestURLRequestContext context(true);
6161 context.set_transport_security_state(&security_state);
6162 context.set_network_delegate(&network_delegate);
6163 context.set_cert_verifier(&mock_cert_verifier);
6164 mock_cert_verifier.set_default_result(OK);
6165 context.Init();
6166
6167 // Now send a request that does not trigger the violation.
6168 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366169 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556170 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016171 DEFAULT_PRIORITY, &d));
6172 request->Start();
6173 base::RunLoop().Run();
6174
6175 // Check that a report was not sent.
6176 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6177 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6178}
6179
estarka5da76702015-04-09 04:00:166180TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556181 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6182 https_test_server.ServeFilesFromSourceDirectory(
6183 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166184 ASSERT_TRUE(https_test_server.Start());
6185 // Make sure this test fails if the test server is changed to not
6186 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556187 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6188 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166189
6190 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366191 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556192 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166193 request->Start();
6194 base::RunLoop().Run();
6195
6196 TransportSecurityState* security_state =
6197 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406198 TransportSecurityState::PKPState pkp_state;
6199 EXPECT_FALSE(
6200 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166201}
6202
dadriandf302c42016-06-10 18:48:596203TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6204 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6205 https_test_server.SetSSLConfig(
6206 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6207 https_test_server.ServeFilesFromSourceDirectory(
6208 base::FilePath(kTestFilePath));
6209 ASSERT_TRUE(https_test_server.Start());
6210
6211 // Set up a MockCertVerifier to be a local root that violates the pin
6212 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6213 ASSERT_TRUE(cert);
6214
6215 MockCertVerifier cert_verifier;
6216 CertVerifyResult verify_result;
6217 verify_result.verified_cert = cert;
6218 verify_result.is_issued_by_known_root = false;
6219 HashValue hash;
6220 ASSERT_TRUE(
6221 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6222 verify_result.public_key_hashes.push_back(hash);
6223 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6224 cert_verifier.set_default_result(OK);
6225
6226 std::string test_server_hostname = https_test_server.GetURL("/").host();
6227
6228 // Set up HPKP
6229 base::Time current_time = base::Time::Now();
6230 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6231 HashValue pin;
6232 ASSERT_TRUE(
6233 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6234 HashValueVector hashes;
6235 hashes.push_back(pin);
6236 GURL report_uri(kHPKPReportUri);
6237 TransportSecurityState security_state;
6238 security_state.AddHPKP(test_server_hostname, expiry,
6239 false, /* include subdomains */
6240 hashes, report_uri);
6241
6242 TestNetworkDelegate network_delegate;
6243 TestURLRequestContext context(true);
6244 context.set_transport_security_state(&security_state);
6245 context.set_network_delegate(&network_delegate);
6246 context.set_cert_verifier(&cert_verifier);
6247 context.Init();
6248
6249 TestDelegate d;
6250 std::unique_ptr<URLRequest> request(context.CreateRequest(
6251 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6252 request->Start();
6253 base::RunLoop().Run();
6254
6255 TransportSecurityState::PKPState pkp_state;
6256 EXPECT_TRUE(
6257 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6258 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6259}
6260
[email protected]242d8562012-10-30 21:20:466261TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556262 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6263 https_test_server.SetSSLConfig(
6264 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6265 https_test_server.ServeFilesFromSourceDirectory(
6266 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466267 ASSERT_TRUE(https_test_server.Start());
6268
tommycli59a63432015-11-06 00:10:556269 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166270
[email protected]242d8562012-10-30 21:20:466271 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366272 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556273 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6274 &d));
[email protected]f7022f32014-08-21 16:32:196275 request->Start();
[email protected]255620da2013-08-19 13:14:296276 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466277
6278 // We should have set parameters from the first header, not the second.
6279 TransportSecurityState* security_state =
6280 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406281 TransportSecurityState::STSState sts_state;
6282 EXPECT_TRUE(
6283 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6284 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6285 sts_state.upgrade_mode);
6286 EXPECT_FALSE(sts_state.include_subdomains);
6287 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466288}
6289
[email protected]9f972ec2013-04-10 20:24:366290TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556291 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6292 https_test_server.SetSSLConfig(
6293 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6294 https_test_server.ServeFilesFromSourceDirectory(
6295 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366296 ASSERT_TRUE(https_test_server.Start());
6297
tommycli59a63432015-11-06 00:10:556298 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166299
[email protected]9f972ec2013-04-10 20:24:366300 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366301 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556302 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6303 &d));
[email protected]f7022f32014-08-21 16:32:196304 request->Start();
[email protected]255620da2013-08-19 13:14:296305 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366306
6307 // We should have set parameters from the first header, not the second.
6308 TransportSecurityState* security_state =
6309 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406310 TransportSecurityState::STSState sts_state;
6311 TransportSecurityState::PKPState pkp_state;
6312 EXPECT_TRUE(
6313 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6314 EXPECT_TRUE(
6315 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6316 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6317 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036318#if defined(OS_ANDROID)
6319 // Android's CertVerifyProc does not (yet) handle pins.
6320#else
martijnc0d6b622015-06-30 19:14:406321 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036322#endif
martijnc0d6b622015-06-30 19:14:406323 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366324
[email protected]a165f092013-06-12 16:10:056325 // Even though there is an HSTS header asserting includeSubdomains, it is
6326 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406327 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056328 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406329 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366330}
6331
[email protected]37fd55fb2013-06-29 13:13:276332// Tests that when multiple HPKP headers are present, asserting different
6333// policies, that only the first such policy is processed.
6334TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556335 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6336 https_test_server.SetSSLConfig(
6337 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6338 https_test_server.ServeFilesFromSourceDirectory(
6339 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276340 ASSERT_TRUE(https_test_server.Start());
6341
tommycli59a63432015-11-06 00:10:556342 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166343
[email protected]37fd55fb2013-06-29 13:13:276344 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366345 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556346 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366347 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196348 request->Start();
[email protected]255620da2013-08-19 13:14:296349 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276350
6351 TransportSecurityState* security_state =
6352 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406353 TransportSecurityState::STSState sts_state;
6354 TransportSecurityState::PKPState pkp_state;
6355 EXPECT_TRUE(
6356 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6357 EXPECT_TRUE(
6358 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6359 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6360 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036361#if defined(OS_ANDROID)
6362 // Android's CertVerifyProc does not (yet) handle pins.
6363#else
martijnc0d6b622015-06-30 19:14:406364 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036365#endif
martijnc0d6b622015-06-30 19:14:406366 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276367
martijnc0d6b622015-06-30 19:14:406368 EXPECT_TRUE(sts_state.include_subdomains);
6369 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276370}
6371
estark1614475f2016-03-10 03:46:476372// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6373// called.
6374class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6375 public:
6376 MockExpectCTReporter() : num_failures_(0) {}
6377 ~MockExpectCTReporter() override {}
6378
6379 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6380 const GURL& report_uri,
6381 const net::SSLInfo& ssl_info) override {
6382 num_failures_++;
6383 }
6384
6385 uint32_t num_failures() { return num_failures_; }
6386
6387 private:
6388 uint32_t num_failures_;
6389};
6390
6391// A CTVerifier that returns net::OK for every certificate.
6392class MockCTVerifier : public CTVerifier {
6393 public:
6394 MockCTVerifier() {}
6395 ~MockCTVerifier() override {}
6396
6397 int Verify(X509Certificate* cert,
6398 const std::string& stapled_ocsp_response,
6399 const std::string& sct_list_from_tls_extension,
6400 ct::CTVerifyResult* result,
6401 const BoundNetLog& net_log) override {
6402 return net::OK;
6403 }
6404
6405 void SetObserver(Observer* observer) override {}
6406};
6407
6408// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6409// for every certificate.
6410class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6411 public:
6412 MockCTPolicyEnforcer()
6413 : default_result_(
6414 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6415 ~MockCTPolicyEnforcer() override {}
6416
6417 ct::CertPolicyCompliance DoesConformToCertPolicy(
6418 X509Certificate* cert,
6419 const SCTList& verified_scts,
6420 const BoundNetLog& net_log) override {
6421 return default_result_;
6422 }
6423
6424 void set_default_result(ct::CertPolicyCompliance default_result) {
6425 default_result_ = default_result;
6426 }
6427
6428 private:
6429 ct::CertPolicyCompliance default_result_;
6430};
6431
6432// Tests that Expect CT headers are processed correctly.
6433TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6434 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6435 https_test_server.SetSSLConfig(
6436 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6437 https_test_server.ServeFilesFromSourceDirectory(
6438 base::FilePath(kTestFilePath));
6439 ASSERT_TRUE(https_test_server.Start());
6440
6441 MockExpectCTReporter reporter;
6442 TransportSecurityState transport_security_state;
6443 transport_security_state.enable_static_expect_ct_ = true;
6444 transport_security_state.SetExpectCTReporter(&reporter);
6445
6446 // Set up a MockCertVerifier to accept the certificate that the server sends.
6447 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6448 ASSERT_TRUE(cert);
6449 MockCertVerifier cert_verifier;
6450 CertVerifyResult verify_result;
6451 verify_result.verified_cert = cert;
6452 verify_result.is_issued_by_known_root = true;
6453 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6454
6455 // Set up a MockCTVerifier and MockCTPolicyEnforcer to trigger an Expect CT
6456 // violation.
6457 MockCTVerifier ct_verifier;
6458 MockCTPolicyEnforcer ct_policy_enforcer;
6459 ct_policy_enforcer.set_default_result(
6460 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6461
6462 TestNetworkDelegate network_delegate;
6463 // Use a MockHostResolver (which by default maps all hosts to
6464 // 127.0.0.1) so that the request can be sent to a site on the Expect
6465 // CT preload list.
6466 MockHostResolver host_resolver;
6467 TestURLRequestContext context(true);
6468 context.set_host_resolver(&host_resolver);
6469 context.set_transport_security_state(&transport_security_state);
6470 context.set_network_delegate(&network_delegate);
6471 context.set_cert_verifier(&cert_verifier);
6472 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206473 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476474 context.Init();
6475
6476 // Now send a request to trigger the violation.
6477 TestDelegate d;
6478 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6479 GURL::Replacements replace_host;
6480 replace_host.SetHostStr(kExpectCTStaticHostname);
6481 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366482 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476483 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6484 violating_request->Start();
6485 base::RunLoop().Run();
6486
6487 EXPECT_EQ(1u, reporter.num_failures());
6488}
6489
tommycli59a63432015-11-06 00:10:556490#endif // !defined(OS_IOS)
6491
[email protected]316c1e5e2012-09-12 15:17:446492TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556493 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446494
6495 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366496 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556497 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366498 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196499 req->Start();
[email protected]255620da2013-08-19 13:14:296500 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446501
6502 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196503 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446504 EXPECT_EQ("text/html", mime_type);
6505
6506 std::string charset;
[email protected]f7022f32014-08-21 16:32:196507 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446508 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196509 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446510}
6511
[email protected]02494ec2014-05-07 15:05:296512TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346513 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346514 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346515 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026516 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346517
6518 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506519 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346520}
6521
[email protected]02494ec2014-05-07 15:05:296522#if !defined(DISABLE_FILE_SUPPORT)
6523TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6524 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6525 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456526 FileProtocolHandler file_protocol_handler(
6527 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296528 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6529
6530 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506531 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296532}
6533
[email protected]588614c22013-08-16 00:09:026534TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556535 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446536
6537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366538 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556539 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366540 &d));
[email protected]f7022f32014-08-21 16:32:196541 req->Start();
[email protected]255620da2013-08-19 13:14:296542 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446543
[email protected]f7022f32014-08-21 16:32:196544 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
robpercival214763f2016-07-01 23:27:016545 EXPECT_THAT(req->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]316c1e5e2012-09-12 15:17:446546}
[email protected]02494ec2014-05-07 15:05:296547#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446548
[email protected]588614c22013-08-16 00:09:026549TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556550 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026551
6552 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366553 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556554 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366555 &d));
[email protected]f7022f32014-08-21 16:32:196556 req->Start();
fdoray5eeb7642016-06-22 16:11:286557 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026558
[email protected]f7022f32014-08-21 16:32:196559 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
robpercival214763f2016-07-01 23:27:016560 EXPECT_THAT(req->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]588614c22013-08-16 00:09:026561}
6562
[email protected]316c1e5e2012-09-12 15:17:446563TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556564 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446565
6566 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366567 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556568 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366569 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196570 req->Start();
[email protected]255620da2013-08-19 13:14:296571 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446572
[email protected]f7022f32014-08-21 16:32:196573 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
robpercival214763f2016-07-01 23:27:016574 EXPECT_THAT(req->status().error(), IsError(ERR_INVALID_URL));
[email protected]316c1e5e2012-09-12 15:17:446575}
6576
[email protected]e50efea2014-03-24 18:41:006577// Make sure redirects are cached, despite not reading their bodies.
6578TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556579 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006580 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556581 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006582
6583 {
6584 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366585 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366586 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196587 req->Start();
[email protected]e50efea2014-03-24 18:41:006588 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196589 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006590 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556591 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006592 }
6593
6594 {
6595 TestDelegate d;
6596 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366597 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366598 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196599 req->Start();
[email protected]e50efea2014-03-24 18:41:006600 base::RunLoop().Run();
6601
6602 EXPECT_EQ(1, d.received_redirect_count());
6603 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196604 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006605
[email protected]f7022f32014-08-21 16:32:196606 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006607 base::RunLoop().Run();
6608 EXPECT_EQ(1, d.received_redirect_count());
6609 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196610 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
tommycli59a63432015-11-06 00:10:556611 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006612 }
6613}
6614
6615// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6616// when the headers are read, since the body won't have been read.
6617TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556618 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006619 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556620 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006621
6622 {
6623 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556624 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006625 default_network_delegate_.set_redirect_on_headers_received_url(
6626 redirect_to_url);
6627
6628 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366629 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366630 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196631 req->Start();
[email protected]e50efea2014-03-24 18:41:006632 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196633 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:006634 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196635 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006636 }
6637
6638 {
6639 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366640 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366641 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196642 req->Start();
[email protected]e50efea2014-03-24 18:41:006643 base::RunLoop().Run();
6644
[email protected]f7022f32014-08-21 16:32:196645 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
6646 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006647 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196648 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006649 }
6650}
6651
[email protected]5f714132014-03-26 10:41:166652// Tests that redirection to an unsafe URL is allowed when it has been marked as
6653// safe.
6654TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556655 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166656
6657 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6658 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6659 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6660
6661 TestDelegate d;
6662 {
danakj8522a25b2016-04-16 00:17:366663 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556664 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166665
[email protected]f7022f32014-08-21 16:32:196666 r->Start();
[email protected]5f714132014-03-26 10:41:166667 base::RunLoop().Run();
6668
[email protected]f7022f32014-08-21 16:32:196669 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:166670
[email protected]f7022f32014-08-21 16:32:196671 EXPECT_EQ(2U, r->url_chain().size());
robpercival214763f2016-07-01 23:27:016672 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196673 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166674 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6675 }
6676}
6677
6678// Tests that a redirect to a different unsafe URL is blocked, even after adding
6679// some other URL to the whitelist.
6680TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556681 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166682
6683 GURL unsafe_url("data:text/html,something");
6684 GURL different_unsafe_url("data:text/html,something-else");
6685 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6686 default_network_delegate_.set_allowed_unsafe_redirect_url(
6687 different_unsafe_url);
6688
6689 TestDelegate d;
6690 {
danakj8522a25b2016-04-16 00:17:366691 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556692 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166693
[email protected]f7022f32014-08-21 16:32:196694 r->Start();
[email protected]5f714132014-03-26 10:41:166695 base::RunLoop().Run();
6696
[email protected]f7022f32014-08-21 16:32:196697 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
robpercival214763f2016-07-01 23:27:016698 EXPECT_THAT(r->status().error(), IsError(ERR_UNSAFE_REDIRECT));
[email protected]5f714132014-03-26 10:41:166699 }
6700}
6701
[email protected]5f714132014-03-26 10:41:166702// Redirects from an URL with fragment to an unsafe URL with fragment should
6703// be allowed, and the reference fragment of the target URL should be preserved.
6704TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556705 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166706
tommycli59a63432015-11-06 00:10:556707 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166708 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6709 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6710
6711 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6712 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6713
6714 TestDelegate d;
6715 {
danakj8522a25b2016-04-16 00:17:366716 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366717 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166718
[email protected]f7022f32014-08-21 16:32:196719 r->Start();
[email protected]5f714132014-03-26 10:41:166720 base::RunLoop().Run();
6721
[email protected]f7022f32014-08-21 16:32:196722 EXPECT_EQ(2U, r->url_chain().size());
6723 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:016724 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196725 EXPECT_EQ(original_url, r->original_url());
6726 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166727 }
6728}
6729
6730// When a delegate has specified a safe redirect URL, but it does not match the
6731// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146732TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556733 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166734
tommycli59a63432015-11-06 00:10:556735 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166736 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556737 GURL redirect_url(http_test_server()->GetURL("/target"));
6738 GURL expected_redirect_url(
6739 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166740
6741 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6742 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6743
6744 TestDelegate d;
6745 {
danakj8522a25b2016-04-16 00:17:366746 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366747 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166748
[email protected]f7022f32014-08-21 16:32:196749 r->Start();
[email protected]5f714132014-03-26 10:41:166750 base::RunLoop().Run();
6751
[email protected]f7022f32014-08-21 16:32:196752 EXPECT_EQ(2U, r->url_chain().size());
6753 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:016754 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196755 EXPECT_EQ(original_url, r->original_url());
6756 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166757 }
6758}
6759
[email protected]f878230e2014-04-03 15:36:146760// When a delegate has specified a safe redirect URL, assume that the redirect
6761// URL should not be changed. In particular, the reference fragment should not
6762// be modified.
6763TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556764 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146765
tommycli59a63432015-11-06 00:10:556766 GURL original_url(
6767 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146768 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6769
6770 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6771 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6772
6773 TestDelegate d;
6774 {
danakj8522a25b2016-04-16 00:17:366775 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366776 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146777
[email protected]f7022f32014-08-21 16:32:196778 r->Start();
[email protected]f878230e2014-04-03 15:36:146779 base::RunLoop().Run();
6780
[email protected]f7022f32014-08-21 16:32:196781 EXPECT_EQ(2U, r->url_chain().size());
6782 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:016783 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196784 EXPECT_EQ(original_url, r->original_url());
6785 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146786 }
6787}
6788
6789// When a URLRequestRedirectJob is created, the redirection must be followed and
6790// the reference fragment of the target URL must not be modified.
6791TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556792 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146793
tommycli59a63432015-11-06 00:10:556794 GURL original_url(
6795 http_test_server()->GetURL("/original#should-not-be-appended"));
6796 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146797
6798 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366799 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366800 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146801
danakj8522a25b2016-04-16 00:17:366802 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196803 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426804 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6805 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146806
[email protected]f7022f32014-08-21 16:32:196807 r->Start();
[email protected]f878230e2014-04-03 15:36:146808 base::RunLoop().Run();
6809
[email protected]f7022f32014-08-21 16:32:196810 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:016811 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:196812 EXPECT_EQ(original_url, r->original_url());
6813 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146814}
6815
lizeb5120f6dc2016-02-19 09:29:446816TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6817 ASSERT_TRUE(http_test_server()->Start());
6818
6819 const std::string referrer("foobar://totally.legit.referrer");
6820 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366821 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446822 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6823 req->SetReferrer(referrer);
6824 req->Start();
6825 base::RunLoop().Run();
6826
6827 EXPECT_EQ(std::string("None"), d.data_received());
6828}
6829
[email protected]316c1e5e2012-09-12 15:17:446830TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556831 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446832
6833 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366834 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556835 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196836 req->SetReferrer("http://user:[email protected]/");
6837 req->Start();
[email protected]255620da2013-08-19 13:14:296838 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446839
6840 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6841}
6842
[email protected]99ecf6e2013-04-10 22:46:136843TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556844 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136845
6846 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366847 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556848 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196849 req->SetReferrer("http://foo.com/test#fragment");
6850 req->Start();
[email protected]255620da2013-08-19 13:14:296851 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136852
6853 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6854}
6855
6856TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556857 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136858
6859 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366860 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556861 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196862 req->SetReferrer("http://foo.com/test#fragment");
6863 req->SetReferrer("");
6864 req->Start();
[email protected]255620da2013-08-19 13:14:296865 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136866
6867 EXPECT_EQ(std::string("None"), d.data_received());
6868}
6869
[email protected]316c1e5e2012-09-12 15:17:446870TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556871 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446872
6873 TestDelegate d;
6874 {
6875 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366876 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556877 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6878 &d));
[email protected]f7022f32014-08-21 16:32:196879 req->Start();
[email protected]255620da2013-08-19 13:14:296880 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446881
6882 EXPECT_EQ(1, d.response_started_count());
6883 EXPECT_EQ(0, d.bytes_received());
6884 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196885 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446886 }
6887}
6888
6889TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556890 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446891
6892 TestDelegate d;
6893 {
6894 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556895 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366896 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366897 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046898
[email protected]f7022f32014-08-21 16:32:196899 req->Start();
[email protected]255620da2013-08-19 13:14:296900 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446901
6902 EXPECT_EQ(1, d.received_redirect_count());
6903
[email protected]f7022f32014-08-21 16:32:196904 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296905 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446906
6907 EXPECT_EQ(1, d.response_started_count());
6908 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196909 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446910
[email protected]6cdfd7f2013-02-08 20:40:156911 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446912 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476913 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446914 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6915
6916 std::string contents;
[email protected]82f84b92013-08-30 18:23:506917 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446918 EXPECT_EQ(contents, d.data_received());
6919 }
6920}
6921
[email protected]79e1fd62013-06-20 06:50:046922TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556923 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046924
6925 TestDelegate d;
6926 {
6927 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556928 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366929 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366930 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046931
6932 EXPECT_FALSE(d.have_full_request_headers());
6933
[email protected]f7022f32014-08-21 16:32:196934 req->Start();
[email protected]255620da2013-08-19 13:14:296935 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046936
6937 EXPECT_EQ(1, d.received_redirect_count());
6938 EXPECT_TRUE(d.have_full_request_headers());
6939 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6940 d.ClearFullRequestHeaders();
6941
[email protected]f7022f32014-08-21 16:32:196942 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296943 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046944
tommycli59a63432015-11-06 00:10:556945 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046946 EXPECT_EQ(1, d.response_started_count());
6947 EXPECT_TRUE(d.have_full_request_headers());
6948 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6949 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196950 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046951
6952 base::FilePath path;
6953 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476954 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046955 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6956
6957 std::string contents;
[email protected]82f84b92013-08-30 18:23:506958 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046959 EXPECT_EQ(contents, d.data_received());
6960 }
6961}
6962
[email protected]316c1e5e2012-09-12 15:17:446963TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556964 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446965
6966 TestDelegate d;
6967 {
6968 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366969 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556970 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6971 &d));
[email protected]f7022f32014-08-21 16:32:196972 req->Start();
[email protected]255620da2013-08-19 13:14:296973 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446974
6975 EXPECT_EQ(1, d.received_redirect_count());
6976
[email protected]f7022f32014-08-21 16:32:196977 req->Cancel();
[email protected]255620da2013-08-19 13:14:296978 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446979
6980 EXPECT_EQ(1, d.response_started_count());
6981 EXPECT_EQ(0, d.bytes_received());
6982 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196983 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446984 }
6985}
6986
6987TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556988 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446989
[email protected]3b23a222013-05-15 21:33:256990 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446991 {
6992 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366993 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556994 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6995 &d));
[email protected]316c1e5e2012-09-12 15:17:446996 HttpRequestHeaders headers;
6997 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196998 req->SetExtraRequestHeaders(headers);
6999 req->Start();
[email protected]255620da2013-08-19 13:14:297000 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:257001
7002 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197003 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257004 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447005 }
7006
[email protected]3b23a222013-05-15 21:33:257007 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:447008 {
7009 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367010 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557011 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7012 &d));
[email protected]316c1e5e2012-09-12 15:17:447013 HttpRequestHeaders headers;
7014 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:197015 req->SetExtraRequestHeaders(headers);
7016 req->Start();
[email protected]255620da2013-08-19 13:14:297017 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447018
[email protected]f7022f32014-08-21 16:32:197019 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257020
7021 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197022 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257023 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:447024 }
7025
[email protected]3b23a222013-05-15 21:33:257026 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:447027 {
7028 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367029 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557030 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7031 &d));
[email protected]316c1e5e2012-09-12 15:17:447032 HttpRequestHeaders headers;
7033 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197034 req->SetExtraRequestHeaders(headers);
7035 req->Start();
[email protected]255620da2013-08-19 13:14:297036 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447037
[email protected]f7022f32014-08-21 16:32:197038 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257039
7040 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197041 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257042 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447043 }
7044}
7045
7046TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557047 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447048
7049 // populate the cache
7050 {
7051 TestDelegate d;
7052 d.set_credentials(AuthCredentials(kUser, kSecret));
7053
danakj8522a25b2016-04-16 00:17:367054 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557055 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197056 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447057
[email protected]255620da2013-08-19 13:14:297058 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447059
7060 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7061 }
7062
7063 // repeat request with end-to-end validation. since auth-basic results in a
7064 // cachable page, we expect this test to result in a 304. in which case, the
7065 // response should be fetched from the cache.
7066 {
7067 TestDelegate d;
7068 d.set_credentials(AuthCredentials(kUser, kSecret));
7069
danakj8522a25b2016-04-16 00:17:367070 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557071 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197072 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7073 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447074
[email protected]255620da2013-08-19 13:14:297075 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447076
7077 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7078
7079 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197080 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447081 }
7082}
7083
7084// Check that Set-Cookie headers in 401 responses are respected.
7085// http://crbug.com/6450
7086TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557087 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447088
7089 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557090 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447091
7092 // Request a page that will give a 401 containing a Set-Cookie header.
7093 // Verify that when the transaction is restarted, it includes the new cookie.
7094 {
[email protected]ceefd7fd2012-11-29 00:36:247095 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447096 TestURLRequestContext context(true);
7097 context.set_network_delegate(&network_delegate);
7098 context.Init();
7099
7100 TestDelegate d;
7101 d.set_credentials(AuthCredentials(kUser, kSecret));
7102
danakj8522a25b2016-04-16 00:17:367103 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367104 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197105 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447106
[email protected]255620da2013-08-19 13:14:297107 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447108
7109 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7110
7111 // Make sure we sent the cookie in the restarted transaction.
7112 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7113 != std::string::npos);
7114 }
7115
7116 // Same test as above, except this time the restart is initiated earlier
7117 // (without user intervention since identity is embedded in the URL).
7118 {
[email protected]ceefd7fd2012-11-29 00:36:247119 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447120 TestURLRequestContext context(true);
7121 context.set_network_delegate(&network_delegate);
7122 context.Init();
7123
7124 TestDelegate d;
7125
7126 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187127 replacements.SetUsernameStr("user2");
7128 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447129 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7130
danakj8522a25b2016-04-16 00:17:367131 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367132 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197133 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447134
[email protected]255620da2013-08-19 13:14:297135 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447136
7137 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7138
7139 // Make sure we sent the cookie in the restarted transaction.
7140 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7141 != std::string::npos);
7142 }
7143}
7144
[email protected]58e32bb2013-01-21 18:23:257145// Tests that load timing works as expected with auth and the cache.
7146TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557147 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257148
7149 // populate the cache
7150 {
7151 TestDelegate d;
7152 d.set_credentials(AuthCredentials(kUser, kSecret));
7153
danakj8522a25b2016-04-16 00:17:367154 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557155 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197156 r->Start();
[email protected]58e32bb2013-01-21 18:23:257157
[email protected]255620da2013-08-19 13:14:297158 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257159
7160 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7161
7162 LoadTimingInfo load_timing_info_before_auth;
7163 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7164 &load_timing_info_before_auth));
7165 TestLoadTimingNotReused(load_timing_info_before_auth,
7166 CONNECT_TIMING_HAS_DNS_TIMES);
7167
7168 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197169 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257170 // The test server does not support keep alive sockets, so the second
7171 // request with auth should use a new socket.
7172 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7173 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7174 load_timing_info.socket_log_id);
7175 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7176 load_timing_info.connect_timing.connect_start);
7177 }
7178
[email protected]3b23a222013-05-15 21:33:257179 // Repeat request with end-to-end validation. Since auth-basic results in a
7180 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257181 // response should be fetched from the cache.
7182 {
7183 TestDelegate d;
7184 d.set_credentials(AuthCredentials(kUser, kSecret));
7185
danakj8522a25b2016-04-16 00:17:367186 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557187 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197188 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7189 r->Start();
[email protected]58e32bb2013-01-21 18:23:257190
[email protected]255620da2013-08-19 13:14:297191 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257192
7193 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7194
7195 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197196 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257197
[email protected]3b23a222013-05-15 21:33:257198 // Since there was a request that went over the wire, the load timing
7199 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257200 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197201 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257202 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257203 }
7204}
7205
[email protected]316c1e5e2012-09-12 15:17:447206// In this test, we do a POST which the server will 302 redirect.
7207// The subsequent transaction should use GET, and should not send the
7208// Content-Type header.
7209// http://code.google.com/p/chromium/issues/detail?id=843
7210TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557211 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447212
7213 const char kData[] = "hello world";
7214
7215 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367216 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557217 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7218 &d));
[email protected]f7022f32014-08-21 16:32:197219 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077220 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447221
7222 // Set headers (some of which are specific to the POST).
7223 HttpRequestHeaders headers;
7224 headers.AddHeadersFromString(
7225 "Content-Type: multipart/form-data; "
7226 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7227 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7228 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7229 "Accept-Language: en-US,en\r\n"
7230 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7231 "Content-Length: 11\r\n"
7232 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197233 req->SetExtraRequestHeaders(headers);
7234 req->Start();
[email protected]255620da2013-08-19 13:14:297235 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447236
7237 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197238 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447239 EXPECT_EQ("text/html", mime_type);
7240
7241 const std::string& data = d.data_received();
7242
7243 // Check that the post-specific headers were stripped:
7244 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7245 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7246 EXPECT_FALSE(ContainsString(data, "Origin:"));
7247
7248 // These extra request headers should not have been stripped.
7249 EXPECT_TRUE(ContainsString(data, "Accept:"));
7250 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7251 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7252}
7253
jww5fe460ff2015-03-28 00:22:517254// The following tests check that we handle mutating the request for HTTP
7255// redirects as expected.
7256// See https://crbug.com/56373, https://crbug.com/102130, and
7257// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447258
7259TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557260 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447261
tommycli59a63432015-11-06 00:10:557262 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517263 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557264 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447265
7266 HTTPRedirectMethodTest(url, "POST", "GET", true);
7267 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7268 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517269
7270 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7271 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7272 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7273 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7274 std::string());
[email protected]316c1e5e2012-09-12 15:17:447275}
7276
7277TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557278 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447279
tommycli59a63432015-11-06 00:10:557280 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517281 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557282 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447283
7284 HTTPRedirectMethodTest(url, "POST", "GET", true);
7285 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7286 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517287
7288 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7289 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7290 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7291 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7292 std::string());
[email protected]316c1e5e2012-09-12 15:17:447293}
7294
7295TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557296 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447297
tommycli59a63432015-11-06 00:10:557298 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517299 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557300 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447301
7302 HTTPRedirectMethodTest(url, "POST", "GET", true);
7303 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7304 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517305
7306 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7307 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7308 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7309 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7310 std::string());
[email protected]316c1e5e2012-09-12 15:17:447311}
7312
7313TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557314 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447315
tommycli59a63432015-11-06 00:10:557316 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517317 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557318 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447319
7320 HTTPRedirectMethodTest(url, "POST", "POST", true);
7321 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7322 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517323
7324 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7325 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7326 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7327 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447328}
7329
[email protected]0a17aab32014-04-24 03:32:377330TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557331 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377332
tommycli59a63432015-11-06 00:10:557333 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517334 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557335 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377336
7337 HTTPRedirectMethodTest(url, "POST", "POST", true);
7338 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7339 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517340
7341 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7342 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7343 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7344 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377345}
7346
7347// Make sure that 308 responses without bodies are not treated as redirects.
7348// Certain legacy apis that pre-date the response code expect this behavior
7349// (Like Google Drive).
7350TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557351 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377352
7353 TestDelegate d;
tommycli59a63432015-11-06 00:10:557354 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377355
danakj8522a25b2016-04-16 00:17:367356 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367357 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377358
[email protected]f7022f32014-08-21 16:32:197359 request->Start();
[email protected]0a17aab32014-04-24 03:32:377360 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197361 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
robpercival214763f2016-07-01 23:27:017362 EXPECT_THAT(request->status().error(), IsOk());
[email protected]0a17aab32014-04-24 03:32:377363 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197364 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377365 EXPECT_EQ("This is not a redirect.", d.data_received());
7366}
7367
[email protected]f878230e2014-04-03 15:36:147368TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557369 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147370
tommycli59a63432015-11-06 00:10:557371 GURL original_url(
7372 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7373 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147374
7375 TestDelegate d;
7376 {
danakj8522a25b2016-04-16 00:17:367377 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367378 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147379
[email protected]f7022f32014-08-21 16:32:197380 r->Start();
[email protected]f878230e2014-04-03 15:36:147381 base::RunLoop().Run();
7382
[email protected]f7022f32014-08-21 16:32:197383 EXPECT_EQ(2U, r->url_chain().size());
7384 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:017385 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197386 EXPECT_EQ(original_url, r->original_url());
7387 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147388 }
7389}
7390
[email protected]cba24642014-08-15 20:49:597391TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557392 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597393
tommycli59a63432015-11-06 00:10:557394 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597395 GURL first_party_url("http://example.com");
7396
7397 TestDelegate d;
7398 {
danakj8522a25b2016-04-16 00:17:367399 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367400 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197401 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597402
[email protected]f7022f32014-08-21 16:32:197403 r->Start();
[email protected]cba24642014-08-15 20:49:597404 base::RunLoop().Run();
7405
[email protected]f7022f32014-08-21 16:32:197406 EXPECT_EQ(2U, r->url_chain().size());
7407 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:017408 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197409 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597410 }
7411}
7412
7413TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557414 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597415
tommycli59a63432015-11-06 00:10:557416 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597417 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557418 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597419
7420 TestDelegate d;
7421 {
danakj8522a25b2016-04-16 00:17:367422 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367423 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197424 r->set_first_party_for_cookies(original_first_party_url);
7425 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597426 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7427
[email protected]f7022f32014-08-21 16:32:197428 r->Start();
[email protected]cba24642014-08-15 20:49:597429 base::RunLoop().Run();
7430
[email protected]f7022f32014-08-21 16:32:197431 EXPECT_EQ(2U, r->url_chain().size());
7432 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
robpercival214763f2016-07-01 23:27:017433 EXPECT_THAT(r->status().error(), IsOk());
[email protected]f7022f32014-08-21 16:32:197434 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597435 }
7436}
7437
[email protected]316c1e5e2012-09-12 15:17:447438TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557439 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447440
7441 const char kData[] = "hello world";
7442
7443 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367444 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557445 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197446 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077447 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447448 HttpRequestHeaders headers;
7449 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517450 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197451 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447452
danakj8522a25b2016-04-16 00:17:367453 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557454 req.get(), &default_network_delegate_,
7455 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427456 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7457 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447458
[email protected]f7022f32014-08-21 16:32:197459 req->Start();
[email protected]255620da2013-08-19 13:14:297460 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197461 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447462}
7463
7464TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557465 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447466
7467 const char kData[] = "hello world";
7468
7469 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367470 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557471 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197472 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077473 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447474 HttpRequestHeaders headers;
7475 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517476 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197477 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447478
danakj8522a25b2016-04-16 00:17:367479 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557480 req.get(), &default_network_delegate_,
7481 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097482 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427483 "Very Good Reason"));
7484 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447485
[email protected]f7022f32014-08-21 16:32:197486 req->Start();
[email protected]255620da2013-08-19 13:14:297487 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197488 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447489 EXPECT_EQ(kData, d.data_received());
7490}
7491
7492// Check that default A-L header is sent.
7493TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557494 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447495
[email protected]8790210c2013-12-02 05:29:537496 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247497 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447498 TestURLRequestContext context(true);
7499 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437500 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447501 context.Init();
7502
7503 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367504 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557505 http_test_server()->GetURL("/echoheader?Accept-Language"),
7506 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197507 req->Start();
[email protected]255620da2013-08-19 13:14:297508 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447509 EXPECT_EQ("en", d.data_received());
7510}
7511
7512// Check that an empty A-L header is not sent. http://crbug.com/77365.
7513TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557514 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447515
[email protected]8790210c2013-12-02 05:29:537516 std::string empty_string; // Avoid most vexing parse on line below.
7517 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247518 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447519 TestURLRequestContext context(true);
7520 context.set_network_delegate(&network_delegate);
7521 context.Init();
7522 // We override the language after initialization because empty entries
7523 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437524 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447525
7526 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367527 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557528 http_test_server()->GetURL("/echoheader?Accept-Language"),
7529 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197530 req->Start();
[email protected]255620da2013-08-19 13:14:297531 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447532 EXPECT_EQ("None", d.data_received());
7533}
7534
7535// Check that if request overrides the A-L header, the default is not appended.
7536// See http://crbug.com/20894
7537TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557538 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447539
7540 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367541 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557542 http_test_server()->GetURL("/echoheader?Accept-Language"),
7543 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447544 HttpRequestHeaders headers;
7545 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197546 req->SetExtraRequestHeaders(headers);
7547 req->Start();
[email protected]255620da2013-08-19 13:14:297548 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447549 EXPECT_EQ(std::string("ru"), d.data_received());
7550}
7551
7552// Check that default A-E header is sent.
7553TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557554 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447555
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("/echoheader?Accept-Encoding"),
7559 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447560 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197561 req->SetExtraRequestHeaders(headers);
7562 req->Start();
[email protected]255620da2013-08-19 13:14:297563 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447564 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7565}
7566
7567// Check that if request overrides the A-E header, the default is not appended.
7568// See http://crbug.com/47381
7569TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557570 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447571
7572 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367573 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557574 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7575 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447576 HttpRequestHeaders headers;
7577 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197578 req->SetExtraRequestHeaders(headers);
7579 req->Start();
[email protected]255620da2013-08-19 13:14:297580 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447581 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7582 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7583}
7584
[email protected]84f05432013-03-15 01:00:127585// Check that setting the A-C header sends the proper header.
7586TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
tommycli59a63432015-11-06 00:10:557587 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447588
7589 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367590 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557591 http_test_server()->GetURL("/echoheader?Accept-Charset"),
7592 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447593 HttpRequestHeaders headers;
7594 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197595 req->SetExtraRequestHeaders(headers);
7596 req->Start();
[email protected]255620da2013-08-19 13:14:297597 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447598 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7599}
7600
7601// Check that default User-Agent header is sent.
7602TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
tommycli59a63432015-11-06 00:10:557603 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447604
7605 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367606 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557607 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7608 &d));
[email protected]f7022f32014-08-21 16:32:197609 req->Start();
[email protected]255620da2013-08-19 13:14:297610 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197611 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377612 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447613}
7614
7615// Check that if request overrides the User-Agent header,
7616// the default is not appended.
marqf14fff8d2015-12-02 15:52:297617// TODO(crbug.com/564656) This test is flaky on iOS.
7618#if defined(OS_IOS)
7619#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7620#else
7621#define MAYBE_OverrideUserAgent OverrideUserAgent
7622#endif
7623TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557624 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447625
7626 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367627 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557628 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7629 &d));
[email protected]316c1e5e2012-09-12 15:17:447630 HttpRequestHeaders headers;
7631 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197632 req->SetExtraRequestHeaders(headers);
7633 req->Start();
[email protected]255620da2013-08-19 13:14:297634 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357635 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447636}
7637
[email protected]ee4c30d2012-11-07 15:08:437638// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7639// User-Agent header to be sent but does not send the Accept-Language and
7640// Accept-Charset headers.
7641TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557642 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437643
[email protected]ceefd7fd2012-11-29 00:36:247644 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437645 TestURLRequestContext context(true);
7646 context.set_network_delegate(&network_delegate);
7647 context.Init();
7648 // We override the HttpUserAgentSettings after initialization because empty
7649 // entries get overridden by Init().
7650 context.set_http_user_agent_settings(NULL);
7651
7652 struct {
7653 const char* request;
7654 const char* expected_response;
tommycli59a63432015-11-06 00:10:557655 } tests[] = {{"/echoheader?Accept-Language", "None"},
7656 {"/echoheader?Accept-Charset", "None"},
7657 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437658
viettrungluue4a8b882014-10-16 06:17:387659 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437660 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367661 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557662 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197663 req->Start();
[email protected]255620da2013-08-19 13:14:297664 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437665 EXPECT_EQ(tests[i].expected_response, d.data_received())
7666 << " Request = \"" << tests[i].request << "\"";
7667 }
7668}
7669
[email protected]5033ab82013-03-22 20:17:467670// Make sure that URLRequest passes on its priority updates to
7671// newly-created jobs after the first one.
7672TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557673 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467674
7675 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367676 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557677 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197678 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467679
danakj8522a25b2016-04-16 00:17:367680 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557681 req.get(), &default_network_delegate_,
7682 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427683 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7684 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467685
[email protected]f7022f32014-08-21 16:32:197686 req->SetPriority(LOW);
7687 req->Start();
7688 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467689
mmenkeed0498b2015-12-08 23:20:427690 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367691 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427692 req.get(), &default_network_delegate_, &job_priority));
7693 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467694
7695 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297696 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427697 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467698}
7699
[email protected]80abdad2014-03-15 00:20:547700// Check that creating a network request while entering/exiting suspend mode
7701// fails as it should. This is the only case where an HttpTransactionFactory
7702// does not return an HttpTransaction.
7703TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7704 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367705 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177706 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547707 network_layer->OnSuspend();
7708
dchengc7eeda422015-12-26 03:56:487709 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427710 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547711
7712 TestURLRequestContext context(true);
7713 context.set_http_transaction_factory(&http_cache);
7714 context.Init();
7715
7716 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367717 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367718 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197719 req->Start();
[email protected]80abdad2014-03-15 00:20:547720 base::RunLoop().Run();
7721
7722 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197723 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
robpercival214763f2016-07-01 23:27:017724 EXPECT_THAT(req->status().error(), IsError(ERR_NETWORK_IO_SUSPENDED));
[email protected]80abdad2014-03-15 00:20:547725}
7726
mmenke2281f3762015-11-02 20:38:177727namespace {
[email protected]80abdad2014-03-15 00:20:547728
mmenke2281f3762015-11-02 20:38:177729// HttpTransactionFactory that synchronously fails to create transactions.
7730class FailingHttpTransactionFactory : public HttpTransactionFactory {
7731 public:
7732 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7733 : network_session_(network_session) {}
7734
7735 ~FailingHttpTransactionFactory() override {}
7736
7737 // HttpTransactionFactory methods:
7738 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367739 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177740 return ERR_FAILED;
7741 }
7742
7743 HttpCache* GetCache() override { return nullptr; }
7744
7745 HttpNetworkSession* GetSession() override { return network_session_; }
7746
7747 private:
7748 HttpNetworkSession* network_session_;
7749
7750 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7751};
7752
7753} // namespace
7754
7755// Check that when a request that fails to create an HttpTransaction can be
7756// cancelled while the failure notification is pending, and doesn't send two
7757// failure notifications.
7758//
7759// This currently only happens when in suspend mode and there's no cache, but
7760// just use a special HttpTransactionFactory, to avoid depending on those
7761// behaviors.
7762TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7763 FailingHttpTransactionFactory http_transaction_factory(
7764 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547765 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177766 context.set_http_transaction_factory(&http_transaction_factory);
7767 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547768 context.Init();
7769
7770 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367771 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367772 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177773 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7774 // try to create an HttpNetworkTransaction synchronously on start).
7775 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197776 req->Start();
mmenke2281f3762015-11-02 20:38:177777 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547778 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177779 // Run pending error task, if there is one.
7780 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547781
7782 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177783 EXPECT_EQ(1, d.response_started_count());
7784 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
7785
7786 // NetworkDelegate should see the cancellation, but not the error.
7787 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7788 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547789}
7790
ttuttlec0c828492015-05-15 01:25:557791TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557792 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557793
7794 TestDelegate d;
tommycli59a63432015-11-06 00:10:557795 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367796 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557797 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7798
7799 req->Start();
7800 base::RunLoop().Run();
7801
7802 EXPECT_TRUE(req->response_info().network_accessed);
7803}
7804
7805TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557806 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557807
7808 // Populate the cache.
7809 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367810 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557811 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557812 req->Start();
7813 base::RunLoop().Run();
7814
7815 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7816 EXPECT_TRUE(req->response_info().network_accessed);
7817 EXPECT_FALSE(req->response_info().was_cached);
7818
tommycli59a63432015-11-06 00:10:557819 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557820 DEFAULT_PRIORITY, &d);
7821 req->Start();
7822 base::RunLoop().Run();
7823
7824 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
7825 EXPECT_FALSE(req->response_info().network_accessed);
7826 EXPECT_TRUE(req->response_info().was_cached);
7827}
7828
7829TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557830 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557831
7832 TestDelegate d;
tommycli59a63432015-11-06 00:10:557833 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367834 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557835 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7836 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7837
7838 req->Start();
7839 base::RunLoop().Run();
7840
7841 EXPECT_FALSE(req->response_info().network_accessed);
7842}
7843
ricea3a1c71f2016-06-17 10:05:267844TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
7845 ASSERT_TRUE(http_test_server()->Start());
7846
7847 TestDelegate d;
7848 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7849 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
7850 req->Start();
7851 base::RunLoop().Run();
7852
7853 EXPECT_EQ(5, req->GetRawBodyBytes());
7854}
7855
7856TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
7857 ASSERT_TRUE(http_test_server()->Start());
7858
7859 TestDelegate d;
7860 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7861 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
7862 req->Start();
7863 base::RunLoop().Run();
7864
7865 EXPECT_EQ(30, req->GetRawBodyBytes());
7866}
7867
bengr1bf8e942014-11-07 01:36:507868class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7869 public:
7870 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7871 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7872 // tests into the factory tests.
7873 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7874 }
7875
7876 void SetUpFactory() override {
7877 interceptor_ = new MockURLRequestInterceptor();
7878 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:367879 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:507880 }
7881
7882 MockURLRequestInterceptor* interceptor() const {
7883 return interceptor_;
7884 }
7885
7886 private:
7887 MockURLRequestInterceptor* interceptor_;
7888};
7889
7890TEST_F(URLRequestInterceptorTestHTTP,
7891 NetworkDelegateNotificationOnRedirectIntercept) {
7892 interceptor()->set_intercept_redirect(true);
7893 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7894 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7895
tommycli59a63432015-11-06 00:10:557896 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507897
7898 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367899 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557900 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507901 req->Start();
7902 base::RunLoop().Run();
7903
7904 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7905 // Check we got one good response
7906 EXPECT_TRUE(req->status().is_success());
7907 if (req->status().is_success())
7908 EXPECT_EQ(200, req->response_headers()->response_code());
7909
7910 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7911 EXPECT_EQ(1, d.response_started_count());
7912 EXPECT_EQ(0, d.received_redirect_count());
7913
7914 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007915 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507916 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7917}
7918
7919TEST_F(URLRequestInterceptorTestHTTP,
7920 NetworkDelegateNotificationOnErrorIntercept) {
7921 // Intercept that error and respond with an OK response.
7922 interceptor()->set_intercept_final_response(true);
7923 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7924 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7925 default_network_delegate()->set_can_be_intercepted_on_error(true);
7926
tommycli59a63432015-11-06 00:10:557927 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507928
7929 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367930 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557931 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367932 &d));
bengr1bf8e942014-11-07 01:36:507933 req->set_method("GET");
7934 req->Start();
7935 base::RunLoop().Run();
7936
7937 EXPECT_TRUE(interceptor()->did_intercept_final());
7938
7939 // Check we received one good response.
7940 EXPECT_TRUE(req->status().is_success());
7941 if (req->status().is_success())
7942 EXPECT_EQ(200, req->response_headers()->response_code());
7943 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7944 EXPECT_EQ(1, d.response_started_count());
7945 EXPECT_EQ(0, d.received_redirect_count());
7946
7947 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007948 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507949 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7950}
7951
7952TEST_F(URLRequestInterceptorTestHTTP,
7953 NetworkDelegateNotificationOnResponseIntercept) {
7954 // Intercept that error and respond with an OK response.
7955 interceptor()->set_intercept_final_response(true);
7956
7957 // Intercept with a real URLRequestHttpJob.
7958 interceptor()->set_use_url_request_http_job(true);
7959
tommycli59a63432015-11-06 00:10:557960 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507961
7962 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367963 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557964 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507965 req->set_method("GET");
7966 req->Start();
7967 base::RunLoop().Run();
7968
7969 EXPECT_TRUE(interceptor()->did_intercept_final());
7970
7971 // Check we received one good response.
7972 EXPECT_TRUE(req->status().is_success());
7973 if (req->status().is_success())
7974 EXPECT_EQ(200, req->response_headers()->response_code());
7975 EXPECT_EQ("hello", d.data_received());
7976 EXPECT_EQ(1, d.response_started_count());
7977 EXPECT_EQ(0, d.received_redirect_count());
7978
7979 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007980 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507981 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7982}
7983
mkwst0c5eab872014-11-21 14:18:547984class URLRequestTestReferrerPolicy : public URLRequestTest {
7985 public:
7986 URLRequestTestReferrerPolicy() {}
7987
tommycli59a63432015-11-06 00:10:557988 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7989 origin_server_.reset(new EmbeddedTestServer(type));
7990 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7991 origin_server_->AddDefaultHandlers(
7992 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7993 } else {
7994 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7995 }
mkwst0c5eab872014-11-21 14:18:547996 ASSERT_TRUE(origin_server_->Start());
7997 }
7998
tommycli59a63432015-11-06 00:10:557999 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
8000 net::EmbeddedTestServer::Type dest_type) {
8001 origin_server_.reset(new EmbeddedTestServer(origin_type));
8002 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8003 origin_server_->AddDefaultHandlers(
8004 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8005 } else {
8006 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8007 }
mkwst0c5eab872014-11-21 14:18:548008 ASSERT_TRUE(origin_server_->Start());
8009
tommycli59a63432015-11-06 00:10:558010 destination_server_.reset(new EmbeddedTestServer(dest_type));
8011 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
8012 destination_server_->AddDefaultHandlers(
8013 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8014 } else {
8015 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8016 }
mkwst0c5eab872014-11-21 14:18:548017 ASSERT_TRUE(destination_server_->Start());
8018 }
8019
8020 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8021 const GURL& referrer,
8022 const GURL& expected) {
8023 // Create and execute the request: we'll only have a |destination_server_|
8024 // if the origins are meant to be distinct. Otherwise, we'll use the
8025 // |origin_server_| for both endpoints.
8026 GURL destination_url =
tommycli59a63432015-11-06 00:10:558027 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8028 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548029 GURL origin_url =
tommycli59a63432015-11-06 00:10:558030 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548031
8032 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368033 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368034 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548035 req->set_referrer_policy(policy);
8036 req->SetReferrer(referrer.spec());
8037 req->Start();
8038 base::RunLoop().Run();
8039
8040 EXPECT_EQ(1, d.response_started_count());
8041 EXPECT_EQ(1, d.received_redirect_count());
8042 EXPECT_EQ(destination_url, req->url());
8043 EXPECT_TRUE(req->status().is_success());
8044 EXPECT_EQ(200, req->response_headers()->response_code());
8045
8046 EXPECT_EQ(expected.spec(), req->referrer());
8047 if (expected.is_empty())
8048 EXPECT_EQ("None", d.data_received());
8049 else
8050 EXPECT_EQ(expected.spec(), d.data_received());
8051 }
8052
tommycli59a63432015-11-06 00:10:558053 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548054
8055 private:
danakj8522a25b2016-04-16 00:17:368056 std::unique_ptr<EmbeddedTestServer> origin_server_;
8057 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548058};
8059
8060TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558061 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548062
8063 VerifyReferrerAfterRedirect(
8064 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558065 origin_server()->GetURL("/path/to/file.html"),
8066 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548067
8068 VerifyReferrerAfterRedirect(
8069 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558070 origin_server()->GetURL("/path/to/file.html"),
8071 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548072
8073 VerifyReferrerAfterRedirect(
8074 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558075 origin_server()->GetURL("/path/to/file.html"),
8076 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548077
8078 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558079 origin_server()->GetURL("/path/to/file.html"),
8080 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548081}
8082
tommycli59a63432015-11-06 00:10:558083TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8084 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8085 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548086
8087 VerifyReferrerAfterRedirect(
8088 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558089 origin_server()->GetURL("/path/to/file.html"),
8090 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548091
8092 VerifyReferrerAfterRedirect(
8093 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558094 origin_server()->GetURL("/path/to/file.html"),
8095 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548096
8097 VerifyReferrerAfterRedirect(
8098 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558099 origin_server()->GetURL("/path/to/file.html"),
8100 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548101
8102 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558103 origin_server()->GetURL("/path/to/file.html"),
8104 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548105}
8106
8107TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558108 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548109
8110 VerifyReferrerAfterRedirect(
8111 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558112 origin_server()->GetURL("/path/to/file.html"),
8113 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548114
8115 VerifyReferrerAfterRedirect(
8116 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558117 origin_server()->GetURL("/path/to/file.html"),
8118 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548119
8120 VerifyReferrerAfterRedirect(
8121 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558122 origin_server()->GetURL("/path/to/file.html"),
8123 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548124
8125 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558126 origin_server()->GetURL("/path/to/file.html"),
8127 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548128}
8129
tommycli59a63432015-11-06 00:10:558130TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8131 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8132 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548133
8134 VerifyReferrerAfterRedirect(
8135 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558136 origin_server()->GetURL("/path/to/file.html"),
8137 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548138
8139 VerifyReferrerAfterRedirect(
8140 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558141 origin_server()->GetURL("/path/to/file.html"),
8142 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548143
8144 VerifyReferrerAfterRedirect(
8145 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558146 origin_server()->GetURL("/path/to/file.html"),
8147 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548148
8149 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558150 origin_server()->GetURL("/path/to/file.html"),
8151 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548152}
8153
tommycli59a63432015-11-06 00:10:558154TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8155 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8156 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548157
8158 VerifyReferrerAfterRedirect(
8159 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558160 origin_server()->GetURL("/path/to/file.html"),
8161 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548162
8163 VerifyReferrerAfterRedirect(
8164 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558165 origin_server()->GetURL("/path/to/file.html"),
8166 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548167
8168 VerifyReferrerAfterRedirect(
8169 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558170 origin_server()->GetURL("/path/to/file.html"),
8171 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548172
8173 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558174 origin_server()->GetURL("/path/to/file.html"),
8175 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548176}
8177
tommycli59a63432015-11-06 00:10:558178TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8179 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8180 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548181
8182 VerifyReferrerAfterRedirect(
8183 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558184 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548185
8186 VerifyReferrerAfterRedirect(
8187 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558188 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548189
8190 VerifyReferrerAfterRedirect(
8191 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558192 origin_server()->GetURL("/path/to/file.html"),
8193 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548194
8195 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558196 origin_server()->GetURL("/path/to/file.html"),
8197 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548198}
8199
[email protected]73e0bba2009-02-19 22:57:098200class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508201 public:
[email protected]ef2bf422012-05-11 03:27:098202 HTTPSRequestTest() : default_context_(true) {
8203 default_context_.set_network_delegate(&default_network_delegate_);
8204 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508205 }
dcheng67be2b1f2014-10-27 21:47:298206 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508207
8208 protected:
[email protected]ceefd7fd2012-11-29 00:36:248209 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098210 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468211};
8212
[email protected]c044616e2013-02-20 02:01:268213TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558214 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8215 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228216 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118217 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468218
[email protected]ea224582008-12-07 20:25:468219 TestDelegate d;
8220 {
danakj8522a25b2016-04-16 00:17:368221 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558222 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198223 r->Start();
8224 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468225
[email protected]255620da2013-08-19 13:14:298226 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468227
8228 EXPECT_EQ(1, d.response_started_count());
8229 EXPECT_FALSE(d.received_data_before_response());
8230 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198231 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198232 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198233 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198234 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198235 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468236 }
[email protected]ea224582008-12-07 20:25:468237}
8238
[email protected]5774ada2010-07-15 06:30:548239TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558240 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8241 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8242 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228243 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118244 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338245
8246 bool err_allowed = true;
8247 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8248 TestDelegate d;
8249 {
8250 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368251 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558252 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338253
[email protected]f7022f32014-08-21 16:32:198254 r->Start();
8255 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338256
[email protected]255620da2013-08-19 13:14:298257 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338258
8259 EXPECT_EQ(1, d.response_started_count());
8260 EXPECT_FALSE(d.received_data_before_response());
8261 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178262 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338263 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198264 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178265 } else {
[email protected]bacff652009-03-31 17:50:338266 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178267 }
[email protected]bacff652009-03-31 17:50:338268 }
8269 }
8270}
8271
[email protected]5774ada2010-07-15 06:30:548272TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558273 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8274 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8275 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228276 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118277 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338278
8279 // Iterate from false to true, just so that we do the opposite of the
8280 // previous test in order to increase test coverage.
8281 bool err_allowed = false;
8282 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8283 TestDelegate d;
8284 {
8285 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368286 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558287 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338288
[email protected]f7022f32014-08-21 16:32:198289 r->Start();
8290 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338291
[email protected]255620da2013-08-19 13:14:298292 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338293
8294 EXPECT_EQ(1, d.response_started_count());
8295 EXPECT_FALSE(d.received_data_before_response());
8296 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178297 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338298 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198299 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178300 } else {
[email protected]bacff652009-03-31 17:50:338301 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178302 }
[email protected]bacff652009-03-31 17:50:338303 }
8304 }
8305}
[email protected]73e0bba2009-02-19 22:57:098306
tommycli59a63432015-11-06 00:10:558307// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8308// security state. (see http://crbug.com/550977).
8309#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448310// This tests that a load of www.google.com with a certificate error sets
8311// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8312// the interstitial to be fatal.
8313TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558314 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8315 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8316 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448317 ASSERT_TRUE(test_server.Start());
8318
8319 // We require that the URL be www.google.com in order to pick up the
8320 // preloaded HSTS entries in the TransportSecurityState. This means that we
8321 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248322 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448323
8324 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248325 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448326 TestURLRequestContext context(true);
8327 context.set_network_delegate(&network_delegate);
8328 context.set_host_resolver(&host_resolver);
8329 TransportSecurityState transport_security_state;
8330 context.set_transport_security_state(&transport_security_state);
8331 context.Init();
8332
8333 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368334 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198335 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368336 test_server.host_port_pair().port())),
8337 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448338
[email protected]f7022f32014-08-21 16:32:198339 r->Start();
8340 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448341
[email protected]255620da2013-08-19 13:14:298342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448343
8344 EXPECT_EQ(1, d.response_started_count());
8345 EXPECT_FALSE(d.received_data_before_response());
8346 EXPECT_TRUE(d.have_certificate_errors());
8347 EXPECT_TRUE(d.certificate_errors_are_fatal());
8348}
8349
8350// This tests that cached HTTPS page loads do not cause any updates to the
8351// TransportSecurityState.
8352TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8353 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8354 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558355 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8356 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8357 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448358 ASSERT_TRUE(test_server.Start());
8359
[email protected]9e6968d2014-05-07 21:46:268360 // We require that the URL be www.google.com in order to pick up the static
8361 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8362 // that we have to use a MockHostResolver in order to direct www.google.com to
8363 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448364
8365 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248366 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448367 TestURLRequestContext context(true);
8368 context.set_network_delegate(&network_delegate);
8369 context.set_host_resolver(&host_resolver);
8370 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268371
martijnc0d6b622015-06-30 19:14:408372 TransportSecurityState::STSState static_sts_state;
8373 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268374 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408375 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448376 context.set_transport_security_state(&transport_security_state);
8377 context.Init();
8378
martijnc0d6b622015-06-30 19:14:408379 TransportSecurityState::STSState dynamic_sts_state;
8380 TransportSecurityState::PKPState dynamic_pkp_state;
8381 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8382 &dynamic_sts_state));
8383 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8384 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268385
[email protected]316c1e5e2012-09-12 15:17:448386 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368387 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198388 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368389 test_server.host_port_pair().port())),
8390 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448391
[email protected]f7022f32014-08-21 16:32:198392 r->Start();
8393 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448394
[email protected]255620da2013-08-19 13:14:298395 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448396
8397 EXPECT_EQ(1, d.response_started_count());
8398 EXPECT_FALSE(d.received_data_before_response());
8399 EXPECT_TRUE(d.have_certificate_errors());
8400 EXPECT_TRUE(d.certificate_errors_are_fatal());
8401
[email protected]9e6968d2014-05-07 21:46:268402 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408403 TransportSecurityState::STSState new_static_sts_state;
8404 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268405 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408406 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8407 TransportSecurityState::STSState new_dynamic_sts_state;
8408 TransportSecurityState::PKPState new_dynamic_pkp_state;
8409 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8410 "www.google.com", &new_dynamic_sts_state));
8411 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8412 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268413
martijnc0d6b622015-06-30 19:14:408414 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8415 EXPECT_EQ(new_static_sts_state.include_subdomains,
8416 static_sts_state.include_subdomains);
8417 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8418 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488419 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8420 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8421 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448422}
8423
[email protected]8ccc69f2012-11-28 19:52:148424// Make sure HSTS preserves a POST request's method and body.
8425TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8426 static const char kData[] = "hello world";
8427
tommycli59a63432015-11-06 00:10:558428 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8429 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228430 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148431 ASSERT_TRUE(test_server.Start());
8432
8433
8434 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8435 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558436 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228437 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148438 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148439
8440 // Force https for www.somewhere.com.
8441 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208442 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8443 bool include_subdomains = false;
8444 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8445 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148446
8447 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8448
8449 TestURLRequestContext context(true);
8450 context.set_host_resolver(&host_resolver);
8451 context.set_transport_security_state(&transport_security_state);
8452 context.set_network_delegate(&network_delegate);
8453 context.Init();
8454
8455 TestDelegate d;
8456 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8457 // cause a certificate error. Ignore the error.
8458 d.set_allow_certificate_errors(true);
8459
danakj8522a25b2016-04-16 00:17:368460 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198461 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368462 test_server.host_port_pair().port())),
8463 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198464 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078465 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148466
[email protected]f7022f32014-08-21 16:32:198467 req->Start();
[email protected]255620da2013-08-19 13:14:298468 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148469
[email protected]f7022f32014-08-21 16:32:198470 EXPECT_EQ("https", req->url().scheme());
8471 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148472 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408473
8474 LoadTimingInfo load_timing_info;
8475 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8476 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8477 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148478}
8479
rob4e0be1f2014-09-11 23:40:228480// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8481TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8482 static const char kOriginHeaderValue[] = "http://www.example.com";
8483
tommycli59a63432015-11-06 00:10:558484 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8485 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228486 ASSERT_TRUE(test_server.Start());
8487
8488 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8489 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558490 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8491 // default.
rob4e0be1f2014-09-11 23:40:228492 MockHostResolver host_resolver;
8493
8494 TransportSecurityState transport_security_state;
8495 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8496 bool include_subdomains = false;
8497 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8498
8499 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8500
8501 MockCertVerifier cert_verifier;
8502 cert_verifier.set_default_result(OK);
8503
8504 TestURLRequestContext context(true);
8505 context.set_host_resolver(&host_resolver);
8506 context.set_transport_security_state(&transport_security_state);
8507 context.set_network_delegate(&network_delegate);
8508 context.set_cert_verifier(&cert_verifier);
8509 context.Init();
8510
8511 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8512 test_server.host_port_pair().port()));
8513 url::Replacements<char> replacements;
8514 const char kNewScheme[] = "https";
8515 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8516 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8517
8518 TestDelegate d;
8519 // Quit on redirect to allow response header inspection upon redirect.
8520 d.set_quit_on_redirect(true);
8521
danakj8522a25b2016-04-16 00:17:368522 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368523 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228524 // Set Origin header to simulate a cross-origin request.
8525 HttpRequestHeaders request_headers;
8526 request_headers.SetHeader("Origin", kOriginHeaderValue);
8527 req->SetExtraRequestHeaders(request_headers);
8528
8529 req->Start();
8530 base::RunLoop().Run();
8531
8532 EXPECT_EQ(1, d.received_redirect_count());
8533
8534 const HttpResponseHeaders* headers = req->response_headers();
8535 std::string redirect_location;
8536 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8537 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8538
8539 std::string received_cors_header;
8540 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8541 &received_cors_header));
8542 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8543}
8544
davidbenb4c25b62016-06-24 02:39:278545// Test that DHE-only servers fail with the expected dedicated error code.
8546TEST_F(HTTPSRequestTest, DHE) {
8547 SpawnedTestServer::SSLOptions ssl_options;
8548 ssl_options.key_exchanges =
8549 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
8550 SpawnedTestServer test_server(
8551 SpawnedTestServer::TYPE_HTTPS, ssl_options,
8552 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8553 ASSERT_TRUE(test_server.Start());
8554
8555 TestDelegate d;
8556 {
8557 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8558 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
8559
8560 r->Start();
8561 EXPECT_TRUE(r->is_pending());
8562
8563 base::RunLoop().Run();
8564
8565 EXPECT_EQ(1, d.response_started_count());
8566 EXPECT_FALSE(r->status().is_success());
8567 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
robpercival214763f2016-07-01 23:27:018568 EXPECT_THAT(r->status().error(), IsError(ERR_SSL_OBSOLETE_CIPHER));
davidbenb4c25b62016-06-24 02:39:278569 }
8570}
8571
[email protected]316c1e5e2012-09-12 15:17:448572namespace {
8573
8574class SSLClientAuthTestDelegate : public TestDelegate {
8575 public:
8576 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8577 }
dchengb03027d2014-10-21 12:00:208578 void OnCertificateRequested(URLRequest* request,
8579 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448580 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178581 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448582 }
8583 int on_certificate_requested_count() {
8584 return on_certificate_requested_count_;
8585 }
8586 private:
8587 int on_certificate_requested_count_;
8588};
8589
8590} // namespace
8591
8592// TODO(davidben): Test the rest of the code. Specifically,
8593// - Filtering which certificates to select.
8594// - Sending a certificate back.
8595// - Getting a certificate request in an SSL renegotiation sending the
8596// HTTP request.
8597TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558598 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8599 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128600 ssl_config.client_cert_type =
8601 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558602 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8603 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228604 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448605 ASSERT_TRUE(test_server.Start());
8606
8607 SSLClientAuthTestDelegate d;
8608 {
danakj8522a25b2016-04-16 00:17:368609 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558610 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448611
[email protected]f7022f32014-08-21 16:32:198612 r->Start();
8613 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448614
[email protected]255620da2013-08-19 13:14:298615 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448616
8617 EXPECT_EQ(1, d.on_certificate_requested_count());
8618 EXPECT_FALSE(d.received_data_before_response());
8619 EXPECT_EQ(0, d.bytes_received());
8620
8621 // Send no certificate.
8622 // TODO(davidben): Get temporary client cert import (with keys) working on
8623 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548624 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448625
[email protected]255620da2013-08-19 13:14:298626 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448627
8628 EXPECT_EQ(1, d.response_started_count());
8629 EXPECT_FALSE(d.received_data_before_response());
8630 EXPECT_NE(0, d.bytes_received());
8631 }
8632}
8633
8634TEST_F(HTTPSRequestTest, ResumeTest) {
8635 // Test that we attempt a session resume when making two connections to the
8636 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228637 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448638 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228639 SpawnedTestServer test_server(
8640 SpawnedTestServer::TYPE_HTTPS,
8641 ssl_options,
8642 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448643 ASSERT_TRUE(test_server.Start());
8644
8645 SSLClientSocket::ClearSessionCache();
8646
8647 {
8648 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368649 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368650 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448651
[email protected]f7022f32014-08-21 16:32:198652 r->Start();
8653 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448654
[email protected]255620da2013-08-19 13:14:298655 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448656
8657 EXPECT_EQ(1, d.response_started_count());
8658 }
8659
8660 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8661 CloseAllConnections();
8662
8663 {
8664 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368665 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368666 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448667
[email protected]f7022f32014-08-21 16:32:198668 r->Start();
8669 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448670
[email protected]255620da2013-08-19 13:14:298671 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448672
8673 // The response will look like;
8674 // insert abc
8675 // lookup abc
8676 // insert xyz
8677 //
8678 // With a newline at the end which makes the split think that there are
8679 // four lines.
8680
8681 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298682 std::vector<std::string> lines = base::SplitString(
8683 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448684 ASSERT_EQ(4u, lines.size()) << d.data_received();
8685
8686 std::string session_id;
8687
8688 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298689 std::vector<std::string> parts = base::SplitString(
8690 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448691 ASSERT_EQ(2u, parts.size());
8692 if (i == 0) {
8693 EXPECT_EQ("insert", parts[0]);
8694 session_id = parts[1];
8695 } else {
8696 EXPECT_EQ("lookup", parts[0]);
8697 EXPECT_EQ(session_id, parts[1]);
8698 }
8699 }
8700 }
8701}
8702
Adam Langley32352ad2014-10-14 22:31:008703// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8704// the result of fetching "ssl-session-cache" from the test server, indicates
8705// that exactly two different sessions were inserted, with no lookups etc.
8706static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298707 std::vector<std::string> lines = base::SplitString(
8708 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008709 ASSERT_EQ(3u, lines.size()) << session_info;
8710
8711 std::string session_id;
8712 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298713 std::vector<std::string> parts = base::SplitString(
8714 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008715 ASSERT_EQ(2u, parts.size());
8716 EXPECT_EQ("insert", parts[0]);
8717 if (i == 0) {
8718 session_id = parts[1];
8719 } else {
8720 EXPECT_NE(session_id, parts[1]);
8721 }
8722 }
8723}
8724
[email protected]316c1e5e2012-09-12 15:17:448725TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8726 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8727 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228728 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448729 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228730 SpawnedTestServer test_server(
8731 SpawnedTestServer::TYPE_HTTPS,
8732 ssl_options,
8733 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448734 ASSERT_TRUE(test_server.Start());
8735
8736 SSLClientSocket::ClearSessionCache();
8737
8738 {
8739 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368740 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368741 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448742
[email protected]f7022f32014-08-21 16:32:198743 r->Start();
8744 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448745
[email protected]255620da2013-08-19 13:14:298746 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448747
8748 EXPECT_EQ(1, d.response_started_count());
8749 }
8750
8751 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8752 HttpNetworkSession::Params params;
8753 params.host_resolver = default_context_.host_resolver();
8754 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118755 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:208756 params.cert_transparency_verifier =
8757 default_context_.cert_transparency_verifier();
8758 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:448759 params.proxy_service = default_context_.proxy_service();
8760 params.ssl_config_service = default_context_.ssl_config_service();
8761 params.http_auth_handler_factory =
8762 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:448763 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448764
mmenkee65e7af2015-10-13 17:16:428765 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:368766 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428767 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448768
8769 default_context_.set_http_transaction_factory(cache.get());
8770
8771 {
8772 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368773 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368774 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448775
[email protected]f7022f32014-08-21 16:32:198776 r->Start();
8777 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448778
[email protected]255620da2013-08-19 13:14:298779 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448780
8781 // The response will look like;
8782 // insert abc
8783 // insert xyz
8784 //
8785 // With a newline at the end which makes the split think that there are
8786 // three lines.
8787
8788 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008789 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448790 }
8791}
8792
[email protected]48d2b7c52014-06-27 01:16:558793class HTTPSFallbackTest : public testing::Test {
8794 public:
Adam Langley32352ad2014-10-14 22:31:008795 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298796 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558797
8798 protected:
8799 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8800 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008801 context_.Init();
8802 delegate_.set_allow_certificate_errors(true);
8803
[email protected]48d2b7c52014-06-27 01:16:558804 SpawnedTestServer test_server(
8805 SpawnedTestServer::TYPE_HTTPS,
8806 ssl_options,
8807 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8808 ASSERT_TRUE(test_server.Start());
8809
tommycli59a63432015-11-06 00:10:558810 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8811 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558812 request_->Start();
8813
8814 base::RunLoop().Run();
8815 }
8816
8817 void ExpectConnection(int version) {
8818 EXPECT_EQ(1, delegate_.response_started_count());
8819 EXPECT_NE(0, delegate_.bytes_received());
8820 EXPECT_EQ(version, SSLConnectionStatusToVersion(
8821 request_->ssl_info().connection_status));
8822 EXPECT_TRUE(request_->ssl_info().connection_status &
8823 SSL_CONNECTION_VERSION_FALLBACK);
8824 }
8825
8826 void ExpectFailure(int error) {
8827 EXPECT_EQ(1, delegate_.response_started_count());
8828 EXPECT_FALSE(request_->status().is_success());
8829 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
8830 EXPECT_EQ(error, request_->status().error());
8831 }
8832
8833 private:
8834 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:478835 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:368836 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:558837};
8838
davidbenb127ca82015-06-15 19:05:428839// Tests the TLS 1.0 fallback doesn't happen.
8840TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558841 SpawnedTestServer::SSLOptions ssl_options(
8842 SpawnedTestServer::SSLOptions::CERT_OK);
8843 ssl_options.tls_intolerant =
8844 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8845
8846 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558847 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:428848}
8849
davidben5a312152016-06-27 22:11:478850// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:558851TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:428852 SpawnedTestServer::SSLOptions ssl_options(
8853 SpawnedTestServer::SSLOptions::CERT_OK);
8854 ssl_options.tls_intolerant =
8855 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8856
8857 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:558858 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8859}
8860
[email protected]a8fed1742013-12-27 02:14:248861class HTTPSSessionTest : public testing::Test {
8862 public:
8863 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598864 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248865
8866 default_context_.set_network_delegate(&default_network_delegate_);
8867 default_context_.set_cert_verifier(&cert_verifier_);
8868 default_context_.Init();
8869 }
dcheng67be2b1f2014-10-27 21:47:298870 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248871
8872 protected:
8873 MockCertVerifier cert_verifier_;
8874 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8875 TestURLRequestContext default_context_;
8876};
8877
8878// Tests that session resumption is not attempted if an invalid certificate
8879// is presented.
8880TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8881 SpawnedTestServer::SSLOptions ssl_options;
8882 ssl_options.record_resume = true;
8883 SpawnedTestServer test_server(
8884 SpawnedTestServer::TYPE_HTTPS,
8885 ssl_options,
8886 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8887 ASSERT_TRUE(test_server.Start());
8888
8889 SSLClientSocket::ClearSessionCache();
8890
8891 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598892 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248893 {
8894 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368895 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368896 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248897
[email protected]f7022f32014-08-21 16:32:198898 r->Start();
8899 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248900
8901 base::RunLoop().Run();
8902
8903 EXPECT_EQ(1, d.response_started_count());
8904 }
8905
8906 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8907 CloseAllConnections();
8908
8909 // Now change the certificate to be acceptable (so that the response is
8910 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598911 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248912 {
8913 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368914 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368915 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248916
[email protected]f7022f32014-08-21 16:32:198917 r->Start();
8918 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248919
8920 base::RunLoop().Run();
8921
8922 // The response will look like;
8923 // insert abc
8924 // insert xyz
8925 //
8926 // With a newline at the end which makes the split think that there are
8927 // three lines.
8928 //
8929 // If a session was presented (eg: a bug), then the response would look
8930 // like;
8931 // insert abc
8932 // lookup abc
8933 // insert xyz
8934
8935 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008936 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248937 }
8938}
8939
[email protected]dffe8242012-03-20 15:14:278940// This the fingerprint of the "Testing CA" certificate used by the testserver.
8941// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268942static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278943 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8944 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8945
[email protected]51523f52013-07-31 21:57:288946// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8947// testserver.
8948static const SHA256HashValue kOCSPTestCertSPKI = { {
8949 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8950 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8951 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8952 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8953} };
8954
[email protected]dffe8242012-03-20 15:14:278955// This is the policy OID contained in the certificates that testserver
8956// generates.
8957static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8958
8959class HTTPSOCSPTest : public HTTPSRequestTest {
8960 public:
8961 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098962 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088963 ev_test_policy_(
8964 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8965 kOCSPTestCertFingerprint,
8966 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028967 }
8968
dcheng67be2b1f2014-10-27 21:47:298969 void SetUp() override {
rsleevid6de8302016-06-21 01:33:208970 context_.SetCTPolicyEnforcer(
8971 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
8972 SetupContext();
[email protected]ef2bf422012-05-11 03:27:098973 context_.Init();
[email protected]dffe8242012-03-20 15:14:278974
[email protected]cba24642014-08-15 20:49:598975 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208976 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428977 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508978 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278979
svaldez2135be52016-04-20 16:34:538980#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:098981 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278982 EnsureNSSHttpIOInit();
8983#endif
8984 }
8985
dadrian612337a2016-07-20 22:36:588986 void DoConnectionWithDelegate(
8987 const SpawnedTestServer::SSLOptions& ssl_options,
8988 TestDelegate* delegate,
8989 SSLInfo* out_ssl_info) {
8990 // Always overwrite |out_ssl_info|.
8991 out_ssl_info->Reset();
8992
[email protected]ce7d0cbc2013-05-03 18:57:228993 SpawnedTestServer test_server(
8994 SpawnedTestServer::TYPE_HTTPS,
8995 ssl_options,
8996 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278997 ASSERT_TRUE(test_server.Start());
8998
dadrian612337a2016-07-20 22:36:588999 delegate->set_allow_certificate_errors(true);
9000 std::unique_ptr<URLRequest> r(context_.CreateRequest(
9001 test_server.GetURL("/"), DEFAULT_PRIORITY, delegate));
[email protected]f7022f32014-08-21 16:32:199002 r->Start();
[email protected]dffe8242012-03-20 15:14:279003
[email protected]255620da2013-08-19 13:14:299004 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:589005 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:279006
dadrian612337a2016-07-20 22:36:589007 *out_ssl_info = r->ssl_info();
9008 }
9009
9010 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
9011 CertStatus* out_cert_status) {
9012 // Always overwrite |out_cert_status|.
9013 *out_cert_status = 0;
9014
9015 TestDelegate d;
9016 SSLInfo ssl_info;
9017 ASSERT_NO_FATAL_FAILURE(
9018 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
9019
9020 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:279021 }
9022
dcheng67be2b1f2014-10-27 21:47:299023 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:539024#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:279025 ShutdownNSSHttpIO();
9026#endif
9027 }
9028
[email protected]a13234c2012-03-20 21:45:029029 protected:
rsleevid6de8302016-06-21 01:33:209030 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9031 public:
9032 AllowAnyCertCTPolicyEnforcer() = default;
9033 ~AllowAnyCertCTPolicyEnforcer() override = default;
9034
9035 ct::CertPolicyCompliance DoesConformToCertPolicy(
9036 X509Certificate* cert,
9037 const SCTList& verified_scts,
9038 const BoundNetLog& net_log) override {
9039 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9040 }
9041
9042 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9043 X509Certificate* cert,
9044 const ct::EVCertsWhitelist* ev_whitelist,
9045 const SCTList& verified_scts,
9046 const BoundNetLog& net_log) override {
9047 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9048 }
9049 };
[email protected]a13234c2012-03-20 21:45:029050 // SetupContext configures the URLRequestContext that will be used for making
9051 // connetions to testserver. This can be overridden in test subclasses for
9052 // different behaviour.
rsleevid6de8302016-06-21 01:33:209053 virtual void SetupContext() {
9054 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149055 true /* check for EV */, true /* online revocation checking */,
9056 false /* require rev. checking for local
9057 anchors */,
9058 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029059 }
9060
danakj8522a25b2016-04-16 00:17:369061 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099062 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369063 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279064};
9065
[email protected]a13234c2012-03-20 21:45:029066static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:019067#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:029068 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9069 // have that ability on other platforms.
9070 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9071#else
9072 return 0;
9073#endif
9074}
9075
[email protected]3a86a712013-07-30 07:16:209076// SystemSupportsHardFailRevocationChecking returns true iff the current
9077// operating system supports revocation checking and can distinguish between
9078// situations where a given certificate lacks any revocation information (eg:
9079// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9080// revocation information cannot be obtained (eg: the CRL was unreachable).
9081// If it does not, then tests which rely on 'hard fail' behaviour should be
9082// skipped.
9083static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539084#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209085 return true;
9086#else
9087 return false;
9088#endif
9089}
9090
[email protected]a13234c2012-03-20 21:45:029091// SystemUsesChromiumEVMetadata returns true iff the current operating system
9092// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9093// several tests are effected because our testing EV certificate won't be
9094// recognised as EV.
9095static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329096#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579097 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9098 return false;
[email protected]e1b2d732014-03-28 16:20:329099#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9100 // On OS X and Android, we use the system to tell us whether a certificate is
9101 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019102 return false;
9103#else
9104 return true;
9105#endif
9106}
9107
[email protected]b6f2de32012-08-17 04:35:089108static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339109#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029110 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9111 return false;
9112#else
9113 return true;
9114#endif
9115}
9116
davidbend1fb2f12014-11-08 02:51:009117static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339118#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039119 return true;
mathpc992e602015-10-21 20:34:039120#else
9121 return false;
9122#endif
davidbend1fb2f12014-11-08 02:51:009123}
9124
[email protected]dffe8242012-03-20 15:14:279125TEST_F(HTTPSOCSPTest, Valid) {
9126 if (!SystemSupportsOCSP()) {
9127 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9128 return;
9129 }
9130
[email protected]ce7d0cbc2013-05-03 18:57:229131 SpawnedTestServer::SSLOptions ssl_options(
9132 SpawnedTestServer::SSLOptions::CERT_AUTO);
9133 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279134
[email protected]924e9f92012-12-16 22:00:539135 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129136 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279137
9138 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9139
[email protected]a13234c2012-03-20 21:45:029140 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9141 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279142
9143 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9144}
9145
9146TEST_F(HTTPSOCSPTest, Revoked) {
9147 if (!SystemSupportsOCSP()) {
9148 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9149 return;
9150 }
9151
[email protected]ce7d0cbc2013-05-03 18:57:229152 SpawnedTestServer::SSLOptions ssl_options(
9153 SpawnedTestServer::SSLOptions::CERT_AUTO);
9154 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279155
9156 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129157 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279158
[email protected]a592c0432012-12-01 18:10:299159#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:279160 // Doesn't pass on OS X yet for reasons that need to be investigated.
9161 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9162#endif
9163 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9164 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9165}
9166
9167TEST_F(HTTPSOCSPTest, Invalid) {
9168 if (!SystemSupportsOCSP()) {
9169 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9170 return;
9171 }
9172
[email protected]ce7d0cbc2013-05-03 18:57:229173 SpawnedTestServer::SSLOptions ssl_options(
9174 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589175 ssl_options.ocsp_status =
9176 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:279177
[email protected]924e9f92012-12-16 22:00:539178 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129179 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279180
[email protected]a13234c2012-03-20 21:45:029181 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279182 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279183
9184 // Without a positive OCSP response, we shouldn't show the EV status.
9185 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9186 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9187}
[email protected]a13234c2012-03-20 21:45:029188
davidbend1fb2f12014-11-08 02:51:009189TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039190 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009191 LOG(WARNING)
9192 << "Skipping test because system doesn't support OCSP stapling";
9193 return;
9194 }
9195
9196 SpawnedTestServer::SSLOptions ssl_options(
9197 SpawnedTestServer::SSLOptions::CERT_AUTO);
9198 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9199 ssl_options.staple_ocsp_response = true;
9200 ssl_options.ocsp_server_unavailable = true;
9201
9202 CertStatus cert_status;
9203 DoConnection(ssl_options, &cert_status);
9204
9205 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9206
9207 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9208 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9209
9210 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9211}
9212
davidben6c3191b2014-11-21 22:38:049213// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489214#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049215#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9216#else
9217#define MAYBE_RevokedStapled RevokedStapled
9218#endif
9219TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039220 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009221 LOG(WARNING)
9222 << "Skipping test because system doesn't support OCSP stapling";
9223 return;
9224 }
9225
9226 SpawnedTestServer::SSLOptions ssl_options(
9227 SpawnedTestServer::SSLOptions::CERT_AUTO);
9228 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9229 ssl_options.staple_ocsp_response = true;
9230 ssl_options.ocsp_server_unavailable = true;
9231
9232 CertStatus cert_status;
9233 DoConnection(ssl_options, &cert_status);
9234
9235 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9236 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9237 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9238}
9239
dadrian612337a2016-07-20 22:36:589240static const struct OCSPVerifyTestData {
9241 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
9242 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
9243 OCSPVerifyResult::ResponseStatus response_status;
9244 bool has_revocation_status;
9245 OCSPRevocationStatus cert_status;
9246} kOCSPVerifyData[] = {
9247
9248 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9249 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9250 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9251 OCSPVerifyResult::PROVIDED,
9252 true,
9253 OCSPRevocationStatus::GOOD},
9254
9255 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9256 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9257 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9258 OCSPVerifyResult::INVALID_DATE,
9259 false,
9260 OCSPRevocationStatus::UNKNOWN},
9261
9262 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9263 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9264 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9265 OCSPVerifyResult::INVALID_DATE,
9266 false,
9267 OCSPRevocationStatus::UNKNOWN},
9268
9269 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9270 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9271 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9272 OCSPVerifyResult::INVALID_DATE,
9273 false,
9274 OCSPRevocationStatus::UNKNOWN},
9275
9276 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9277 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9278 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9279 OCSPVerifyResult::INVALID_DATE,
9280 false,
9281 OCSPRevocationStatus::UNKNOWN},
9282
9283 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
9284 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9285 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9286 OCSPVerifyResult::ERROR_RESPONSE,
9287 false,
9288 OCSPRevocationStatus::UNKNOWN},
9289
9290 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
9291 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9292 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9293 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
9294 false,
9295 OCSPRevocationStatus::UNKNOWN},
9296
9297 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
9298 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9299 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9300 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
9301 false,
9302 OCSPRevocationStatus::UNKNOWN},
9303
9304 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9305 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9306 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9307 OCSPVerifyResult::INVALID_DATE,
9308 false,
9309 OCSPRevocationStatus::UNKNOWN},
9310
9311 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9312 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9313 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9314 OCSPVerifyResult::PROVIDED,
9315 true,
9316 OCSPRevocationStatus::UNKNOWN},
9317
9318 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9319 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9320 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9321 OCSPVerifyResult::INVALID_DATE,
9322 false,
9323 OCSPRevocationStatus::UNKNOWN},
9324
9325 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9326 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9327 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9328 OCSPVerifyResult::INVALID_DATE,
9329 false,
9330 OCSPRevocationStatus::UNKNOWN},
9331
9332 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9333 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9334 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
9335 OCSPVerifyResult::BAD_PRODUCED_AT,
9336 false,
9337 OCSPRevocationStatus::UNKNOWN},
9338
9339 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9340 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9341 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9342 OCSPVerifyResult::BAD_PRODUCED_AT,
9343 false,
9344 OCSPRevocationStatus::UNKNOWN},
9345
9346 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9347 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9348 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9349 OCSPVerifyResult::BAD_PRODUCED_AT,
9350 false,
9351 OCSPRevocationStatus::UNKNOWN},
9352
9353 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9354 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9355 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9356 OCSPVerifyResult::PROVIDED,
9357 true,
9358 OCSPRevocationStatus::REVOKED},
9359
9360 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9361 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9362 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9363 OCSPVerifyResult::INVALID_DATE,
9364 false,
9365 OCSPRevocationStatus::UNKNOWN},
9366
9367 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9368 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9369 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9370 OCSPVerifyResult::INVALID_DATE,
9371 false,
9372 OCSPRevocationStatus::UNKNOWN},
9373
9374 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9375 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9376 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9377 OCSPVerifyResult::PROVIDED,
9378 true,
9379 OCSPRevocationStatus::GOOD},
9380
9381 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9382 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9383 {SpawnedTestServer::SSLOptions::OCSP_OK,
9384 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9385 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9386 OCSPVerifyResult::PROVIDED,
9387 true,
9388 OCSPRevocationStatus::GOOD},
9389
9390 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9391 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9392 {SpawnedTestServer::SSLOptions::OCSP_OK,
9393 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9394 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9395 OCSPVerifyResult::PROVIDED,
9396 true,
9397 OCSPRevocationStatus::GOOD},
9398
9399 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9400 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9401 {SpawnedTestServer::SSLOptions::OCSP_OK,
9402 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9403 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9404 OCSPVerifyResult::PROVIDED,
9405 true,
9406 OCSPRevocationStatus::GOOD},
9407
9408 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9409 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9410 {SpawnedTestServer::SSLOptions::OCSP_OK,
9411 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9412 {SpawnedTestServer::SSLOptions::OCSP_OK,
9413 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9414 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9415 OCSPVerifyResult::INVALID_DATE,
9416 false,
9417 OCSPRevocationStatus::UNKNOWN},
9418
9419 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9420 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9421 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9422 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9423 {SpawnedTestServer::SSLOptions::OCSP_OK,
9424 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9425 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9426 OCSPVerifyResult::PROVIDED,
9427 true,
9428 OCSPRevocationStatus::REVOKED},
9429
9430 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9431 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9432 {SpawnedTestServer::SSLOptions::OCSP_OK,
9433 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9434 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9435 OCSPVerifyResult::PROVIDED,
9436 true,
9437 OCSPRevocationStatus::UNKNOWN},
9438
9439 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9440 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9441 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9442 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9443 {SpawnedTestServer::SSLOptions::OCSP_OK,
9444 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9445 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9446 OCSPVerifyResult::PROVIDED,
9447 true,
9448 OCSPRevocationStatus::UNKNOWN},
9449
9450 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9451 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9452 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9453 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9454 false,
9455 OCSPRevocationStatus::UNKNOWN},
9456
9457 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9458 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9459 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9460 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9461 false,
9462 OCSPRevocationStatus::UNKNOWN},
9463
9464};
9465
9466class HTTPSOCSPVerifyTest
9467 : public HTTPSOCSPTest,
9468 public testing::WithParamInterface<OCSPVerifyTestData> {};
9469
9470TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
9471 SpawnedTestServer::SSLOptions ssl_options(
9472 SpawnedTestServer::SSLOptions::CERT_AUTO);
9473 OCSPVerifyTestData test = GetParam();
9474
9475 ssl_options.ocsp_responses = test.ocsp_responses;
9476 ssl_options.ocsp_produced = test.ocsp_produced;
9477 ssl_options.staple_ocsp_response = true;
9478
9479 SSLInfo ssl_info;
9480 OCSPErrorTestDelegate delegate;
9481 ASSERT_NO_FATAL_FAILURE(
9482 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
9483
9484 // The SSLInfo must be extracted from |delegate| on error, due to how
9485 // URLRequest caches certificate errors.
9486 if (delegate.have_certificate_errors()) {
9487 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
9488 ssl_info = delegate.ssl_info();
9489 }
9490
9491 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
9492
9493 if (test.has_revocation_status)
9494 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
9495}
9496
9497INSTANTIATE_TEST_CASE_P(OCSPVerify,
9498 HTTPSOCSPVerifyTest,
9499 testing::ValuesIn(kOCSPVerifyData));
9500
[email protected]3a86a712013-07-30 07:16:209501class HTTPSHardFailTest : public HTTPSOCSPTest {
9502 protected:
rsleevid6de8302016-06-21 01:33:209503 void SetupContext() override {
9504 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149505 false /* check for EV */, false /* online revocation checking */,
9506 true /* require rev. checking for local
9507 anchors */,
9508 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209509 }
9510};
9511
[email protected]3a86a712013-07-30 07:16:209512TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9513 if (!SystemSupportsOCSP()) {
9514 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9515 return;
9516 }
9517
9518 if (!SystemSupportsHardFailRevocationChecking()) {
9519 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9520 << "revocation checking";
9521 return;
9522 }
9523
9524 SpawnedTestServer::SSLOptions ssl_options(
9525 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589526 ssl_options.ocsp_status =
9527 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:209528
9529 CertStatus cert_status;
9530 DoConnection(ssl_options, &cert_status);
9531
9532 EXPECT_EQ(CERT_STATUS_REVOKED,
9533 cert_status & CERT_STATUS_REVOKED);
9534
9535 // Without a positive OCSP response, we shouldn't show the EV status.
9536 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9537}
9538
[email protected]a13234c2012-03-20 21:45:029539class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9540 protected:
rsleevid6de8302016-06-21 01:33:209541 void SetupContext() override {
9542 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149543 true /* check for EV */, false /* online revocation checking */,
9544 false /* require rev. checking for local
9545 anchors */,
9546 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029547 }
9548};
9549
9550TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9551 if (!SystemSupportsOCSP()) {
9552 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9553 return;
9554 }
9555
[email protected]ce7d0cbc2013-05-03 18:57:229556 SpawnedTestServer::SSLOptions ssl_options(
9557 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589558 ssl_options.ocsp_status =
9559 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029560 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9561
[email protected]924e9f92012-12-16 22:00:539562 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129563 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029564
9565 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9566 cert_status & CERT_STATUS_ALL_ERRORS);
9567
9568 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089569 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9570 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029571}
9572
[email protected]be0fff62013-08-29 23:37:489573TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9574 if (!SystemSupportsOCSP()) {
9575 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9576 return;
9577 }
9578
9579 SpawnedTestServer::SSLOptions ssl_options(
9580 SpawnedTestServer::SSLOptions::CERT_AUTO);
9581 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9582 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9583
9584 CertStatus cert_status;
9585 DoConnection(ssl_options, &cert_status);
9586
9587 // Currently only works for Windows. When using NSS or OS X, it's not
9588 // possible to determine whether the check failed because of actual
9589 // revocation or because there was an OCSP failure.
9590#if defined(OS_WIN)
9591 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9592#else
9593 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9594#endif
9595
9596 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9597 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9598 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9599}
9600
[email protected]a13234c2012-03-20 21:45:029601TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9602 if (!SystemSupportsOCSP()) {
9603 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9604 return;
9605 }
9606
[email protected]ce7d0cbc2013-05-03 18:57:229607 SpawnedTestServer::SSLOptions ssl_options(
9608 SpawnedTestServer::SSLOptions::CERT_AUTO);
9609 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029610 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9611
9612 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129613 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029614
9615 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9616
9617 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9618 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089619 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9620 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029621}
9622
9623TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9624 if (!SystemSupportsOCSP()) {
9625 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9626 return;
9627 }
9628
[email protected]ce7d0cbc2013-05-03 18:57:229629 SpawnedTestServer::SSLOptions ssl_options(
9630 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589631 ssl_options.ocsp_status =
9632 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029633 SSLConfigService::SetCRLSet(
9634 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9635
9636 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129637 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029638
9639 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9640 cert_status & CERT_STATUS_ALL_ERRORS);
9641
9642 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089643 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9644 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029645}
9646
[email protected]51523f52013-07-31 21:57:289647TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9648 if (!SystemSupportsOCSP()) {
9649 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9650 return;
9651 }
9652
9653 SpawnedTestServer::SSLOptions ssl_options(
9654 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589655 ssl_options.ocsp_status =
9656 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:289657 SSLConfigService::SetCRLSet(
9658 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9659 false, &kOCSPTestCertSPKI, "")));
9660
9661 CertStatus cert_status;
9662 DoConnection(ssl_options, &cert_status);
9663
9664 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9665 // revocation check for EV.
9666 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9667 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9668 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9669 EXPECT_FALSE(
9670 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9671}
9672
9673TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9674 if (!SystemSupportsOCSP()) {
9675 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9676 return;
9677 }
9678
[email protected]ce7d0cbc2013-05-03 18:57:229679 SpawnedTestServer::SSLOptions ssl_options(
9680 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589681 ssl_options.ocsp_status =
9682 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029683 SSLConfigService::SetCRLSet(
9684 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9685
[email protected]51523f52013-07-31 21:57:289686 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129687 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029688
[email protected]51523f52013-07-31 21:57:289689 // Even with a fresh CRLSet, we should still do online revocation checks when
9690 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9691 // test.
9692 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
9693 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029694
[email protected]51523f52013-07-31 21:57:289695 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029696 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289697 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029698}
9699
[email protected]b6f2de32012-08-17 04:35:089700TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9701 // Test that when EV verification is requested, but online revocation
9702 // checking is disabled, and the leaf certificate is not in fact EV, that
9703 // no revocation checking actually happens.
9704 if (!SystemSupportsOCSP()) {
9705 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9706 return;
9707 }
9708
9709 // Unmark the certificate's OID as EV, which should disable revocation
9710 // checking (as per the user preference)
9711 ev_test_policy_.reset();
9712
[email protected]ce7d0cbc2013-05-03 18:57:229713 SpawnedTestServer::SSLOptions ssl_options(
9714 SpawnedTestServer::SSLOptions::CERT_AUTO);
9715 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089716 SSLConfigService::SetCRLSet(
9717 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9718
9719 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129720 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089721
9722 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9723
9724 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9725 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9726}
9727
[email protected]a13234c2012-03-20 21:45:029728class HTTPSCRLSetTest : public HTTPSOCSPTest {
9729 protected:
rsleevid6de8302016-06-21 01:33:209730 void SetupContext() override {
9731 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149732 false /* check for EV */, false /* online revocation checking */,
9733 false /* require rev. checking for local
9734 anchors */,
9735 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029736 }
9737};
9738
9739TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229740 SpawnedTestServer::SSLOptions ssl_options(
9741 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589742 ssl_options.ocsp_status =
9743 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029744 SSLConfigService::SetCRLSet(
9745 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9746
[email protected]924e9f92012-12-16 22:00:539747 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129748 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029749
9750 // If we're not trying EV verification then, even if the CRLSet has expired,
9751 // we don't fall back to online revocation checks.
9752 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9753 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9754 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9755}
[email protected]51523f52013-07-31 21:57:289756
9757TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309758#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289759 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9760 return;
9761#endif
9762
9763 SpawnedTestServer::SSLOptions ssl_options(
9764 SpawnedTestServer::SSLOptions::CERT_AUTO);
9765 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9766 ssl_options.cert_serial = 10;
9767 SSLConfigService::SetCRLSet(
9768 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9769 false, &kOCSPTestCertSPKI, "\x0a")));
9770
9771 CertStatus cert_status = 0;
9772 DoConnection(ssl_options, &cert_status);
9773
9774 // If the certificate is recorded as revoked in the CRLSet, that should be
9775 // reflected without online revocation checking.
9776 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9777 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9778 EXPECT_FALSE(
9779 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9780}
[email protected]316c1e5e2012-09-12 15:17:449781#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279782
mmenke9f2ec60c2015-06-01 20:59:479783#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9784// These tests aren't passing on Android. Either the RemoteTestServer isn't
9785// starting up successfully, or it can't access the test files.
9786// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319787class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119788 public:
[email protected]d9fca99a2012-02-24 16:16:209789 URLRequestTestFTP()
mmenke9f2ec60c2015-06-01 20:59:479790 : ftp_transaction_factory_(&host_resolver_),
tommycli59a63432015-11-06 00:10:559791 ftp_test_server_(SpawnedTestServer::TYPE_FTP,
9792 SpawnedTestServer::kLocalhost,
9793 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479794 // Can't use |default_context_|'s HostResolver to set up the
9795 // FTPTransactionFactory because it hasn't been created yet.
9796 default_context_.set_host_resolver(&host_resolver_);
9797 }
9798
9799 // URLRequestTest interface:
9800 void SetUpFactory() override {
9801 // Add FTP support to the default URLRequestContext.
9802 job_factory_impl_->SetProtocolHandler(
svaldez5d58c9e2015-08-24 21:36:209803 "ftp",
danakj8522a25b2016-04-16 00:17:369804 base::WrapUnique(new FtpProtocolHandler(&ftp_transaction_factory_)));
mmenke9f2ec60c2015-06-01 20:59:479805 }
9806
9807 std::string GetTestFileContents() {
9808 base::FilePath path;
9809 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9810 path = path.Append(kTestFilePath);
9811 path = path.AppendASCII(kFtpTestFile);
9812 std::string contents;
9813 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9814 return contents;
[email protected]95409e12010-08-17 20:07:119815 }
9816
[email protected]b89ca032009-08-31 21:41:319817 protected:
mmenke9f2ec60c2015-06-01 20:59:479818 MockHostResolver host_resolver_;
9819 FtpNetworkLayer ftp_transaction_factory_;
9820
tommycli59a63432015-11-06 00:10:559821 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319822};
9823
[email protected]d2a133182012-08-05 16:44:089824// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099825TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089826 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089827
9828 TestDelegate d;
9829 {
danakj8522a25b2016-04-16 00:17:369830 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:369831 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199832 r->Start();
9833 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089834
[email protected]255620da2013-08-19 13:14:299835 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089836
[email protected]f7022f32014-08-21 16:32:199837 EXPECT_FALSE(r->is_pending());
9838 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
robpercival214763f2016-07-01 23:27:019839 EXPECT_THAT(r->status().error(), IsError(ERR_UNSAFE_PORT));
[email protected]d2a133182012-08-05 16:44:089840 }
9841}
9842
mmenke9f2ec60c2015-06-01 20:59:479843TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559844 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119845
[email protected]a25e90e2009-09-09 17:05:379846 TestDelegate d;
9847 {
danakj8522a25b2016-04-16 00:17:369848 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559849 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199850 r->Start();
9851 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379852
[email protected]255620da2013-08-19 13:14:299853 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379854
[email protected]f7022f32014-08-21 16:32:199855 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379856 EXPECT_EQ(1, d.response_started_count());
9857 EXPECT_FALSE(d.received_data_before_response());
9858 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559859 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199860 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559861 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199862 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379863 }
9864}
9865
mmenke9f2ec60c2015-06-01 20:59:479866TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559867 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119868
[email protected]dd265012009-01-08 20:45:279869 TestDelegate d;
9870 {
danakj8522a25b2016-04-16 00:17:369871 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559872 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199873 r->Start();
9874 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279875
[email protected]255620da2013-08-19 13:14:299876 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279877
[email protected]f7022f32014-08-21 16:32:199878 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279879 EXPECT_EQ(1, d.response_started_count());
9880 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479881 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559882 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199883 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559884 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199885 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279886 }
9887}
9888
mmenke9f2ec60c2015-06-01 20:59:479889TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559890 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119891
[email protected]dd265012009-01-08 20:45:279892 TestDelegate d;
9893 {
danakj8522a25b2016-04-16 00:17:369894 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559895 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9896 "chrome"),
9897 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199898 r->Start();
9899 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279900
[email protected]255620da2013-08-19 13:14:299901 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279902
[email protected]f7022f32014-08-21 16:32:199903 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479904 EXPECT_EQ(1, d.response_started_count());
9905 EXPECT_FALSE(d.received_data_before_response());
9906 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559907 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199908 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559909 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199910 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259911
9912 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199913 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259914 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:279915 }
9916}
9917
mmenke9f2ec60c2015-06-01 20:59:479918TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:559919 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119920
[email protected]dd265012009-01-08 20:45:279921 TestDelegate d;
9922 {
danakj8522a25b2016-04-16 00:17:369923 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559924 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9925 "wrong_password"),
davidben151423e2015-03-23 18:48:369926 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199927 r->Start();
9928 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279929
[email protected]255620da2013-08-19 13:14:299930 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279931
[email protected]f7022f32014-08-21 16:32:199932 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279933 EXPECT_EQ(1, d.response_started_count());
9934 EXPECT_FALSE(d.received_data_before_response());
9935 EXPECT_EQ(d.bytes_received(), 0);
9936 }
9937}
9938
mmenke9f2ec60c2015-06-01 20:59:479939TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:559940 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119941
[email protected]8b8a197d2009-08-26 15:57:589942 TestDelegate d;
9943 // Set correct login credentials. The delegate will be asked for them when
9944 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589945 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589946 {
danakj8522a25b2016-04-16 00:17:369947 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559948 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9949 "wrong_password"),
davidben151423e2015-03-23 18:48:369950 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199951 r->Start();
9952 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589953
[email protected]255620da2013-08-19 13:14:299954 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:589955
[email protected]f7022f32014-08-21 16:32:199956 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589957 EXPECT_EQ(1, d.response_started_count());
9958 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479959 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:589960 }
9961}
9962
mmenke9f2ec60c2015-06-01 20:59:479963TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:559964 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119965
[email protected]dd265012009-01-08 20:45:279966 TestDelegate d;
9967 {
danakj8522a25b2016-04-16 00:17:369968 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559969 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9970 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479971 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199972 r->Start();
9973 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279974
[email protected]255620da2013-08-19 13:14:299975 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279976
[email protected]f7022f32014-08-21 16:32:199977 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279978 EXPECT_EQ(1, d.response_started_count());
9979 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479980 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:279981 }
9982}
[email protected]8b8a197d2009-08-26 15:57:589983
mmenke9f2ec60c2015-06-01 20:59:479984TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:559985 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119986
[email protected]8b8a197d2009-08-26 15:57:589987 TestDelegate d;
9988 // Set correct login credentials. The delegate will be asked for them when
9989 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:589990 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:589991 {
danakj8522a25b2016-04-16 00:17:369992 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559993 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
9994 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:479995 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199996 r->Start();
9997 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:589998
[email protected]255620da2013-08-19 13:14:299999 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810000
[email protected]f7022f32014-08-21 16:32:1910001 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810002 EXPECT_EQ(1, d.response_started_count());
10003 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710004 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810005 }
10006}
[email protected]60a3df52009-09-22 16:13:2410007
mmenke9f2ec60c2015-06-01 20:59:4710008TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510009 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110010
danakj8522a25b2016-04-16 00:17:3610011 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410012 {
10013 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610014 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510015 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10016 "chrome"),
10017 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910018 r->Start();
10019 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410020
[email protected]255620da2013-08-19 13:14:2910021 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410022
[email protected]f7022f32014-08-21 16:32:1910023 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410024 EXPECT_EQ(1, d->response_started_count());
10025 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710026 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410027 }
10028
10029 d.reset(new TestDelegate);
10030 {
10031 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610032 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510033 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910034 r->Start();
10035 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410036
[email protected]255620da2013-08-19 13:14:2910037 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410038
[email protected]f7022f32014-08-21 16:32:1910039 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410040 EXPECT_EQ(1, d->response_started_count());
10041 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710042 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410043 }
10044}
10045
mmenke9f2ec60c2015-06-01 20:59:4710046TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510047 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110048
danakj8522a25b2016-04-16 00:17:3610049 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410050 // Set correct login credentials. The delegate will be asked for them when
10051 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810052 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410053 {
danakj8522a25b2016-04-16 00:17:3610054 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510055 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10056 "wrong_password"),
davidben151423e2015-03-23 18:48:3610057 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910058 r->Start();
10059 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410060
[email protected]255620da2013-08-19 13:14:2910061 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410062
[email protected]f7022f32014-08-21 16:32:1910063 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410064 EXPECT_EQ(1, d->response_started_count());
10065 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710066 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410067 }
10068
10069 // Use a new delegate without explicit credentials. The cached ones should be
10070 // used.
10071 d.reset(new TestDelegate);
10072 {
10073 // Don't pass wrong credentials in the URL, they would override valid cached
10074 // ones.
danakj8522a25b2016-04-16 00:17:3610075 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510076 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910077 r->Start();
10078 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410079
[email protected]255620da2013-08-19 13:14:2910080 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410081
[email protected]f7022f32014-08-21 16:32:1910082 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410083 EXPECT_EQ(1, d->response_started_count());
10084 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710085 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410086 }
10087}
ricea3a1c71f2016-06-17 10:05:2610088
10089TEST_F(URLRequestTestFTP, RawBodyBytes) {
10090 ASSERT_TRUE(ftp_test_server_.Start());
10091
10092 TestDelegate d;
10093 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10094 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10095 req->Start();
10096 base::RunLoop().Run();
10097
10098 EXPECT_EQ(6, req->GetRawBodyBytes());
10099}
10100
[email protected]316c1e5e2012-09-12 15:17:4410101#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110102
ttuttlec0c828492015-05-15 01:25:5510103TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10104 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610105 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510106 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10107
10108 EXPECT_FALSE(req->response_info().network_accessed);
10109
10110 req->Start();
10111 base::RunLoop().Run();
10112
10113 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10114 EXPECT_FALSE(req->response_info().network_accessed);
10115}
10116
10117TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10118 MockHostResolver host_resolver;
10119 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10120 TestURLRequestContext context(true);
10121 context.set_network_delegate(&network_delegate);
10122 context.set_host_resolver(&host_resolver);
10123 host_resolver.rules()->AddSimulatedFailure("*");
10124 context.Init();
10125
10126 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610127 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510128 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10129
10130 EXPECT_FALSE(req->response_info().network_accessed);
10131
10132 req->Start();
10133 base::RunLoop().Run();
10134 EXPECT_TRUE(req->response_info().network_accessed);
10135}
10136
mmenkeed0498b2015-12-08 23:20:4210137// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210138// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210139TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210140 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610141 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210142 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10143
danakj8522a25b2016-04-16 00:17:3610144 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210145 req.get(), &default_network_delegate_,
10146 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210147 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10148 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210149
10150 req->Start();
10151 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210152 base::RunLoop().RunUntilIdle();
10153 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
10154 EXPECT_EQ(0, d.received_redirect_count());
10155}
10156
[email protected]7461a402011-03-24 23:19:5110157} // namespace net