blob: c87ac7a720e16945731b55df007744f1d393f77a [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"
[email protected]6e7845ae2013-03-29 21:48:1164#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2465#include "net/cert/mock_cert_verifier.h"
eranmdcec9632016-10-10 14:16:1066#include "net/cert/signed_certificate_timestamp_and_status.h"
[email protected]6e7845ae2013-03-29 21:48:1167#include "net/cert/test_root_certs.h"
eromaned744f32015-04-09 06:35:4968#include "net/cert_net/nss_ocsp.h"
[email protected]aa84a7e2012-03-15 21:29:0669#include "net/cookies/cookie_monster.h"
70#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5271#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5372#include "net/dns/mock_host_resolver.h"
[email protected]b7572ea2013-11-26 20:16:3873#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5274#include "net/http/http_cache.h"
75#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1976#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2577#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2178#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0079#include "net/http/http_util.h"
mikecirone8b85c432016-09-08 19:11:0080#include "net/log/net_log_event_type.h"
mikecironef22f9812016-10-04 03:40:1981#include "net/log/net_log_source.h"
vishal.b62985ca92015-04-17 08:45:5182#include "net/log/test_net_log.h"
mmenke43758e62015-05-04 21:09:4683#include "net/log/test_net_log_entry.h"
84#include "net/log/test_net_log_util.h"
tbansalca83c002016-04-28 20:56:2885#include "net/nqe/external_estimate_provider.h"
tbansal2ecbbc72016-10-06 17:15:4786#include "net/proxy/proxy_server.h"
[email protected]63de95b2008-12-10 04:11:2787#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1988#include "net/socket/ssl_client_socket.h"
nharperb7441ef2016-01-25 23:54:1489#include "net/ssl/channel_id_service.h"
90#include "net/ssl/default_channel_id_store.h"
[email protected]536fd0b2013-03-14 17:41:5791#include "net/ssl/ssl_connection_status_flags.h"
tommycli59a63432015-11-06 00:10:5592#include "net/ssl/ssl_server_config.h"
nharperb7441ef2016-01-25 23:54:1493#include "net/ssl/token_binding.h"
[email protected]6e7845ae2013-03-29 21:48:1194#include "net/test/cert_test_util.h"
estarkcd39c11f2015-10-19 19:46:3695#include "net/test/embedded_test_server/embedded_test_server.h"
96#include "net/test/embedded_test_server/http_request.h"
97#include "net/test/embedded_test_server/http_response.h"
robpercival214763f2016-07-01 23:27:0198#include "net/test/gtest_util.h"
[email protected]89b32522013-05-07 20:04:2199#include "net/test/spawned_test_server/spawned_test_server.h"
rsleevia69c79a2016-06-22 03:28:43100#include "net/test/test_data_directory.h"
mmenkefb18c772015-09-30 22:22:50101#include "net/test/url_request/url_request_failed_job.h"
[email protected]e0f35c92013-05-08 16:04:34102#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:43103#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:52104#include "net/url_request/url_request.h"
mmenkefb18c772015-09-30 22:22:50105#include "net/url_request/url_request_filter.h"
[email protected]bcb84f8b2009-08-31 16:20:14106#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:50107#include "net/url_request/url_request_intercepting_job_factory.h"
108#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:49109#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:51110#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:47111#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:44112#include "net/url_request/url_request_test_util.h"
robpercival214763f2016-07-01 23:27:01113#include "testing/gmock/include/gmock/gmock.h"
initial.commit586acc5fe2008-07-26 22:42:52114#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:15115#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:52116
[email protected]02494ec2014-05-07 15:05:29117#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:55118#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:29119#include "net/url_request/file_protocol_handler.h"
120#include "net/url_request/url_request_file_dir_job.h"
121#endif
122
mmenke9f2ec60c2015-06-01 20:59:47123#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
124#include "net/ftp/ftp_network_layer.h"
[email protected]02494ec2014-05-07 15:05:29125#include "net/url_request/ftp_protocol_handler.h"
126#endif
127
[email protected]dffe8242012-03-20 15:14:27128#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:48129#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:56130#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:27131#endif
132
robpercival214763f2016-07-01 23:27:01133using net::test::IsError;
134using net::test::IsOk;
135
[email protected]ad65a3e2013-12-25 18:18:01136using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33137using base::Time;
halton.huoe4e45742014-12-08 07:55:46138using std::string;
[email protected]e1acf6f2008-10-27 20:43:33139
[email protected]7461a402011-03-24 23:19:51140namespace net {
141
initial.commit586acc5fe2008-07-26 22:42:52142namespace {
143
[email protected]42cba2fb2013-03-29 19:58:57144const base::string16 kChrome(ASCIIToUTF16("chrome"));
145const base::string16 kSecret(ASCIIToUTF16("secret"));
146const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44147
mmenke9f2ec60c2015-06-01 20:59:47148const base::FilePath::CharType kTestFilePath[] =
149 FILE_PATH_LITERAL("net/data/url_request_unittest");
150
151#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
152// Test file used in most FTP tests.
153const char kFtpTestFile[] = "BullRunSpeech.txt";
154#endif
155
[email protected]2bba3252013-04-08 19:50:59156// Tests load timing information in the case a fresh connection was used, with
157// no proxy.
[email protected]cba24642014-08-15 20:49:59158void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25159 int connect_timing_flags) {
160 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19161 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25162
163 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
164 EXPECT_FALSE(load_timing_info.request_start.is_null());
165
166 EXPECT_LE(load_timing_info.request_start,
167 load_timing_info.connect_timing.connect_start);
168 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
169 connect_timing_flags);
170 EXPECT_LE(load_timing_info.connect_timing.connect_end,
171 load_timing_info.send_start);
172 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
173 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
174
[email protected]58e32bb2013-01-21 18:23:25175 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
176 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
177}
178
[email protected]2bba3252013-04-08 19:50:59179// Same as above, but with proxy times.
180void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59181 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59182 int connect_timing_flags) {
183 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19184 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59185
186 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
187 EXPECT_FALSE(load_timing_info.request_start.is_null());
188
189 EXPECT_LE(load_timing_info.request_start,
190 load_timing_info.proxy_resolve_start);
191 EXPECT_LE(load_timing_info.proxy_resolve_start,
192 load_timing_info.proxy_resolve_end);
193 EXPECT_LE(load_timing_info.proxy_resolve_end,
194 load_timing_info.connect_timing.connect_start);
195 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
196 connect_timing_flags);
197 EXPECT_LE(load_timing_info.connect_timing.connect_end,
198 load_timing_info.send_start);
199 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
200 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
201}
202
203// Same as above, but with a reused socket and proxy times.
204void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59205 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59206 EXPECT_TRUE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19207 EXPECT_NE(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59208
209 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
210 EXPECT_FALSE(load_timing_info.request_start.is_null());
211
212 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
213
214 EXPECT_LE(load_timing_info.request_start,
215 load_timing_info.proxy_resolve_start);
216 EXPECT_LE(load_timing_info.proxy_resolve_start,
217 load_timing_info.proxy_resolve_end);
218 EXPECT_LE(load_timing_info.proxy_resolve_end,
219 load_timing_info.send_start);
220 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
221 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
222}
223
xunjielia6888202015-04-14 21:34:25224#if !defined(DISABLE_FILE_SUPPORT)
[email protected]3b23a222013-05-15 21:33:25225// Tests load timing information in the case of a cache hit, when no cache
226// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17227base::StringPiece TestNetResourceProvider(int key) {
228 return "header";
229}
230
231void FillBuffer(char* buffer, size_t len) {
232 static bool called = false;
233 if (!called) {
234 called = true;
235 int seed = static_cast<int>(Time::Now().ToInternalValue());
236 srand(seed);
237 }
238
239 for (size_t i = 0; i < len; i++) {
240 buffer[i] = static_cast<char>(rand());
241 if (!buffer[i])
242 buffer[i] = 'g';
243 }
244}
xunjielia6888202015-04-14 21:34:25245#endif
[email protected]e3a85452013-11-14 01:46:17246
[email protected]3b23a222013-05-15 21:33:25247void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59248 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25249 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19250 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25251
252 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
253 EXPECT_FALSE(load_timing_info.request_start.is_null());
254
255 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
256 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
257 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
258 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
259
260 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
261 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
262}
263
mmenke9f2ec60c2015-06-01 20:59:47264#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
[email protected]3b23a222013-05-15 21:33:25265// Tests load timing in the case that there is no HTTP response. This can be
266// used to test in the case of errors or non-HTTP requests.
267void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59268 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25269 EXPECT_FALSE(load_timing_info.socket_reused);
mikecironef22f9812016-10-04 03:40:19270 EXPECT_EQ(NetLogSource::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25271
272 // Only the request times should be non-null.
273 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
274 EXPECT_FALSE(load_timing_info.request_start.is_null());
275
276 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
277
278 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
279 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
280 EXPECT_TRUE(load_timing_info.send_start.is_null());
281 EXPECT_TRUE(load_timing_info.send_end.is_null());
282 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
283}
xunjielia6888202015-04-14 21:34:25284#endif
[email protected]58e32bb2013-01-21 18:23:25285
mmenkefb18c772015-09-30 22:22:50286// Test power monitor source that can simulate entering suspend mode. Can't use
287// the one in base/ because it insists on bringing its own MessageLoop.
288class TestPowerMonitorSource : public base::PowerMonitorSource {
289 public:
290 TestPowerMonitorSource() {}
291 ~TestPowerMonitorSource() override {}
292
293 void Suspend() { ProcessPowerEvent(SUSPEND_EVENT); }
294
295 void Resume() { ProcessPowerEvent(RESUME_EVENT); }
296
297 bool IsOnBatteryPowerImpl() override { return false; }
298
299 private:
300 DISALLOW_COPY_AND_ASSIGN(TestPowerMonitorSource);
301};
302
mmenkeed0498b2015-12-08 23:20:42303// Job that allows monitoring of its priority.
304class PriorityMonitoringURLRequestJob : public URLRequestTestJob {
305 public:
306 // The latest priority of the job is always written to |request_priority_|.
307 PriorityMonitoringURLRequestJob(URLRequest* request,
308 NetworkDelegate* network_delegate,
309 RequestPriority* request_priority)
310 : URLRequestTestJob(request, network_delegate),
311 request_priority_(request_priority) {
312 *request_priority_ = DEFAULT_PRIORITY;
313 }
314
315 void SetPriority(RequestPriority priority) override {
316 *request_priority_ = priority;
317 URLRequestTestJob::SetPriority(priority);
318 }
319
320 private:
321 RequestPriority* const request_priority_;
322};
323
[email protected]71c64f62008-11-15 04:36:51324// Do a case-insensitive search through |haystack| for |needle|.
325bool ContainsString(const std::string& haystack, const char* needle) {
brettwa2027fb2015-07-14 02:24:50326 std::string::const_iterator it = std::search(
327 haystack.begin(), haystack.end(), needle, needle + strlen(needle),
328 base::CaseInsensitiveCompareASCII<char>());
[email protected]71c64f62008-11-15 04:36:51329 return it != haystack.end();
330}
331
danakj8522a25b2016-04-16 00:17:36332std::unique_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
333 std::unique_ptr<UploadElementReader> reader(
[email protected]f288ef02012-12-15 20:28:28334 new UploadBytesElementReader(data, strlen(data)));
dchengc7eeda422015-12-26 03:56:48335 return ElementsUploadDataStream::CreateWithReader(std::move(reader), 0);
[email protected]195e77d2009-07-23 19:10:23336}
337
[email protected]96adadb2010-08-28 01:16:17338// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51339void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17340 // -1 means unknown. 0 means no encryption.
341 EXPECT_GT(ssl_info.security_bits, 0);
342
343 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
avibf0746c2015-12-09 19:53:14344 uint16_t cipher_suite =
345 SSLConnectionStatusToCipherSuite(ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29346 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17347}
348
[email protected]79e1fd62013-06-20 06:50:04349void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
350 const GURL& host_url) {
351 std::string sent_value;
352
353 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
354 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
355
356 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
357 EXPECT_EQ("keep-alive", sent_value);
358}
359
[email protected]dc5a5cf2012-09-26 02:49:30360// A network delegate that allows the user to choose a subset of request stages
361// to block in. When blocking, the delegate can do one of the following:
362// * synchronously return a pre-specified error code, or
363// * asynchronously return that value via an automatically called callback,
364// or
365// * block and wait for the user to do a callback.
366// Additionally, the user may also specify a redirect URL -- then each request
367// with the current URL different from the redirect target will be redirected
368// to that target, in the on-before-URL-request stage, independent of whether
369// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12370class BlockingNetworkDelegate : public TestNetworkDelegate {
371 public:
[email protected]dc5a5cf2012-09-26 02:49:30372 // Stages in which the delegate can block.
373 enum Stage {
[email protected]9045b8822012-01-13 20:35:35374 NOT_BLOCKED = 0,
375 ON_BEFORE_URL_REQUEST = 1 << 0,
376 ON_BEFORE_SEND_HEADERS = 1 << 1,
377 ON_HEADERS_RECEIVED = 1 << 2,
378 ON_AUTH_REQUIRED = 1 << 3
379 };
380
[email protected]dc5a5cf2012-09-26 02:49:30381 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59382 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30383 enum BlockMode {
384 SYNCHRONOUS, // No callback, returns specified return values.
385 AUTO_CALLBACK, // |this| posts a task to run the callback using the
386 // specified return codes.
387 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
388 // |auth_retval_| are ignored. In every blocking stage the
389 // message loop is quit.
390 };
391
392 // Creates a delegate which does not block at all.
393 explicit BlockingNetworkDelegate(BlockMode block_mode);
394
395 // For users to trigger a callback returning |response|.
396 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
397 // Only call if |block_mode_| == USER_CALLBACK.
398 void DoCallback(int response);
399 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
400
401 // Setters.
402 void set_retval(int retval) {
403 ASSERT_NE(USER_CALLBACK, block_mode_);
404 ASSERT_NE(ERR_IO_PENDING, retval);
405 ASSERT_NE(OK, retval);
406 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35407 }
408
[email protected]dc5a5cf2012-09-26 02:49:30409 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
410 // |auth_credentials_| will be passed with the response.
411 void set_auth_retval(AuthRequiredResponse auth_retval) {
412 ASSERT_NE(USER_CALLBACK, block_mode_);
413 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
414 auth_retval_ = auth_retval;
415 }
416 void set_auth_credentials(const AuthCredentials& auth_credentials) {
417 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35418 }
419
[email protected]dc5a5cf2012-09-26 02:49:30420 void set_redirect_url(const GURL& url) {
421 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35422 }
423
[email protected]dc5a5cf2012-09-26 02:49:30424 void set_block_on(int block_on) {
425 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35426 }
427
[email protected]dc5a5cf2012-09-26 02:49:30428 // Allows the user to check in which state did we block.
429 Stage stage_blocked_for_callback() const {
430 EXPECT_EQ(USER_CALLBACK, block_mode_);
431 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35432 }
433
434 private:
[email protected]dc5a5cf2012-09-26 02:49:30435 void RunCallback(int response, const CompletionCallback& callback);
436 void RunAuthCallback(AuthRequiredResponse response,
437 const AuthCallback& callback);
438
[email protected]9045b8822012-01-13 20:35:35439 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20440 int OnBeforeURLRequest(URLRequest* request,
441 const CompletionCallback& callback,
442 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35443
ryansturm2343cb62016-06-15 01:09:00444 int OnBeforeStartTransaction(URLRequest* request,
445 const CompletionCallback& callback,
446 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35447
dchengb03027d2014-10-21 12:00:20448 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35449 URLRequest* request,
450 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32451 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16452 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13453 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35454
dchengb03027d2014-10-21 12:00:20455 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35456 URLRequest* request,
457 const AuthChallengeInfo& auth_info,
458 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13459 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35460
[email protected]dc5a5cf2012-09-26 02:49:30461 // Resets the callbacks and |stage_blocked_for_callback_|.
462 void Reset();
[email protected]9045b8822012-01-13 20:35:35463
[email protected]dc5a5cf2012-09-26 02:49:30464 // Checks whether we should block in |stage|. If yes, returns an error code
465 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
466 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
467
468 // Configuration parameters, can be adjusted by public methods:
469 const BlockMode block_mode_;
470
471 // Values returned on blocking stages when mode is SYNCHRONOUS or
472 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
473 int retval_; // To be returned in non-auth stages.
474 AuthRequiredResponse auth_retval_;
475
[email protected]5f714132014-03-26 10:41:16476 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30477 int block_on_; // Bit mask: in which stages to block.
478
479 // |auth_credentials_| will be copied to |*target_auth_credential_| on
480 // callback.
481 AuthCredentials auth_credentials_;
482 AuthCredentials* target_auth_credentials_;
483
484 // Internal variables, not set by not the user:
485 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
486 // USER_CALLBACK).
487 Stage stage_blocked_for_callback_;
488
489 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35490 CompletionCallback callback_;
491 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30492
493 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
494
495 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35496};
497
[email protected]dc5a5cf2012-09-26 02:49:30498BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
499 : block_mode_(block_mode),
500 retval_(OK),
501 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
502 block_on_(0),
503 target_auth_credentials_(NULL),
504 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32505 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30506}
507
508void BlockingNetworkDelegate::DoCallback(int response) {
509 ASSERT_EQ(USER_CALLBACK, block_mode_);
510 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
511 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
512 CompletionCallback callback = callback_;
513 Reset();
514 RunCallback(response, callback);
515}
516
517void BlockingNetworkDelegate::DoAuthCallback(
518 NetworkDelegate::AuthRequiredResponse response) {
519 ASSERT_EQ(USER_CALLBACK, block_mode_);
520 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
521 AuthCallback auth_callback = auth_callback_;
522 Reset();
523 RunAuthCallback(response, auth_callback);
524}
525
526void BlockingNetworkDelegate::RunCallback(int response,
527 const CompletionCallback& callback) {
528 callback.Run(response);
529}
530
531void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
532 const AuthCallback& callback) {
533 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
534 ASSERT_TRUE(target_auth_credentials_ != NULL);
535 *target_auth_credentials_ = auth_credentials_;
536 }
537 callback.Run(response);
538}
539
540int BlockingNetworkDelegate::OnBeforeURLRequest(
541 URLRequest* request,
542 const CompletionCallback& callback,
543 GURL* new_url) {
544 if (redirect_url_ == request->url())
545 return OK; // We've already seen this request and redirected elsewhere.
546
547 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
548
549 if (!redirect_url_.is_empty())
550 *new_url = redirect_url_;
551
552 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
553}
554
ryansturm2343cb62016-06-15 01:09:00555int BlockingNetworkDelegate::OnBeforeStartTransaction(
[email protected]dc5a5cf2012-09-26 02:49:30556 URLRequest* request,
557 const CompletionCallback& callback,
558 HttpRequestHeaders* headers) {
ryansturm2343cb62016-06-15 01:09:00559 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]dc5a5cf2012-09-26 02:49:30560
561 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
562}
563
564int BlockingNetworkDelegate::OnHeadersReceived(
565 URLRequest* request,
566 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32567 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16568 scoped_refptr<HttpResponseHeaders>* override_response_headers,
569 GURL* allowed_unsafe_redirect_url) {
570 TestNetworkDelegate::OnHeadersReceived(request,
571 callback,
572 original_response_headers,
573 override_response_headers,
574 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30575
576 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
577}
578
579NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
580 URLRequest* request,
581 const AuthChallengeInfo& auth_info,
582 const AuthCallback& callback,
583 AuthCredentials* credentials) {
584 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
585 credentials);
586 // Check that the user has provided callback for the previous blocked stage.
587 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
588
589 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
590 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
591 }
592
593 target_auth_credentials_ = credentials;
594
595 switch (block_mode_) {
596 case SYNCHRONOUS:
597 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
598 *target_auth_credentials_ = auth_credentials_;
599 return auth_retval_;
600
601 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45602 base::ThreadTaskRunnerHandle::Get()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30603 FROM_HERE,
604 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
605 weak_factory_.GetWeakPtr(), auth_retval_, callback));
606 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
607
608 case USER_CALLBACK:
609 auth_callback_ = callback;
610 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
skyostil4891b25b2015-06-11 11:43:45611 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17612 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30613 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
614 }
615 NOTREACHED();
616 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
617}
618
619void BlockingNetworkDelegate::Reset() {
620 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
621 stage_blocked_for_callback_ = NOT_BLOCKED;
622 callback_.Reset();
623 auth_callback_.Reset();
624}
625
626int BlockingNetworkDelegate::MaybeBlockStage(
627 BlockingNetworkDelegate::Stage stage,
628 const CompletionCallback& callback) {
629 // Check that the user has provided callback for the previous blocked stage.
630 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
631
632 if ((block_on_ & stage) == 0) {
633 return OK;
634 }
635
636 switch (block_mode_) {
637 case SYNCHRONOUS:
638 EXPECT_NE(OK, retval_);
639 return retval_;
640
641 case AUTO_CALLBACK:
skyostil4891b25b2015-06-11 11:43:45642 base::ThreadTaskRunnerHandle::Get()->PostTask(
643 FROM_HERE, base::Bind(&BlockingNetworkDelegate::RunCallback,
644 weak_factory_.GetWeakPtr(), retval_, callback));
[email protected]dc5a5cf2012-09-26 02:49:30645 return ERR_IO_PENDING;
646
647 case USER_CALLBACK:
648 callback_ = callback;
649 stage_blocked_for_callback_ = stage;
skyostil4891b25b2015-06-11 11:43:45650 base::ThreadTaskRunnerHandle::Get()->PostTask(
ki.stfu375812e2015-10-09 20:23:17651 FROM_HERE, base::MessageLoop::QuitWhenIdleClosure());
[email protected]dc5a5cf2012-09-26 02:49:30652 return ERR_IO_PENDING;
653 }
654 NOTREACHED();
655 return 0;
656}
657
[email protected]d5a4dd62012-05-23 01:41:04658class TestURLRequestContextWithProxy : public TestURLRequestContext {
659 public:
660 // Does not own |delegate|.
661 TestURLRequestContextWithProxy(const std::string& proxy,
662 NetworkDelegate* delegate)
663 : TestURLRequestContext(true) {
664 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
665 set_network_delegate(delegate);
666 Init();
667 }
dchengb03027d2014-10-21 12:00:20668 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04669};
670
stefanocsbd5be5202016-06-10 03:37:55671// A mock ReportSenderInterface that just remembers the latest report
estark06e0dac2015-08-07 21:56:01672// URI and report to be sent.
673class MockCertificateReportSender
stefanocsbd5be5202016-06-10 03:37:55674 : public TransportSecurityState::ReportSenderInterface {
estark06e0dac2015-08-07 21:56:01675 public:
676 MockCertificateReportSender() {}
677 ~MockCertificateReportSender() override {}
678
estarkb1716e22016-09-28 06:03:44679 void Send(const GURL& report_uri,
680 base::StringPiece content_type,
681 base::StringPiece report) override {
estark06e0dac2015-08-07 21:56:01682 latest_report_uri_ = report_uri;
estarkb1716e22016-09-28 06:03:44683 report.CopyToString(&latest_report_);
684 content_type.CopyToString(&latest_content_type_);
estark06e0dac2015-08-07 21:56:01685 }
686
estarkf2979122016-04-05 17:04:39687 void SetErrorCallback(
688 const base::Callback<void(const GURL&, int)>& error_callback) override {}
689
estark06e0dac2015-08-07 21:56:01690 const GURL& latest_report_uri() { return latest_report_uri_; }
691 const std::string& latest_report() { return latest_report_; }
estarkb1716e22016-09-28 06:03:44692 const std::string& latest_content_type() { return latest_content_type_; }
estark06e0dac2015-08-07 21:56:01693
694 private:
695 GURL latest_report_uri_;
696 std::string latest_report_;
estarkb1716e22016-09-28 06:03:44697 std::string latest_content_type_;
estark06e0dac2015-08-07 21:56:01698};
699
estarkcd39c11f2015-10-19 19:46:36700class TestExperimentalFeaturesNetworkDelegate : public TestNetworkDelegate {
701 public:
702 bool OnAreExperimentalCookieFeaturesEnabled() const override { return true; }
jww79aceda2015-12-07 01:56:34703 bool OnAreStrictSecureCookiesEnabled() const override { return true; }
estarkcd39c11f2015-10-19 19:46:36704};
705
dadrian612337a2016-07-20 22:36:58706// OCSPErrorTestDelegate caches the SSLInfo passed to OnSSLCertificateError.
707// This is needed because after the certificate failure, the URLRequest will
708// retry the connection, and return a partial SSLInfo with a cached cert status.
709// The partial SSLInfo does not have the OCSP information filled out.
710class OCSPErrorTestDelegate : public TestDelegate {
711 public:
712 void OnSSLCertificateError(URLRequest* request,
713 const SSLInfo& ssl_info,
714 bool fatal) override {
715 ssl_info_ = ssl_info;
716 on_ssl_certificate_error_called_ = true;
717 TestDelegate::OnSSLCertificateError(request, ssl_info, fatal);
718 }
719
720 bool on_ssl_certificate_error_called() {
721 return on_ssl_certificate_error_called_;
722 }
723
724 SSLInfo ssl_info() { return ssl_info_; }
725
726 private:
727 bool on_ssl_certificate_error_called_ = false;
728 SSLInfo ssl_info_;
729};
730
[email protected]d5a4dd62012-05-23 01:41:04731} // namespace
732
[email protected]a592c0432012-12-01 18:10:29733// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48734class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00735 public:
[email protected]ef2bf422012-05-11 03:27:09736 URLRequestTest() : default_context_(true) {
737 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25738 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50739 job_factory_impl_ = new URLRequestJobFactoryImpl();
740 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50741 }
bengr1bf8e942014-11-07 01:36:50742
dcheng67be2b1f2014-10-27 21:47:29743 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18744 // URLRequestJobs may post clean-up tasks on destruction.
745 base::RunLoop().RunUntilIdle();
746 }
[email protected]87a09a92011-07-14 15:50:50747
dcheng2339883c2014-12-23 00:23:05748 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50749 SetUpFactory();
750 default_context_.set_job_factory(job_factory_.get());
751 default_context_.Init();
752 PlatformTest::SetUp();
753 }
754
755 virtual void SetUpFactory() {
svaldez5d58c9e2015-08-24 21:36:20756 job_factory_impl_->SetProtocolHandler(
danakj8522a25b2016-04-16 00:17:36757 "data", base::WrapUnique(new DataProtocolHandler));
bengr1bf8e942014-11-07 01:36:50758#if !defined(DISABLE_FILE_SUPPORT)
759 job_factory_impl_->SetProtocolHandler(
ricea2deef682016-09-09 08:04:07760 "file", base::MakeUnique<FileProtocolHandler>(
761 base::ThreadTaskRunnerHandle::Get()));
bengr1bf8e942014-11-07 01:36:50762#endif
763 }
764
765 TestNetworkDelegate* default_network_delegate() {
766 return &default_network_delegate_;
767 }
768
769 const TestURLRequestContext& default_context() const {
770 return default_context_;
771 }
772
773
[email protected]3c5ca8c2011-09-29 01:14:51774 // Adds the TestJobInterceptor to the default context.
775 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23776 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
svaldez5d58c9e2015-08-24 21:36:20777 job_factory_impl_->SetProtocolHandler("http", nullptr);
778 job_factory_impl_->SetProtocolHandler("http",
danakj8522a25b2016-04-16 00:17:36779 base::WrapUnique(protocol_handler_));
[email protected]f53b4802012-12-20 17:04:23780 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51781 }
782
[email protected]87a09a92011-07-14 15:50:50783 protected:
vishal.b62985ca92015-04-17 08:45:51784 TestNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24785 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50786 URLRequestJobFactoryImpl* job_factory_impl_;
danakj8522a25b2016-04-16 00:17:36787 std::unique_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09788 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48789};
790
[email protected]316c1e5e2012-09-12 15:17:44791TEST_F(URLRequestTest, AboutBlankTest) {
792 TestDelegate d;
793 {
danakj8522a25b2016-04-16 00:17:36794 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36795 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44796
[email protected]f7022f32014-08-21 16:32:19797 r->Start();
798 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44799
[email protected]255620da2013-08-19 13:14:29800 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44801
[email protected]f7022f32014-08-21 16:32:19802 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44803 EXPECT_FALSE(d.received_data_before_response());
804 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19805 EXPECT_EQ("", r->GetSocketAddress().host());
806 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04807
808 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19809 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44810 }
811}
812
813TEST_F(URLRequestTest, DataURLImageTest) {
814 TestDelegate d;
815 {
816 // Use our nice little Chrome logo.
danakj8522a25b2016-04-16 00:17:36817 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
818 GURL("data:image/png;base64,"
819 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
820 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
821 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
822 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
823 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
824 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
825 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
826 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
827 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
828 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
829 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
830 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
831 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
832 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
833 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
834 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
835 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
836 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
837 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
davidben151423e2015-03-23 18:48:36838 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44839
[email protected]f7022f32014-08-21 16:32:19840 r->Start();
841 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44842
[email protected]255620da2013-08-19 13:14:29843 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44844
[email protected]f7022f32014-08-21 16:32:19845 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44846 EXPECT_FALSE(d.received_data_before_response());
847 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19848 EXPECT_EQ("", r->GetSocketAddress().host());
849 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04850
851 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19852 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44853 }
854}
855
[email protected]5ecf7cb282014-05-11 01:49:55856#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44857TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15858 base::FilePath app_path;
kraush5a645822016-04-07 18:35:04859
860#if defined(OS_ANDROID)
861 // Android devices are not guaranteed to be able to read /proc/self/exe
862 // Use /etc/hosts instead
863 app_path = base::FilePath("/etc/hosts");
864#else
[email protected]316c1e5e2012-09-12 15:17:44865 PathService::Get(base::FILE_EXE, &app_path);
kraush5a645822016-04-07 18:35:04866#endif // OS_ANDROID
867
[email protected]316c1e5e2012-09-12 15:17:44868 GURL app_url = FilePathToFileURL(app_path);
869
870 TestDelegate d;
871 {
danakj8522a25b2016-04-16 00:17:36872 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36873 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44874
[email protected]f7022f32014-08-21 16:32:19875 r->Start();
876 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44877
[email protected]255620da2013-08-19 13:14:29878 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44879
avibf0746c2015-12-09 19:53:14880 int64_t file_size = -1;
[email protected]56285702013-12-04 18:22:49881 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44882
[email protected]f7022f32014-08-21 16:32:19883 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44884 EXPECT_EQ(1, d.response_started_count());
885 EXPECT_FALSE(d.received_data_before_response());
886 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19887 EXPECT_EQ("", r->GetSocketAddress().host());
888 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04889
890 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19891 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44892 }
893}
894
[email protected]ba40bb762012-12-17 07:11:04895TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15896 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04897 PathService::Get(base::FILE_EXE, &app_path);
898 GURL app_url = FilePathToFileURL(app_path);
899
900 TestDelegate d;
901 {
danakj8522a25b2016-04-16 00:17:36902 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36903 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04904
[email protected]f7022f32014-08-21 16:32:19905 r->Start();
906 EXPECT_TRUE(r->is_pending());
907 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04908 }
[email protected]79e1fd62013-06-20 06:50:04909 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04910 // destroyed.
[email protected]255620da2013-08-19 13:14:29911 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04912}
913
[email protected]316c1e5e2012-09-12 15:17:44914TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
915 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36916 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44917 FillBuffer(buffer.get(), buffer_size);
918
[email protected]6cdfd7f2013-02-08 20:40:15919 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52920 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44921 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30922 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44923
avibf0746c2015-12-09 19:53:14924 int64_t file_size;
[email protected]56285702013-12-04 18:22:49925 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44926
927 const size_t first_byte_position = 500;
928 const size_t last_byte_position = buffer_size - first_byte_position;
929 const size_t content_length = last_byte_position - first_byte_position + 1;
930 std::string partial_buffer_string(buffer.get() + first_byte_position,
931 buffer.get() + last_byte_position + 1);
932
933 TestDelegate d;
934 {
danakj8522a25b2016-04-16 00:17:36935 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36936 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44937
938 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38939 headers.SetHeader(
940 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59941 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38942 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19943 r->SetExtraRequestHeaders(headers);
944 r->Start();
945 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44946
[email protected]255620da2013-08-19 13:14:29947 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19948 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44949 EXPECT_EQ(1, d.response_started_count());
950 EXPECT_FALSE(d.received_data_before_response());
951 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
952 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
953 EXPECT_TRUE(partial_buffer_string == d.data_received());
954 }
955
[email protected]dd3aa792013-07-16 19:10:23956 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44957}
958
959TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
960 const size_t buffer_size = 4000;
danakj8522a25b2016-04-16 00:17:36961 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44962 FillBuffer(buffer.get(), buffer_size);
963
[email protected]6cdfd7f2013-02-08 20:40:15964 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52965 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44966 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30967 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44968
avibf0746c2015-12-09 19:53:14969 int64_t file_size;
[email protected]56285702013-12-04 18:22:49970 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44971
972 const size_t first_byte_position = 500;
973 const size_t last_byte_position = buffer_size - 1;
974 const size_t content_length = last_byte_position - first_byte_position + 1;
975 std::string partial_buffer_string(buffer.get() + first_byte_position,
976 buffer.get() + last_byte_position + 1);
977
978 TestDelegate d;
979 {
danakj8522a25b2016-04-16 00:17:36980 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:36981 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44982
983 HttpRequestHeaders headers;
984 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59985 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38986 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19987 r->SetExtraRequestHeaders(headers);
988 r->Start();
989 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44990
[email protected]255620da2013-08-19 13:14:29991 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19992 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44993 EXPECT_EQ(1, d.response_started_count());
994 EXPECT_FALSE(d.received_data_before_response());
995 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
996 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
997 EXPECT_TRUE(partial_buffer_string == d.data_received());
998 }
999
[email protected]dd3aa792013-07-16 19:10:231000 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441001}
1002
1003TEST_F(URLRequestTest, FileTestMultipleRanges) {
1004 const size_t buffer_size = 400000;
danakj8522a25b2016-04-16 00:17:361005 std::unique_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:441006 FillBuffer(buffer.get(), buffer_size);
1007
[email protected]6cdfd7f2013-02-08 20:40:151008 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:521009 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:441010 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:301011 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:441012
avibf0746c2015-12-09 19:53:141013 int64_t file_size;
[email protected]56285702013-12-04 18:22:491014 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:441015
1016 TestDelegate d;
1017 {
danakj8522a25b2016-04-16 00:17:361018 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361019 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:441020
1021 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:381022 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:191023 r->SetExtraRequestHeaders(headers);
1024 r->Start();
1025 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441026
[email protected]255620da2013-08-19 13:14:291027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441028 EXPECT_TRUE(d.request_failed());
1029 }
1030
[email protected]dd3aa792013-07-16 19:10:231031 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:441032}
1033
[email protected]3ca8b362013-11-11 22:18:071034TEST_F(URLRequestTest, AllowFileURLs) {
1035 base::ScopedTempDir temp_dir;
1036 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
1037 base::FilePath test_file;
vabrb8582322016-09-09 08:05:371038 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.GetPath(), &test_file));
[email protected]3ca8b362013-11-11 22:18:071039 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:301040 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:591041 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:071042
1043 {
1044 TestDelegate d;
1045 TestNetworkDelegate network_delegate;
1046 network_delegate.set_can_access_files(true);
1047 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361048 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361049 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191050 r->Start();
[email protected]3ca8b362013-11-11 22:18:071051 base::RunLoop().Run();
1052 EXPECT_FALSE(d.request_failed());
1053 EXPECT_EQ(test_data, d.data_received());
1054 }
1055
1056 {
1057 TestDelegate d;
1058 TestNetworkDelegate network_delegate;
1059 network_delegate.set_can_access_files(false);
1060 default_context_.set_network_delegate(&network_delegate);
danakj8522a25b2016-04-16 00:17:361061 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:361062 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191063 r->Start();
[email protected]3ca8b362013-11-11 22:18:071064 base::RunLoop().Run();
1065 EXPECT_TRUE(d.request_failed());
1066 EXPECT_EQ("", d.data_received());
1067 }
1068}
1069
[email protected]316c1e5e2012-09-12 15:17:441070
1071TEST_F(URLRequestTest, FileDirCancelTest) {
1072 // Put in mock resource provider.
1073 NetModule::SetResourceProvider(TestNetResourceProvider);
1074
1075 TestDelegate d;
1076 {
[email protected]6cdfd7f2013-02-08 20:40:151077 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:441078 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
1079 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
1080 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
1081
danakj8522a25b2016-04-16 00:17:361082 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361083 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191084 req->Start();
1085 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:441086
1087 d.set_cancel_in_received_data_pending(true);
1088
[email protected]255620da2013-08-19 13:14:291089 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441090 }
1091
1092 // Take out mock resource provider.
1093 NetModule::SetResourceProvider(NULL);
1094}
1095
[email protected]5f9581402013-10-30 13:08:321096TEST_F(URLRequestTest, FileDirOutputSanity) {
1097 // Verify the general sanity of the the output of the file:
1098 // directory lister by checking for the output of a known existing
1099 // file.
1100 const char sentinel_name[] = "filedir-sentinel";
1101
1102 base::FilePath path;
1103 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471104 path = path.Append(kTestFilePath);
[email protected]5f9581402013-10-30 13:08:321105
1106 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361107 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361108 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191109 req->Start();
[email protected]5f9581402013-10-30 13:08:321110 base::RunLoop().Run();
1111
1112 // Generate entry for the sentinel file.
1113 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:581114 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:491115 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:321116 EXPECT_GT(info.size, 0);
1117 std::string sentinel_output = GetDirectoryListingEntry(
1118 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1119 std::string(sentinel_name),
1120 false /* is_dir */,
1121 info.size,
1122 info.last_modified);
1123
1124 ASSERT_LT(0, d.bytes_received());
1125 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501126 EXPECT_EQ(OK, d.request_status());
[email protected]5f9581402013-10-30 13:08:321127 // Check for the entry generated for the "sentinel" file.
1128 const std::string& data = d.data_received();
1129 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1130}
1131
[email protected]316c1e5e2012-09-12 15:17:441132TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1133 // There is an implicit redirect when loading a file path that matches a
1134 // directory and does not end with a slash. Ensure that following such
1135 // redirects does not crash. See http://crbug.com/18686.
1136
[email protected]6cdfd7f2013-02-08 20:40:151137 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441138 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:471139 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:441140
1141 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361142 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361143 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191144 req->Start();
[email protected]255620da2013-08-19 13:14:291145 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441146
1147 ASSERT_EQ(1, d.received_redirect_count());
1148 ASSERT_LT(0, d.bytes_received());
1149 ASSERT_FALSE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:501150 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441151}
1152
1153#if defined(OS_WIN)
1154// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1155TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1156 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361157 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361158 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191159 req->Start();
[email protected]255620da2013-08-19 13:14:291160 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441161
1162 ASSERT_EQ(1, d.received_redirect_count());
maksim.sisovb53724b52016-09-16 05:30:501163 EXPECT_NE(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:441164}
[email protected]5ecf7cb282014-05-11 01:49:551165#endif // defined(OS_WIN)
1166
1167#endif // !defined(DISABLE_FILE_SUPPORT)
1168
1169TEST_F(URLRequestTest, InvalidUrlTest) {
1170 TestDelegate d;
1171 {
danakj8522a25b2016-04-16 00:17:361172 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361173 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551174
[email protected]f7022f32014-08-21 16:32:191175 r->Start();
1176 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551177
1178 base::RunLoop().Run();
1179 EXPECT_TRUE(d.request_failed());
1180 }
1181}
1182
jochen0e3b3a62014-09-16 18:31:231183TEST_F(URLRequestTest, InvalidReferrerTest) {
1184 TestURLRequestContext context;
1185 TestNetworkDelegate network_delegate;
1186 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1187 context.set_network_delegate(&network_delegate);
1188 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361189 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:361190 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231191 req->SetReferrer("https://somewhere.com/");
1192
1193 req->Start();
1194 base::RunLoop().Run();
1195 EXPECT_TRUE(d.request_failed());
1196}
1197
[email protected]5ecf7cb282014-05-11 01:49:551198#if defined(OS_WIN)
1199TEST_F(URLRequestTest, ResolveShortcutTest) {
1200 base::FilePath app_path;
1201 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
mmenke9f2ec60c2015-06-01 20:59:471202 app_path = app_path.Append(kTestFilePath);
[email protected]5ecf7cb282014-05-11 01:49:551203 app_path = app_path.AppendASCII("with-headers.html");
1204
1205 std::wstring lnk_path = app_path.value() + L".lnk";
1206
1207 base::win::ScopedCOMInitializer com_initializer;
1208
1209 // Temporarily create a shortcut for test
1210 {
1211 base::win::ScopedComPtr<IShellLink> shell;
1212 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1213 CLSCTX_INPROC_SERVER)));
1214 base::win::ScopedComPtr<IPersistFile> persist;
1215 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1216 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1217 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1218 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1219 }
1220
1221 TestDelegate d;
1222 {
danakj8522a25b2016-04-16 00:17:361223 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361224 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551225
[email protected]f7022f32014-08-21 16:32:191226 r->Start();
1227 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551228
1229 base::RunLoop().Run();
1230
1231 WIN32_FILE_ATTRIBUTE_DATA data;
1232 GetFileAttributesEx(app_path.value().c_str(),
1233 GetFileExInfoStandard, &data);
1234 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1235 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1236 FILE_ATTRIBUTE_NORMAL, NULL);
1237 EXPECT_NE(INVALID_HANDLE_VALUE, file);
danakj8522a25b2016-04-16 00:17:361238 std::unique_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]5ecf7cb282014-05-11 01:49:551239 DWORD read_size;
1240 BOOL result;
1241 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1242 &read_size, NULL);
1243 std::string content(buffer.get(), read_size);
1244 CloseHandle(file);
1245
[email protected]f7022f32014-08-21 16:32:191246 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551247 EXPECT_EQ(1, d.received_redirect_count());
1248 EXPECT_EQ(content, d.data_received());
1249 }
1250
1251 // Clean the shortcut
1252 DeleteFile(lnk_path.c_str());
1253}
1254#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441255
1256// Custom URLRequestJobs for use with interceptor tests
1257class RestartTestJob : public URLRequestTestJob {
1258 public:
1259 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1260 : URLRequestTestJob(request, network_delegate, true) {}
1261 protected:
dchengb03027d2014-10-21 12:00:201262 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441263 private:
dchengb03027d2014-10-21 12:00:201264 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441265};
1266
1267class CancelTestJob : public URLRequestTestJob {
1268 public:
1269 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1270 : URLRequestTestJob(request, network_delegate, true) {}
1271 protected:
dchengb03027d2014-10-21 12:00:201272 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441273 private:
dchengb03027d2014-10-21 12:00:201274 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441275};
1276
1277class CancelThenRestartTestJob : public URLRequestTestJob {
1278 public:
1279 explicit CancelThenRestartTestJob(URLRequest* request,
1280 NetworkDelegate* network_delegate)
1281 : URLRequestTestJob(request, network_delegate, true) {
1282 }
1283 protected:
dchengb03027d2014-10-21 12:00:201284 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441285 request_->Cancel();
1286 this->NotifyRestartRequired();
1287 }
1288 private:
dchengb03027d2014-10-21 12:00:201289 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441290};
1291
bengr1bf8e942014-11-07 01:36:501292// An Interceptor for use with interceptor tests.
1293class MockURLRequestInterceptor : public URLRequestInterceptor {
1294 public:
1295 // Static getters for canned response header and data strings.
1296 static std::string ok_data() {
1297 return URLRequestTestJob::test_data_1();
1298 }
1299
1300 static std::string ok_headers() {
1301 return URLRequestTestJob::test_headers();
1302 }
1303
1304 static std::string redirect_data() {
1305 return std::string();
1306 }
1307
1308 static std::string redirect_headers() {
1309 return URLRequestTestJob::test_redirect_headers();
1310 }
1311
1312 static std::string error_data() {
1313 return std::string("ohhh nooooo mr. bill!");
1314 }
1315
1316 static std::string error_headers() {
1317 return URLRequestTestJob::test_error_headers();
1318 }
1319
1320 MockURLRequestInterceptor()
1321 : intercept_main_request_(false), restart_main_request_(false),
1322 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1323 simulate_main_network_error_(false),
1324 intercept_redirect_(false), cancel_redirect_request_(false),
1325 intercept_final_response_(false), cancel_final_request_(false),
1326 use_url_request_http_job_(false),
1327 did_intercept_main_(false), did_restart_main_(false),
1328 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1329 did_simulate_error_main_(false),
1330 did_intercept_redirect_(false), did_cancel_redirect_(false),
1331 did_intercept_final_(false), did_cancel_final_(false) {
1332 }
1333
1334 ~MockURLRequestInterceptor() override {
1335 }
1336
1337 // URLRequestInterceptor implementation:
1338 URLRequestJob* MaybeInterceptRequest(
1339 URLRequest* request,
1340 NetworkDelegate* network_delegate) const override {
1341 if (restart_main_request_) {
1342 restart_main_request_ = false;
1343 did_restart_main_ = true;
1344 return new RestartTestJob(request, network_delegate);
1345 }
1346 if (cancel_main_request_) {
1347 cancel_main_request_ = false;
1348 did_cancel_main_ = true;
1349 return new CancelTestJob(request, network_delegate);
1350 }
1351 if (cancel_then_restart_main_request_) {
1352 cancel_then_restart_main_request_ = false;
1353 did_cancel_then_restart_main_ = true;
1354 return new CancelThenRestartTestJob(request, network_delegate);
1355 }
1356 if (simulate_main_network_error_) {
1357 simulate_main_network_error_ = false;
1358 did_simulate_error_main_ = true;
1359 if (use_url_request_http_job_) {
1360 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1361 }
1362 // This job will result in error since the requested URL is not one of the
1363 // URLs supported by these tests.
1364 return new URLRequestTestJob(request, network_delegate, true);
1365 }
1366 if (!intercept_main_request_)
1367 return nullptr;
1368 intercept_main_request_ = false;
1369 did_intercept_main_ = true;
1370 URLRequestTestJob* job = new URLRequestTestJob(request,
1371 network_delegate,
1372 main_headers_,
1373 main_data_,
1374 true);
1375 job->set_load_timing_info(main_request_load_timing_info_);
1376 return job;
1377 }
1378
1379 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1380 NetworkDelegate* network_delegate,
1381 const GURL& location) const override {
1382 if (cancel_redirect_request_) {
1383 cancel_redirect_request_ = false;
1384 did_cancel_redirect_ = true;
1385 return new CancelTestJob(request, network_delegate);
1386 }
1387 if (!intercept_redirect_)
1388 return nullptr;
1389 intercept_redirect_ = false;
1390 did_intercept_redirect_ = true;
1391 if (use_url_request_http_job_) {
1392 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1393 }
1394 return new URLRequestTestJob(request,
1395 network_delegate,
1396 redirect_headers_,
1397 redirect_data_,
1398 true);
1399 }
1400
1401 URLRequestJob* MaybeInterceptResponse(
1402 URLRequest* request,
1403 NetworkDelegate* network_delegate) const override {
1404 if (cancel_final_request_) {
1405 cancel_final_request_ = false;
1406 did_cancel_final_ = true;
1407 return new CancelTestJob(request, network_delegate);
1408 }
1409 if (!intercept_final_response_)
1410 return nullptr;
1411 intercept_final_response_ = false;
1412 did_intercept_final_ = true;
1413 if (use_url_request_http_job_) {
1414 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1415 }
1416 return new URLRequestTestJob(request,
1417 network_delegate,
1418 final_headers_,
1419 final_data_,
1420 true);
1421 }
1422
1423 void set_intercept_main_request(bool intercept_main_request) {
1424 intercept_main_request_ = intercept_main_request;
1425 }
1426
1427 void set_main_headers(const std::string& main_headers) {
1428 main_headers_ = main_headers;
1429 }
1430
1431 void set_main_data(const std::string& main_data) {
1432 main_data_ = main_data;
1433 }
1434
1435 void set_main_request_load_timing_info(
1436 const LoadTimingInfo& main_request_load_timing_info) {
1437 main_request_load_timing_info_ = main_request_load_timing_info;
1438 }
1439
1440 void set_restart_main_request(bool restart_main_request) {
1441 restart_main_request_ = restart_main_request;
1442 }
1443
1444 void set_cancel_main_request(bool cancel_main_request) {
1445 cancel_main_request_ = cancel_main_request;
1446 }
1447
1448 void set_cancel_then_restart_main_request(
1449 bool cancel_then_restart_main_request) {
1450 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1451 }
1452
1453 void set_simulate_main_network_error(bool simulate_main_network_error) {
1454 simulate_main_network_error_ = simulate_main_network_error;
1455 }
1456
1457 void set_intercept_redirect(bool intercept_redirect) {
1458 intercept_redirect_ = intercept_redirect;
1459 }
1460
1461 void set_redirect_headers(const std::string& redirect_headers) {
1462 redirect_headers_ = redirect_headers;
1463 }
1464
1465 void set_redirect_data(const std::string& redirect_data) {
1466 redirect_data_ = redirect_data;
1467 }
1468
1469 void set_cancel_redirect_request(bool cancel_redirect_request) {
1470 cancel_redirect_request_ = cancel_redirect_request;
1471 }
1472
1473 void set_intercept_final_response(bool intercept_final_response) {
1474 intercept_final_response_ = intercept_final_response;
1475 }
1476
1477 void set_final_headers(const std::string& final_headers) {
1478 final_headers_ = final_headers;
1479 }
1480
1481 void set_final_data(const std::string& final_data) {
1482 final_data_ = final_data;
1483 }
1484
1485 void set_cancel_final_request(bool cancel_final_request) {
1486 cancel_final_request_ = cancel_final_request;
1487 }
1488
1489 void set_use_url_request_http_job(bool use_url_request_http_job) {
1490 use_url_request_http_job_ = use_url_request_http_job;
1491 }
1492
1493 bool did_intercept_main() const {
1494 return did_intercept_main_;
1495 }
1496
1497 bool did_restart_main() const {
1498 return did_restart_main_;
1499 }
1500
1501 bool did_cancel_main() const {
1502 return did_cancel_main_;
1503 }
1504
1505 bool did_cancel_then_restart_main() const {
1506 return did_cancel_then_restart_main_;
1507 }
1508
1509 bool did_simulate_error_main() const {
1510 return did_simulate_error_main_;
1511 }
1512
1513 bool did_intercept_redirect() const {
1514 return did_intercept_redirect_;
1515 }
1516
1517 bool did_cancel_redirect() const {
1518 return did_cancel_redirect_;
1519 }
1520
1521 bool did_intercept_final() const {
1522 return did_intercept_final_;
1523 }
1524
1525 bool did_cancel_final() const {
1526 return did_cancel_final_;
1527 }
1528
1529 private:
1530 // Indicate whether to intercept the main request, and if so specify the
1531 // response to return and the LoadTimingInfo to use.
1532 mutable bool intercept_main_request_;
1533 mutable std::string main_headers_;
1534 mutable std::string main_data_;
1535 mutable LoadTimingInfo main_request_load_timing_info_;
1536
1537 // These indicate actions that can be taken within MaybeInterceptRequest.
1538 mutable bool restart_main_request_;
1539 mutable bool cancel_main_request_;
1540 mutable bool cancel_then_restart_main_request_;
1541 mutable bool simulate_main_network_error_;
1542
1543 // Indicate whether to intercept redirects, and if so specify the response to
1544 // return.
1545 mutable bool intercept_redirect_;
1546 mutable std::string redirect_headers_;
1547 mutable std::string redirect_data_;
1548
1549 // Cancel the request within MaybeInterceptRedirect.
1550 mutable bool cancel_redirect_request_;
1551
1552 // Indicate whether to intercept the final response, and if so specify the
1553 // response to return.
1554 mutable bool intercept_final_response_;
1555 mutable std::string final_headers_;
1556 mutable std::string final_data_;
1557
1558 // Cancel the final request within MaybeInterceptResponse.
1559 mutable bool cancel_final_request_;
1560
1561 // Instruct the interceptor to use a real URLRequestHTTPJob.
1562 mutable bool use_url_request_http_job_;
1563
1564 // These indicate if the interceptor did something or not.
1565 mutable bool did_intercept_main_;
1566 mutable bool did_restart_main_;
1567 mutable bool did_cancel_main_;
1568 mutable bool did_cancel_then_restart_main_;
1569 mutable bool did_simulate_error_main_;
1570 mutable bool did_intercept_redirect_;
1571 mutable bool did_cancel_redirect_;
1572 mutable bool did_intercept_final_;
1573 mutable bool did_cancel_final_;
1574};
1575
1576// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1577class URLRequestInterceptorTest : public URLRequestTest {
1578 public:
1579 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1580 }
1581
1582 ~URLRequestInterceptorTest() override {
1583 // URLRequestJobs may post clean-up tasks on destruction.
1584 base::RunLoop().RunUntilIdle();
1585 }
1586
1587 void SetUpFactory() override {
1588 interceptor_ = new MockURLRequestInterceptor();
1589 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:361590 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:501591 }
1592
1593 MockURLRequestInterceptor* interceptor() const {
1594 return interceptor_;
1595 }
1596
1597 private:
1598 MockURLRequestInterceptor* interceptor_;
1599};
1600
1601TEST_F(URLRequestInterceptorTest, Intercept) {
1602 // Intercept the main request and respond with a simple response.
1603 interceptor()->set_intercept_main_request(true);
1604 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1605 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591606 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361607 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361608 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501609 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1610 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1611 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1612 req->SetUserData(nullptr, user_data0);
1613 req->SetUserData(&user_data1, user_data1);
1614 req->SetUserData(&user_data2, user_data2);
1615 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191616 req->Start();
[email protected]255620da2013-08-19 13:14:291617 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591618
bengr1bf8e942014-11-07 01:36:501619 // Make sure we can retrieve our specific user data.
1620 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1621 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1622 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591623
bengr1bf8e942014-11-07 01:36:501624 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501625 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501626 EXPECT_EQ(200, req->response_headers()->response_code());
1627 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1628 EXPECT_EQ(1, d.response_started_count());
1629 EXPECT_EQ(0, d.received_redirect_count());
1630}
[email protected]2bba3252013-04-08 19:50:591631
bengr1bf8e942014-11-07 01:36:501632TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1633 // Intercept the main request and respond with a redirect.
1634 interceptor()->set_intercept_main_request(true);
1635 interceptor()->set_main_headers(
1636 MockURLRequestInterceptor::redirect_headers());
1637 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1638
1639 // Intercept that redirect and respond with a final OK response.
1640 interceptor()->set_intercept_redirect(true);
1641 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1642 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1643
1644 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361645 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361646 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501647 req->set_method("GET");
1648 req->Start();
1649 base::RunLoop().Run();
1650
1651 // Check that the interceptor got called as expected.
1652 EXPECT_TRUE(interceptor()->did_intercept_main());
1653 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1654
1655 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501656 int status = d.request_status();
1657 EXPECT_EQ(OK, status);
1658 if (status == OK)
bengr1bf8e942014-11-07 01:36:501659 EXPECT_EQ(200, req->response_headers()->response_code());
1660
1661 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1662 EXPECT_EQ(1, d.response_started_count());
1663 EXPECT_EQ(0, d.received_redirect_count());
1664}
1665
1666TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1667 // Intercept the main request to generate a server error response.
1668 interceptor()->set_intercept_main_request(true);
1669 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1670 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1671
1672 // Intercept that error and respond with an OK response.
1673 interceptor()->set_intercept_final_response(true);
1674 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1675 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1676
1677 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361678 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361679 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501680 req->set_method("GET");
1681 req->Start();
1682 base::RunLoop().Run();
1683
1684 // Check that the interceptor got called as expected.
1685 EXPECT_TRUE(interceptor()->did_intercept_main());
1686 EXPECT_TRUE(interceptor()->did_intercept_final());
1687
1688 // Check that we got one good response.
maksim.sisovb53724b52016-09-16 05:30:501689 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501690 EXPECT_EQ(200, req->response_headers()->response_code());
1691 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1692 EXPECT_EQ(1, d.response_started_count());
1693 EXPECT_EQ(0, d.received_redirect_count());
1694}
1695
1696TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1697 // Intercept the main request to simulate a network error.
1698 interceptor()->set_simulate_main_network_error(true);
1699
1700 // Intercept that error and respond with an OK response.
1701 interceptor()->set_intercept_final_response(true);
1702 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1703 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1704
1705 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361706 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361707 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501708 req->set_method("GET");
1709 req->Start();
1710 base::RunLoop().Run();
1711
1712 // Check that the interceptor got called as expected.
1713 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1714 EXPECT_TRUE(interceptor()->did_intercept_final());
1715
1716 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501717 EXPECT_EQ(OK, d.request_status());
bengr1bf8e942014-11-07 01:36:501718 EXPECT_EQ(200, req->response_headers()->response_code());
1719 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1720 EXPECT_EQ(1, d.response_started_count());
1721 EXPECT_EQ(0, d.received_redirect_count());
1722}
1723
1724TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1725 // Restart the main request.
1726 interceptor()->set_restart_main_request(true);
1727
1728 // then intercept the new main request and respond with an OK response
1729 interceptor()->set_intercept_main_request(true);
1730 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1731 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1732
1733 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361734 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361735 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501736 req->set_method("GET");
1737 req->Start();
1738 base::RunLoop().Run();
1739
1740 // Check that the interceptor got called as expected.
1741 EXPECT_TRUE(interceptor()->did_restart_main());
1742 EXPECT_TRUE(interceptor()->did_intercept_main());
1743
1744 // Check that we received one good response.
maksim.sisovb53724b52016-09-16 05:30:501745 int status = d.request_status();
1746 EXPECT_EQ(OK, status);
1747 if (status == OK)
bengr1bf8e942014-11-07 01:36:501748 EXPECT_EQ(200, req->response_headers()->response_code());
1749
1750 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1751 EXPECT_EQ(1, d.response_started_count());
1752 EXPECT_EQ(0, d.received_redirect_count());
1753}
1754
1755TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1756 // Intercept the main request and cancel from within the restarted job.
1757 interceptor()->set_cancel_main_request(true);
1758
1759 // Set up to intercept the final response and override it with an OK response.
1760 interceptor()->set_intercept_final_response(true);
1761 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1762 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1763
1764 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361765 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361766 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501767 req->set_method("GET");
1768 req->Start();
1769 base::RunLoop().Run();
1770
1771 // Check that the interceptor got called as expected.
1772 EXPECT_TRUE(interceptor()->did_cancel_main());
1773 EXPECT_FALSE(interceptor()->did_intercept_final());
1774
1775 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501776 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501777}
1778
1779TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1780 // Intercept the main request and respond with a redirect.
1781 interceptor()->set_intercept_main_request(true);
1782 interceptor()->set_main_headers(
1783 MockURLRequestInterceptor::redirect_headers());
1784 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1785
1786 // Intercept the redirect and cancel from within that job.
1787 interceptor()->set_cancel_redirect_request(true);
1788
1789 // Set up to intercept the final response and override it with an OK response.
1790 interceptor()->set_intercept_final_response(true);
1791 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1792 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1793
1794 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361795 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361796 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501797 req->set_method("GET");
1798 req->Start();
1799 base::RunLoop().Run();
1800
1801 // Check that the interceptor got called as expected.
1802 EXPECT_TRUE(interceptor()->did_intercept_main());
1803 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1804 EXPECT_FALSE(interceptor()->did_intercept_final());
1805
1806 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501807 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501808}
1809
1810TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1811 // Intercept the main request to simulate a network error.
1812 interceptor()->set_simulate_main_network_error(true);
1813
1814 // Set up to intercept final the response and cancel from within that job.
1815 interceptor()->set_cancel_final_request(true);
1816
1817 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361818 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361819 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501820 req->set_method("GET");
1821 req->Start();
1822 base::RunLoop().Run();
1823
1824 // Check that the interceptor got called as expected.
1825 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1826 EXPECT_TRUE(interceptor()->did_cancel_final());
1827
1828 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501829 EXPECT_EQ(ERR_ABORTED, d.request_status());
bengr1bf8e942014-11-07 01:36:501830}
1831
1832TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1833 // Intercept the main request and cancel then restart from within that job.
1834 interceptor()->set_cancel_then_restart_main_request(true);
1835
1836 // Set up to intercept the final response and override it with an OK response.
1837 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501838 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1839 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501840
1841 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361842 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361843 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501844 req->set_method("GET");
1845 req->Start();
1846 base::RunLoop().Run();
1847
1848 // Check that the interceptor got called as expected.
1849 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1850 EXPECT_FALSE(interceptor()->did_intercept_final());
1851
1852 // Check that we see a canceled request.
maksim.sisovb53724b52016-09-16 05:30:501853 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]2bba3252013-04-08 19:50:591854}
1855
1856// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1857// reused. |connect_time_flags| is used to indicate if there should be dns
1858// or SSL times, and |used_proxy| is used for proxy times.
1859LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1860 int connect_time_flags,
1861 bool used_proxy) {
1862 LoadTimingInfo load_timing;
1863 load_timing.socket_log_id = 1;
1864
1865 if (used_proxy) {
1866 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1867 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1868 }
1869
1870 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1871 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1872 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1873 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1874 }
1875 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1876 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1877 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1878 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1879 }
1880 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1881
1882 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1883 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1884 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1885 return load_timing;
1886}
1887
1888// Same as above, but in the case of a reused socket.
1889LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1890 bool used_proxy) {
1891 LoadTimingInfo load_timing;
1892 load_timing.socket_log_id = 1;
1893 load_timing.socket_reused = true;
1894
1895 if (used_proxy) {
1896 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1897 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1898 }
1899
1900 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1901 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1902 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1903 return load_timing;
1904}
1905
bengr1bf8e942014-11-07 01:36:501906LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1907 const LoadTimingInfo& job_load_timing,
1908 const URLRequestContext& context,
1909 MockURLRequestInterceptor* interceptor) {
1910 interceptor->set_intercept_main_request(true);
1911 interceptor->set_main_request_load_timing_info(job_load_timing);
1912 TestDelegate d;
danakj8522a25b2016-04-16 00:17:361913 std::unique_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361914 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501915 req->Start();
1916 base::RunLoop().Run();
1917
1918 LoadTimingInfo resulting_load_timing;
1919 req->GetLoadTimingInfo(&resulting_load_timing);
1920
1921 // None of these should be modified by the URLRequest.
1922 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1923 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1924 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1925 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1926 EXPECT_EQ(job_load_timing.receive_headers_end,
1927 resulting_load_timing.receive_headers_end);
caseqe8340bc92016-04-20 00:02:571928 EXPECT_EQ(job_load_timing.push_start, resulting_load_timing.push_start);
1929 EXPECT_EQ(job_load_timing.push_end, resulting_load_timing.push_end);
bengr1bf8e942014-11-07 01:36:501930
1931 return resulting_load_timing;
1932}
1933
[email protected]2bba3252013-04-08 19:50:591934// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501935TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591936 base::TimeTicks now = base::TimeTicks::Now();
1937 LoadTimingInfo job_load_timing =
1938 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1939
[email protected]2ca01e52013-10-31 22:05:191940 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501941 RunURLRequestInterceptorLoadTimingTest(
1942 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591943
1944 // Nothing should have been changed by the URLRequest.
1945 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1946 load_timing_result.proxy_resolve_start);
1947 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1948 load_timing_result.proxy_resolve_end);
1949 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1950 load_timing_result.connect_timing.dns_start);
1951 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1952 load_timing_result.connect_timing.dns_end);
1953 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1954 load_timing_result.connect_timing.connect_start);
1955 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1956 load_timing_result.connect_timing.connect_end);
1957 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1958 load_timing_result.connect_timing.ssl_start);
1959 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1960 load_timing_result.connect_timing.ssl_end);
1961
1962 // Redundant sanity check.
1963 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1964}
1965
1966// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501967TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591968 base::TimeTicks now = base::TimeTicks::Now();
1969 LoadTimingInfo job_load_timing =
1970 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1971
[email protected]2ca01e52013-10-31 22:05:191972 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501973 RunURLRequestInterceptorLoadTimingTest(
1974 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591975
1976 // Nothing should have been changed by the URLRequest.
1977 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1978 load_timing_result.proxy_resolve_start);
1979 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1980 load_timing_result.proxy_resolve_end);
1981 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1982 load_timing_result.connect_timing.dns_start);
1983 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1984 load_timing_result.connect_timing.dns_end);
1985 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1986 load_timing_result.connect_timing.connect_start);
1987 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1988 load_timing_result.connect_timing.connect_end);
1989 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1990 load_timing_result.connect_timing.ssl_start);
1991 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1992 load_timing_result.connect_timing.ssl_end);
1993
1994 // Redundant sanity check.
1995 TestLoadTimingNotReusedWithProxy(load_timing_result,
1996 CONNECT_TIMING_HAS_SSL_TIMES);
1997}
1998
1999// Make sure that URLRequest correctly adjusts proxy times when they're before
2000// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102001// the case of reusing a SPDY session. The connected socket is not considered
2002// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592003//
2004// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502005TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592006 base::TimeTicks now = base::TimeTicks::Now();
2007 LoadTimingInfo job_load_timing =
2008 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2009 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2010 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2011 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2012 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2013 job_load_timing.connect_timing.connect_start =
2014 now - base::TimeDelta::FromDays(2);
2015 job_load_timing.connect_timing.connect_end =
2016 now - base::TimeDelta::FromDays(1);
2017
[email protected]2ca01e52013-10-31 22:05:192018 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502019 RunURLRequestInterceptorLoadTimingTest(
2020 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592021
2022 // Proxy times, connect times, and DNS times should all be replaced with
2023 // request_start.
2024 EXPECT_EQ(load_timing_result.request_start,
2025 load_timing_result.proxy_resolve_start);
2026 EXPECT_EQ(load_timing_result.request_start,
2027 load_timing_result.proxy_resolve_end);
2028 EXPECT_EQ(load_timing_result.request_start,
2029 load_timing_result.connect_timing.dns_start);
2030 EXPECT_EQ(load_timing_result.request_start,
2031 load_timing_result.connect_timing.dns_end);
2032 EXPECT_EQ(load_timing_result.request_start,
2033 load_timing_result.connect_timing.connect_start);
2034 EXPECT_EQ(load_timing_result.request_start,
2035 load_timing_result.connect_timing.connect_end);
2036
2037 // Other times should have been left null.
2038 TestLoadTimingNotReusedWithProxy(load_timing_result,
2039 CONNECT_TIMING_HAS_DNS_TIMES);
2040}
2041
2042// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502043TEST_F(URLRequestInterceptorTest,
2044 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592045 base::TimeTicks now = base::TimeTicks::Now();
2046 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2047 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2048 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2049
[email protected]2ca01e52013-10-31 22:05:192050 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502051 RunURLRequestInterceptorLoadTimingTest(
2052 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592053
2054 // Proxy times and connect times should all be replaced with request_start.
2055 EXPECT_EQ(load_timing_result.request_start,
2056 load_timing_result.proxy_resolve_start);
2057 EXPECT_EQ(load_timing_result.request_start,
2058 load_timing_result.proxy_resolve_end);
2059
2060 // Other times should have been left null.
2061 TestLoadTimingReusedWithProxy(load_timing_result);
2062}
2063
2064// Make sure that URLRequest correctly adjusts connect times when they're before
2065// |request_start|, due to reusing a connected socket. The connected socket is
2066// not considered reused in this test (May be a preconnect).
2067//
2068// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502069TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592070 base::TimeTicks now = base::TimeTicks::Now();
2071 LoadTimingInfo job_load_timing =
2072 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2073 job_load_timing.connect_timing.connect_start =
2074 now - base::TimeDelta::FromDays(1);
2075 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2076 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2077 job_load_timing.connect_timing.connect_end =
2078 now - base::TimeDelta::FromDays(4);
2079
[email protected]2ca01e52013-10-31 22:05:192080 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502081 RunURLRequestInterceptorLoadTimingTest(
2082 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592083
2084 // Connect times, and SSL times should be replaced with request_start.
2085 EXPECT_EQ(load_timing_result.request_start,
2086 load_timing_result.connect_timing.connect_start);
2087 EXPECT_EQ(load_timing_result.request_start,
2088 load_timing_result.connect_timing.ssl_start);
2089 EXPECT_EQ(load_timing_result.request_start,
2090 load_timing_result.connect_timing.ssl_end);
2091 EXPECT_EQ(load_timing_result.request_start,
2092 load_timing_result.connect_timing.connect_end);
2093
2094 // Other times should have been left null.
2095 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2096}
2097
2098// Make sure that URLRequest correctly adjusts connect times when they're before
2099// |request_start|, due to reusing a connected socket in the case that there
2100// are also proxy times. The connected socket is not considered reused in this
2101// test (May be a preconnect).
2102//
2103// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502104TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592105 base::TimeTicks now = base::TimeTicks::Now();
2106 LoadTimingInfo job_load_timing =
2107 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2108 job_load_timing.connect_timing.connect_start =
2109 now - base::TimeDelta::FromDays(1);
2110 job_load_timing.connect_timing.connect_end =
2111 now - base::TimeDelta::FromDays(2);
2112
[email protected]2ca01e52013-10-31 22:05:192113 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502114 RunURLRequestInterceptorLoadTimingTest(
2115 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592116
2117 // Connect times should be replaced with proxy_resolve_end.
2118 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2119 load_timing_result.connect_timing.connect_start);
2120 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2121 load_timing_result.connect_timing.connect_end);
2122
2123 // Other times should have been left null.
2124 TestLoadTimingNotReusedWithProxy(load_timing_result,
2125 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2126}
2127
[email protected]316c1e5e2012-09-12 15:17:442128// Check that two different URL requests have different identifiers.
2129TEST_F(URLRequestTest, Identifiers) {
2130 TestDelegate d;
2131 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362132 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362133 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:362134 std::unique_ptr<URLRequest> other_req(
davidben151423e2015-03-23 18:48:362135 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442136
mmenke19378d22014-09-09 04:12:592137 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442138}
2139
blundellb8163592f2015-12-16 14:22:422140#if defined(OS_IOS)
2141// TODO(droger): Check that a failure to connect to the proxy is reported to
2142// the network delegate. crbug.com/496743
2143#define MAYBE_NetworkDelegateProxyError DISABLED_NetworkDelegateProxyError
2144#else
2145#define MAYBE_NetworkDelegateProxyError NetworkDelegateProxyError
2146#endif
2147TEST_F(URLRequestTest, MAYBE_NetworkDelegateProxyError) {
[email protected]316c1e5e2012-09-12 15:17:442148 MockHostResolver host_resolver;
2149 host_resolver.rules()->AddSimulatedFailure("*");
2150
[email protected]ceefd7fd2012-11-29 00:36:242151 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442152 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2153
2154 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362155 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362156 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192157 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442158
[email protected]f7022f32014-08-21 16:32:192159 req->Start();
[email protected]255620da2013-08-19 13:14:292160 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442161
2162 // Check we see a failed request.
[email protected]d8fc4722014-06-13 13:17:152163 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:472164 EXPECT_FALSE(req->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:502165 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:442166
2167 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:012168 EXPECT_THAT(network_delegate.last_error(),
2169 IsError(ERR_PROXY_CONNECTION_FAILED));
[email protected]316c1e5e2012-09-12 15:17:442170 EXPECT_EQ(1, network_delegate.completed_requests());
2171}
2172
[email protected]cba24642014-08-15 20:49:592173// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442174// content is empty.
2175TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2176 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362177 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:362178 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192179 req->Start();
[email protected]255620da2013-08-19 13:14:292180 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442181 EXPECT_EQ("", d.data_received());
2182 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2183}
2184
[email protected]5033ab82013-03-22 20:17:462185// Make sure that SetPriority actually sets the URLRequest's priority
2186// correctly, both before and after start.
2187TEST_F(URLRequestTest, SetPriorityBasic) {
2188 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362189 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362190 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192191 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462192
[email protected]f7022f32014-08-21 16:32:192193 req->SetPriority(LOW);
2194 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462195
[email protected]f7022f32014-08-21 16:32:192196 req->Start();
2197 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462198
[email protected]f7022f32014-08-21 16:32:192199 req->SetPriority(MEDIUM);
2200 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462201}
2202
2203// Make sure that URLRequest calls SetPriority on a job before calling
2204// Start on it.
2205TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2206 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362207 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362208 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192209 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462210
mmenkeed0498b2015-12-08 23:20:422211 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362212 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422213 req.get(), &default_network_delegate_, &job_priority));
2214 AddTestInterceptor()->set_main_intercept_job(std::move(job));
2215 EXPECT_EQ(DEFAULT_PRIORITY, job_priority);
[email protected]5033ab82013-03-22 20:17:462216
[email protected]f7022f32014-08-21 16:32:192217 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462218
[email protected]f7022f32014-08-21 16:32:192219 req->Start();
mmenkeed0498b2015-12-08 23:20:422220 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462221}
2222
2223// Make sure that URLRequest passes on its priority updates to its
2224// job.
2225TEST_F(URLRequestTest, SetJobPriority) {
2226 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362227 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362228 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462229
mmenkeed0498b2015-12-08 23:20:422230 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362231 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422232 req.get(), &default_network_delegate_, &job_priority));
2233 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:462234
[email protected]f7022f32014-08-21 16:32:192235 req->SetPriority(LOW);
2236 req->Start();
mmenkeed0498b2015-12-08 23:20:422237 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:462238
[email protected]f7022f32014-08-21 16:32:192239 req->SetPriority(MEDIUM);
2240 EXPECT_EQ(MEDIUM, req->priority());
mmenkeed0498b2015-12-08 23:20:422241 EXPECT_EQ(MEDIUM, job_priority);
[email protected]5033ab82013-03-22 20:17:462242}
2243
[email protected]bb1c4662013-11-14 00:00:072244// Setting the IGNORE_LIMITS load flag should be okay if the priority
2245// is MAXIMUM_PRIORITY.
2246TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2247 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362248 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362249 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192250 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072251
mmenkeed0498b2015-12-08 23:20:422252 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:362253 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:422254 req.get(), &default_network_delegate_, &job_priority));
2255 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]bb1c4662013-11-14 00:00:072256
[email protected]f7022f32014-08-21 16:32:192257 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2258 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072259
[email protected]f7022f32014-08-21 16:32:192260 req->SetPriority(MAXIMUM_PRIORITY);
2261 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072262
[email protected]f7022f32014-08-21 16:32:192263 req->Start();
2264 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
mmenkeed0498b2015-12-08 23:20:422265 EXPECT_EQ(MAXIMUM_PRIORITY, job_priority);
[email protected]bb1c4662013-11-14 00:00:072266}
2267
nick5d570de92015-05-04 20:16:162268namespace {
2269
2270// Less verbose way of running a simple testserver for the tests below.
tommycli59a63432015-11-06 00:10:552271class LocalHttpTestServer : public EmbeddedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442272 public:
tommycli59a63432015-11-06 00:10:552273 explicit LocalHttpTestServer(const base::FilePath& document_root) {
2274 AddDefaultHandlers(document_root);
tommyclieae5f75f2015-11-05 19:07:272275 }
tommycli59a63432015-11-06 00:10:552276
2277 LocalHttpTestServer() { AddDefaultHandlers(base::FilePath()); }
2278};
tommyclieae5f75f2015-11-05 19:07:272279
nick5d570de92015-05-04 20:16:162280} // namespace
2281
[email protected]f2f31b32013-01-16 23:24:092282TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442283 LocalHttpTestServer test_server;
2284 ASSERT_TRUE(test_server.Start());
2285
2286 TestURLRequestContext context;
danakj8522a25b2016-04-16 00:17:362287 std::unique_ptr<DelayedCookieMonster> delayed_cm(new DelayedCookieMonster());
[email protected]90499482013-06-01 00:39:502288 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442289
2290 // Set up a cookie.
2291 {
2292 TestNetworkDelegate network_delegate;
2293 context.set_network_delegate(&network_delegate);
2294 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362295 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552296 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362297 &d));
[email protected]f7022f32014-08-21 16:32:192298 req->Start();
[email protected]255620da2013-08-19 13:14:292299 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442300 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2301 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2302 EXPECT_EQ(1, network_delegate.set_cookie_count());
2303 }
2304
2305 // Verify that the cookie is set.
2306 {
2307 TestNetworkDelegate network_delegate;
2308 context.set_network_delegate(&network_delegate);
2309 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362310 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552311 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192312 req->Start();
[email protected]255620da2013-08-19 13:14:292313 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442314
2315 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2316 != std::string::npos);
2317 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2318 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2319 }
2320}
2321
[email protected]f2f31b32013-01-16 23:24:092322TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442323 LocalHttpTestServer test_server;
2324 ASSERT_TRUE(test_server.Start());
2325
2326 // Set up a cookie.
2327 {
2328 TestNetworkDelegate network_delegate;
2329 default_context_.set_network_delegate(&network_delegate);
2330 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362331 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552332 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362333 &d));
[email protected]f7022f32014-08-21 16:32:192334 req->Start();
[email protected]255620da2013-08-19 13:14:292335 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442336 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2337 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2338 }
2339
2340 // Verify that the cookie is set.
2341 {
2342 TestNetworkDelegate network_delegate;
2343 default_context_.set_network_delegate(&network_delegate);
2344 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362345 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552346 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192347 req->Start();
[email protected]255620da2013-08-19 13:14:292348 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442349
2350 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2351 != std::string::npos);
2352 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2353 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2354 }
2355
2356 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2357 {
2358 TestNetworkDelegate network_delegate;
2359 default_context_.set_network_delegate(&network_delegate);
2360 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362361 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552362 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192363 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2364 req->Start();
[email protected]255620da2013-08-19 13:14:292365 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442366
2367 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2368 == std::string::npos);
2369
2370 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2371 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2372 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2373 }
2374}
2375
2376TEST_F(URLRequestTest, DoNotSaveCookies) {
2377 LocalHttpTestServer test_server;
2378 ASSERT_TRUE(test_server.Start());
2379
2380 // Set up a cookie.
2381 {
2382 TestNetworkDelegate network_delegate;
2383 default_context_.set_network_delegate(&network_delegate);
2384 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362385 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552386 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362387 &d));
[email protected]f7022f32014-08-21 16:32:192388 req->Start();
[email protected]255620da2013-08-19 13:14:292389 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442390
2391 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2392 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2393 EXPECT_EQ(1, network_delegate.set_cookie_count());
2394 }
2395
2396 // Try to set-up another cookie and update the previous cookie.
2397 {
2398 TestNetworkDelegate network_delegate;
2399 default_context_.set_network_delegate(&network_delegate);
2400 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362401 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552402 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362403 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192404 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2405 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442406
[email protected]255620da2013-08-19 13:14:292407 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442408
2409 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2410 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2411 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2412 EXPECT_EQ(0, network_delegate.set_cookie_count());
2413 }
2414
2415 // Verify the cookies weren't saved or updated.
2416 {
2417 TestNetworkDelegate network_delegate;
2418 default_context_.set_network_delegate(&network_delegate);
2419 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362420 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552421 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192422 req->Start();
[email protected]255620da2013-08-19 13:14:292423 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442424
2425 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2426 == std::string::npos);
2427 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2428 != std::string::npos);
2429
2430 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2431 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2432 EXPECT_EQ(0, network_delegate.set_cookie_count());
2433 }
2434}
2435
2436TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2437 LocalHttpTestServer test_server;
2438 ASSERT_TRUE(test_server.Start());
2439
2440 // Set up a cookie.
2441 {
2442 TestNetworkDelegate network_delegate;
2443 default_context_.set_network_delegate(&network_delegate);
2444 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362445 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552446 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362447 &d));
[email protected]f7022f32014-08-21 16:32:192448 req->Start();
[email protected]255620da2013-08-19 13:14:292449 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442450
2451 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2452 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2453 }
2454
2455 // Verify that the cookie is set.
2456 {
2457 TestNetworkDelegate network_delegate;
2458 default_context_.set_network_delegate(&network_delegate);
2459 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362460 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552461 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192462 req->Start();
[email protected]255620da2013-08-19 13:14:292463 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442464
2465 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2466 != std::string::npos);
2467
2468 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2469 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2470 }
2471
2472 // Verify that the cookie isn't sent.
2473 {
2474 TestNetworkDelegate network_delegate;
2475 default_context_.set_network_delegate(&network_delegate);
2476 TestDelegate d;
2477 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362478 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552479 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192480 req->Start();
[email protected]255620da2013-08-19 13:14:292481 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442482
2483 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2484 == std::string::npos);
2485
[email protected]22e045f2013-09-20 03:54:032486 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442487 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2488 }
2489}
2490
marqf14fff8d2015-12-02 15:52:292491// TODO(crbug.com/564656) This test is flaky on iOS.
2492#if defined(OS_IOS)
2493#define MAYBE_DoNotSaveCookies_ViaPolicy FLAKY_DoNotSaveCookies_ViaPolicy
2494#else
2495#define MAYBE_DoNotSaveCookies_ViaPolicy DoNotSaveCookies_ViaPolicy
2496#endif
[email protected]316c1e5e2012-09-12 15:17:442497TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2498 LocalHttpTestServer test_server;
2499 ASSERT_TRUE(test_server.Start());
2500
2501 // Set up a cookie.
2502 {
2503 TestNetworkDelegate network_delegate;
2504 default_context_.set_network_delegate(&network_delegate);
2505 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362506 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552507 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362508 &d));
[email protected]f7022f32014-08-21 16:32:192509 req->Start();
[email protected]255620da2013-08-19 13:14:292510 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442511
2512 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2513 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2514 }
2515
2516 // Try to set-up another cookie and update the previous cookie.
2517 {
2518 TestNetworkDelegate network_delegate;
2519 default_context_.set_network_delegate(&network_delegate);
2520 TestDelegate d;
2521 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362522 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552523 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362524 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192525 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442526
[email protected]255620da2013-08-19 13:14:292527 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442528
2529 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2530 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2531 }
2532
2533 // Verify the cookies weren't saved or updated.
2534 {
2535 TestNetworkDelegate network_delegate;
2536 default_context_.set_network_delegate(&network_delegate);
2537 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362538 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552539 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192540 req->Start();
[email protected]255620da2013-08-19 13:14:292541 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442542
2543 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2544 == std::string::npos);
2545 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2546 != std::string::npos);
2547
2548 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2549 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2550 }
2551}
2552
2553TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2554 LocalHttpTestServer test_server;
2555 ASSERT_TRUE(test_server.Start());
2556
2557 // Set up an empty cookie.
2558 {
2559 TestNetworkDelegate network_delegate;
2560 default_context_.set_network_delegate(&network_delegate);
2561 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362562 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552563 test_server.GetURL("/set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192564 req->Start();
[email protected]255620da2013-08-19 13:14:292565 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442566
2567 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2568 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2569 EXPECT_EQ(0, network_delegate.set_cookie_count());
2570 }
2571}
2572
2573TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2574 LocalHttpTestServer test_server;
2575 ASSERT_TRUE(test_server.Start());
2576
2577 // Set up a cookie.
2578 {
2579 TestNetworkDelegate network_delegate;
2580 default_context_.set_network_delegate(&network_delegate);
2581 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362582 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552583 test_server.GetURL("/set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362584 &d));
[email protected]f7022f32014-08-21 16:32:192585 req->Start();
[email protected]255620da2013-08-19 13:14:292586 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442587
2588 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2589 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2590 }
2591
2592 // Verify that the cookie is set.
2593 {
2594 TestNetworkDelegate network_delegate;
2595 default_context_.set_network_delegate(&network_delegate);
2596 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362597 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552598 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192599 req->Start();
[email protected]255620da2013-08-19 13:14:292600 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442601
2602 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2603 != std::string::npos);
2604
2605 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2606 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2607 }
2608
2609 // Verify that the cookie isn't sent.
2610 {
2611 TestNetworkDelegate network_delegate;
2612 default_context_.set_network_delegate(&network_delegate);
2613 TestDelegate d;
2614 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
danakj8522a25b2016-04-16 00:17:362615 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552616 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192617 req->Start();
[email protected]255620da2013-08-19 13:14:292618 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442619
2620 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2621 == std::string::npos);
2622
[email protected]22e045f2013-09-20 03:54:032623 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442624 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2625 }
2626}
2627
2628TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2629 LocalHttpTestServer test_server;
2630 ASSERT_TRUE(test_server.Start());
2631
2632 // Set up a cookie.
2633 {
2634 TestNetworkDelegate network_delegate;
2635 default_context_.set_network_delegate(&network_delegate);
2636 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362637 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552638 test_server.GetURL("/set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362639 &d));
[email protected]f7022f32014-08-21 16:32:192640 req->Start();
[email protected]255620da2013-08-19 13:14:292641 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442642
2643 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2644 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2645 }
2646
2647 // Try to set-up another cookie and update the previous cookie.
2648 {
2649 TestNetworkDelegate network_delegate;
2650 default_context_.set_network_delegate(&network_delegate);
2651 TestDelegate d;
2652 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
danakj8522a25b2016-04-16 00:17:362653 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552654 test_server.GetURL("/set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362655 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192656 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442657
[email protected]255620da2013-08-19 13:14:292658 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442659
2660 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2661 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2662 }
2663
2664 // Verify the cookies weren't saved or updated.
2665 {
2666 TestNetworkDelegate network_delegate;
2667 default_context_.set_network_delegate(&network_delegate);
2668 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362669 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:552670 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192671 req->Start();
[email protected]255620da2013-08-19 13:14:292672 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442673
2674 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2675 == std::string::npos);
2676 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2677 != std::string::npos);
2678
2679 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2680 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2681 }
2682}
2683
mkwstc5fa7762016-03-28 09:28:232684TEST_F(URLRequestTest, SameSiteCookies) {
mkwst3f3daac2015-02-26 20:15:262685 LocalHttpTestServer test_server;
2686 ASSERT_TRUE(test_server.Start());
2687
mkwst202534e32016-01-15 16:07:152688 TestNetworkDelegate network_delegate;
mkwst202534e32016-01-15 16:07:152689 default_context_.set_network_delegate(&network_delegate);
2690
mkwstf71d0bd2016-03-21 14:15:242691 const std::string kHost = "example.test";
2692 const std::string kSubHost = "subdomain.example.test";
2693 const std::string kCrossHost = "cross-origin.test";
2694
2695 // Set up two 'SameSite' cookies on 'example.test'
mkwst3f3daac2015-02-26 20:15:262696 {
mkwst3f3daac2015-02-26 20:15:262697 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362698 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242699 test_server.GetURL(kHost,
2700 "/set-cookie?StrictSameSiteCookie=1;SameSite=Strict&"
2701 "LaxSameSiteCookie=1;SameSite=Lax"),
davidben151423e2015-03-23 18:48:362702 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262703 req->Start();
2704 base::RunLoop().Run();
2705 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2706 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
mkwstf71d0bd2016-03-21 14:15:242707 EXPECT_EQ(2, network_delegate.set_cookie_count());
mkwst3f3daac2015-02-26 20:15:262708 }
2709
mkwstf71d0bd2016-03-21 14:15:242710 // Verify that both cookies are sent for same-site requests.
mkwst3f3daac2015-02-26 20:15:262711 {
mkwst3f3daac2015-02-26 20:15:262712 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362713 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242714 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2715 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2716 req->set_initiator(url::Origin(test_server.GetURL(kHost, "/")));
mkwst3f3daac2015-02-26 20:15:262717 req->Start();
2718 base::RunLoop().Run();
2719
mkwstf71d0bd2016-03-21 14:15:242720 EXPECT_NE(std::string::npos,
2721 d.data_received().find("StrictSameSiteCookie=1"));
2722 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262723 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2724 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2725 }
2726
mkwstf71d0bd2016-03-21 14:15:242727 // Verify that both cookies are sent for same-registrable-domain requests.
mkwst3f3daac2015-02-26 20:15:262728 {
mkwst3f3daac2015-02-26 20:15:262729 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362730 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242731 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2732 req->set_first_party_for_cookies(test_server.GetURL(kSubHost, "/"));
2733 req->set_initiator(url::Origin(test_server.GetURL(kSubHost, "/")));
mkwst202534e32016-01-15 16:07:152734 req->Start();
2735 base::RunLoop().Run();
2736
mkwstf71d0bd2016-03-21 14:15:242737 EXPECT_NE(std::string::npos,
2738 d.data_received().find("StrictSameSiteCookie=1"));
2739 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152740 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2741 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2742 }
2743
mkwstf71d0bd2016-03-21 14:15:242744 // Verify that neither cookie is not sent for cross-site requests.
2745 {
2746 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362747 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242748 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2749 req->set_first_party_for_cookies(test_server.GetURL(kCrossHost, "/"));
2750 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2751 req->Start();
2752 base::RunLoop().Run();
2753
2754 EXPECT_EQ(std::string::npos,
2755 d.data_received().find("StrictSameSiteCookie=1"));
2756 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
2757 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2758 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2759 }
2760
2761 // Verify that the lax cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152762 // method is "safe".
2763 {
2764 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362765 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242766 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2767 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2768 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
2769 req->set_method("GET");
mkwst202534e32016-01-15 16:07:152770 req->Start();
2771 base::RunLoop().Run();
2772
mkwstf71d0bd2016-03-21 14:15:242773 EXPECT_EQ(std::string::npos,
2774 d.data_received().find("StrictSameSiteCookie=1"));
2775 EXPECT_NE(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst202534e32016-01-15 16:07:152776 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2777 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2778 }
2779
mkwstf71d0bd2016-03-21 14:15:242780 // Verify that neither cookie is sent for cross-site initiators when the
mkwst202534e32016-01-15 16:07:152781 // method is unsafe (e.g. POST).
2782 {
2783 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362784 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
mkwstf71d0bd2016-03-21 14:15:242785 test_server.GetURL(kHost, "/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2786 req->set_first_party_for_cookies(test_server.GetURL(kHost, "/"));
2787 req->set_initiator(url::Origin(test_server.GetURL(kCrossHost, "/")));
mkwst202534e32016-01-15 16:07:152788 req->set_method("POST");
mkwst3f3daac2015-02-26 20:15:262789 req->Start();
2790 base::RunLoop().Run();
2791
mkwstf71d0bd2016-03-21 14:15:242792 EXPECT_EQ(std::string::npos,
2793 d.data_received().find("StrictSameSiteCookie=1"));
2794 EXPECT_EQ(std::string::npos, d.data_received().find("LaxSameSiteCookie=1"));
mkwst3f3daac2015-02-26 20:15:262795 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2796 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2797 }
2798}
2799
estark557a5eb82015-12-01 22:57:102800// Tests that __Secure- cookies can't be set on non-secure origins.
estarkcd39c11f2015-10-19 19:46:362801TEST_F(URLRequestTest, SecureCookiePrefixOnNonsecureOrigin) {
tommycli59a63432015-11-06 00:10:552802 EmbeddedTestServer http_server;
2803 http_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362804 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552805 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2806 https_server.AddDefaultHandlers(
2807 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2808 ASSERT_TRUE(http_server.Start());
2809 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362810
estarkb15166b2015-12-18 16:56:382811 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362812 TestURLRequestContext context(true);
2813 context.set_network_delegate(&network_delegate);
2814 context.Init();
2815
estarkb15166b2015-12-18 16:56:382816 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362817 {
2818 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362819 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102820 http_server.GetURL("/set-cookie?__Secure-nonsecure-origin=1;Secure"),
estarkcd39c11f2015-10-19 19:46:362821 DEFAULT_PRIORITY, &d));
2822 req->Start();
2823 base::RunLoop().Run();
2824 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2825 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2826 }
2827
2828 // Verify that the cookie is not set.
2829 {
2830 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362831 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552832 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362833 req->Start();
2834 base::RunLoop().Run();
2835
jww79aceda2015-12-07 01:56:342836 EXPECT_EQ(d.data_received().find("__Secure-nonsecure-origin=1"),
2837 std::string::npos);
estarkcd39c11f2015-10-19 19:46:362838 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2839 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2840 }
2841}
2842
estarkb15166b2015-12-18 16:56:382843TEST_F(URLRequestTest, SecureCookiePrefixNonsecure) {
tommycli59a63432015-11-06 00:10:552844 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2845 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362846 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552847 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362848
2849 TestNetworkDelegate network_delegate;
2850 TestURLRequestContext context(true);
2851 context.set_network_delegate(&network_delegate);
2852 context.Init();
2853
estarkb15166b2015-12-18 16:56:382854 // Try to set a non-Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362855 {
2856 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362857 std::unique_ptr<URLRequest> req(
estark557a5eb82015-12-01 22:57:102858 context.CreateRequest(https_server.GetURL("/set-cookie?__Secure-foo=1"),
tommycli59a63432015-11-06 00:10:552859 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362860 req->Start();
2861 base::RunLoop().Run();
2862 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2863 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2864 }
2865
2866 // Verify that the cookie is not set.
2867 {
2868 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362869 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552870 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362871 req->Start();
2872 base::RunLoop().Run();
2873
jww79aceda2015-12-07 01:56:342874 EXPECT_EQ(d.data_received().find("__Secure-foo=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362875 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2876 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2877 }
2878}
2879
estarkb15166b2015-12-18 16:56:382880TEST_F(URLRequestTest, SecureCookiePrefixSecure) {
tommycli59a63432015-11-06 00:10:552881 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2882 https_server.AddDefaultHandlers(
estarkcd39c11f2015-10-19 19:46:362883 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
tommycli59a63432015-11-06 00:10:552884 ASSERT_TRUE(https_server.Start());
estarkcd39c11f2015-10-19 19:46:362885
estarkb15166b2015-12-18 16:56:382886 TestNetworkDelegate network_delegate;
estarkcd39c11f2015-10-19 19:46:362887 TestURLRequestContext context(true);
2888 context.set_network_delegate(&network_delegate);
2889 context.Init();
2890
estarkb15166b2015-12-18 16:56:382891 // Try to set a Secure __Secure- cookie.
estarkcd39c11f2015-10-19 19:46:362892 {
2893 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362894 std::unique_ptr<URLRequest> req(context.CreateRequest(
estark557a5eb82015-12-01 22:57:102895 https_server.GetURL("/set-cookie?__Secure-bar=1;Secure"),
tommycli59a63432015-11-06 00:10:552896 DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362897 req->Start();
2898 base::RunLoop().Run();
2899 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2900 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2901 }
2902
2903 // Verify that the cookie is set.
2904 {
2905 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362906 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:552907 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
estarkcd39c11f2015-10-19 19:46:362908 req->Start();
2909 base::RunLoop().Run();
2910
jww79aceda2015-12-07 01:56:342911 EXPECT_NE(d.data_received().find("__Secure-bar=1"), std::string::npos);
2912 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2913 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2914 }
2915}
2916
2917// Tests that secure cookies can't be set on non-secure origins if strict secure
2918// cookies are enabled.
2919TEST_F(URLRequestTest, StrictSecureCookiesOnNonsecureOrigin) {
2920 EmbeddedTestServer http_server;
2921 http_server.AddDefaultHandlers(
2922 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2923 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2924 https_server.AddDefaultHandlers(
2925 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2926 ASSERT_TRUE(http_server.Start());
2927 ASSERT_TRUE(https_server.Start());
2928
2929 TestExperimentalFeaturesNetworkDelegate network_delegate;
2930 TestURLRequestContext context(true);
2931 context.set_network_delegate(&network_delegate);
2932 context.Init();
2933
2934 // Try to set a Secure cookie, with experimental features enabled.
2935 {
2936 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362937 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342938 http_server.GetURL("/set-cookie?nonsecure-origin=1;Secure"),
2939 DEFAULT_PRIORITY, &d));
2940 req->Start();
2941 base::RunLoop().Run();
2942 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2943 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2944 }
2945
2946 // Verify that the cookie is not set.
2947 {
2948 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362949 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342950 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2951 req->Start();
2952 base::RunLoop().Run();
2953
2954 EXPECT_EQ(d.data_received().find("nonsecure-origin=1"), std::string::npos);
2955 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2956 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2957 }
2958}
2959
2960// Tests that secure cookies can be set on secure origins even if strict secure
2961// cookies are enabled.
2962TEST_F(URLRequestTest, StrictSecureCookiesOnSecureOrigin) {
2963 EmbeddedTestServer https_server(EmbeddedTestServer::TYPE_HTTPS);
2964 https_server.AddDefaultHandlers(
2965 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
2966 ASSERT_TRUE(https_server.Start());
2967
2968 TestExperimentalFeaturesNetworkDelegate network_delegate;
2969 TestURLRequestContext context(true);
2970 context.set_network_delegate(&network_delegate);
2971 context.Init();
2972
2973 // Try to set a Secure cookie, with experimental features enabled.
2974 {
2975 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362976 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342977 https_server.GetURL("/set-cookie?secure-origin=1;Secure"),
2978 DEFAULT_PRIORITY, &d));
2979 req->Start();
2980 base::RunLoop().Run();
2981 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2982 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2983 }
2984
2985 // Verify that the cookie is not set.
2986 {
2987 TestDelegate d;
danakj8522a25b2016-04-16 00:17:362988 std::unique_ptr<URLRequest> req(context.CreateRequest(
jww79aceda2015-12-07 01:56:342989 https_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
2990 req->Start();
2991 base::RunLoop().Run();
2992
2993 EXPECT_NE(d.data_received().find("secure-origin=1"), std::string::npos);
estarkcd39c11f2015-10-19 19:46:362994 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2995 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2996 }
2997}
2998
mmenkefb18c772015-09-30 22:22:502999// Tests that a request is cancelled while entering suspend mode. Uses mocks
3000// rather than a spawned test server because the connection used to talk to
3001// the test server is affected by entering suspend mode on Android.
3002TEST_F(URLRequestTest, CancelOnSuspend) {
3003 TestPowerMonitorSource* power_monitor_source = new TestPowerMonitorSource();
danakj8522a25b2016-04-16 00:17:363004 base::PowerMonitor power_monitor(base::WrapUnique(power_monitor_source));
mmenkefb18c772015-09-30 22:22:503005
3006 URLRequestFailedJob::AddUrlHandler();
3007
3008 TestDelegate d;
3009 // Request that just hangs.
3010 GURL url(URLRequestFailedJob::GetMockHttpUrl(ERR_IO_PENDING));
danakj8522a25b2016-04-16 00:17:363011 std::unique_ptr<URLRequest> r(
mmenkefb18c772015-09-30 22:22:503012 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
3013 r->Start();
3014
3015 power_monitor_source->Suspend();
3016 // Wait for the suspend notification to cause the request to fail.
3017 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503018 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenkefb18c772015-09-30 22:22:503019 EXPECT_TRUE(d.request_failed());
3020 EXPECT_EQ(1, default_network_delegate_.completed_requests());
3021
3022 URLRequestFilter::GetInstance()->ClearHandlers();
3023
3024 // Shouldn't be needed, but just in case.
3025 power_monitor_source->Resume();
3026}
3027
[email protected]5095cd72012-11-01 10:29:163028// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
3029// value for the |fixed_date| argument given to the constructor.
3030class FixedDateNetworkDelegate : public TestNetworkDelegate {
3031 public:
3032 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
3033 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:203034 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:163035
[email protected]cba24642014-08-15 20:49:593036 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:203037 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593038 URLRequest* request,
3039 const CompletionCallback& callback,
3040 const HttpResponseHeaders* original_response_headers,
3041 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:133042 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163043
3044 private:
3045 std::string fixed_date_;
3046
3047 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3048};
3049
3050int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593051 URLRequest* request,
3052 const CompletionCallback& callback,
3053 const HttpResponseHeaders* original_response_headers,
3054 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163055 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593056 HttpResponseHeaders* new_response_headers =
3057 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163058
3059 new_response_headers->RemoveHeader("Date");
3060 new_response_headers->AddHeader("Date: " + fixed_date_);
3061
3062 *override_response_headers = new_response_headers;
3063 return TestNetworkDelegate::OnHeadersReceived(request,
3064 callback,
3065 original_response_headers,
[email protected]5f714132014-03-26 10:41:163066 override_response_headers,
3067 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163068}
3069
3070// Test that cookie expiration times are adjusted for server/client clock
3071// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3072// headers by defaulting to GMT. (crbug.com/135131)
3073TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3074 LocalHttpTestServer test_server;
3075 ASSERT_TRUE(test_server.Start());
3076
3077 // Set up an expired cookie.
3078 {
3079 TestNetworkDelegate network_delegate;
3080 default_context_.set_network_delegate(&network_delegate);
3081 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363082 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193083 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553084 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363085 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193086 req->Start();
[email protected]255620da2013-08-19 13:14:293087 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163088 }
3089 // Verify that the cookie is not set.
3090 {
3091 TestNetworkDelegate network_delegate;
3092 default_context_.set_network_delegate(&network_delegate);
3093 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363094 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553095 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193096 req->Start();
[email protected]255620da2013-08-19 13:14:293097 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163098
3099 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3100 }
3101 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3102 {
3103 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3104 default_context_.set_network_delegate(&network_delegate);
3105 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363106 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193107 test_server.GetURL(
tommycli59a63432015-11-06 00:10:553108 "/set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:363109 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193110 req->Start();
[email protected]255620da2013-08-19 13:14:293111 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163112 }
3113 // Verify that the cookie is set.
3114 {
3115 TestNetworkDelegate network_delegate;
3116 default_context_.set_network_delegate(&network_delegate);
3117 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363118 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553119 test_server.GetURL("/echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193120 req->Start();
[email protected]255620da2013-08-19 13:14:293121 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163122
3123 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3124 }
3125}
3126
3127
[email protected]316c1e5e2012-09-12 15:17:443128// Check that it is impossible to change the referrer in the extra headers of
3129// an URLRequest.
3130TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3131 LocalHttpTestServer test_server;
3132 ASSERT_TRUE(test_server.Start());
3133
3134 // If extra headers contain referer and the request contains a referer,
3135 // only the latter shall be respected.
3136 {
3137 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363138 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553139 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193140 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443141
3142 HttpRequestHeaders headers;
3143 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193144 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443145
[email protected]f7022f32014-08-21 16:32:193146 req->Start();
[email protected]255620da2013-08-19 13:14:293147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443148
3149 EXPECT_EQ("http://foo.com/", d.data_received());
3150 }
3151
3152 // If extra headers contain a referer but the request does not, no referer
3153 // shall be sent in the header.
3154 {
3155 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363156 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553157 test_server.GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:443158
3159 HttpRequestHeaders headers;
3160 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193161 req->SetExtraRequestHeaders(headers);
3162 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443163
[email protected]f7022f32014-08-21 16:32:193164 req->Start();
[email protected]255620da2013-08-19 13:14:293165 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443166
3167 EXPECT_EQ("None", d.data_received());
3168 }
3169}
3170
[email protected]b89290212009-08-14 22:37:353171class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113172 public:
mmenke9f2ec60c2015-06-01 20:59:473173 URLRequestTestHTTP() : test_server_(base::FilePath(kTestFilePath)) {}
[email protected]95409e12010-08-17 20:07:113174
[email protected]b89290212009-08-14 22:37:353175 protected:
[email protected]21184962011-10-26 00:50:303176 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3177 // |request_method| is the method to use for the initial request.
3178 // |redirect_method| is the method that is expected to be used for the second
3179 // request, after redirection.
3180 // If |include_data| is true, data is uploaded with the request. The
3181 // response body is expected to match it exactly, if and only if
3182 // |request_method| == |redirect_method|.
3183 void HTTPRedirectMethodTest(const GURL& redirect_url,
3184 const std::string& request_method,
3185 const std::string& redirect_method,
3186 bool include_data) {
3187 static const char kData[] = "hello world";
3188 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363189 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:363190 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193191 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303192 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073193 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303194 HttpRequestHeaders headers;
3195 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513196 base::SizeTToString(arraysize(kData) - 1));
svaldez5b3a8972015-10-09 23:23:543197 headers.SetHeader(HttpRequestHeaders::kContentType, "text/plain");
[email protected]f7022f32014-08-21 16:32:193198 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303199 }
[email protected]f7022f32014-08-21 16:32:193200 req->Start();
[email protected]255620da2013-08-19 13:14:293201 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193202 EXPECT_EQ(redirect_method, req->method());
maksim.sisovb53724b52016-09-16 05:30:503203 EXPECT_EQ(OK, d.request_status());
[email protected]21184962011-10-26 00:50:303204 if (include_data) {
3205 if (request_method == redirect_method) {
svaldez5b3a8972015-10-09 23:23:543206 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3207 HttpRequestHeaders::kContentLength));
3208 EXPECT_TRUE(req->extra_request_headers().HasHeader(
3209 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303210 EXPECT_EQ(kData, d.data_received());
3211 } else {
svaldez5b3a8972015-10-09 23:23:543212 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3213 HttpRequestHeaders::kContentLength));
3214 EXPECT_FALSE(req->extra_request_headers().HasHeader(
3215 HttpRequestHeaders::kContentType));
[email protected]21184962011-10-26 00:50:303216 EXPECT_NE(kData, d.data_received());
3217 }
3218 }
3219 if (HasFailure())
3220 LOG(WARNING) << "Request method was: " << request_method;
3221 }
3222
jww5fe460ff2015-03-28 00:22:513223 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3224 // |request_method| is the method to use for the initial request.
3225 // |redirect_method| is the method that is expected to be used for the second
3226 // request, after redirection.
3227 // |origin_value| is the expected value for the Origin header after
3228 // redirection. If empty, expects that there will be no Origin header.
3229 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
3230 const std::string& request_method,
3231 const std::string& redirect_method,
3232 const std::string& origin_value) {
3233 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363234 std::unique_ptr<URLRequest> req(
jww5fe460ff2015-03-28 00:22:513235 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3236 req->set_method(request_method);
3237 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
3238 redirect_url.GetOrigin().spec(), false);
3239 req->Start();
3240
3241 base::RunLoop().Run();
3242
3243 EXPECT_EQ(redirect_method, req->method());
3244 // Note that there is no check for request success here because, for
3245 // purposes of testing, the request very well may fail. For example, if the
3246 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
3247 // origin, there is not an HTTPS server in this unit test framework, so the
3248 // request would fail. However, that's fine, as long as the request headers
3249 // are in order and pass the checks below.
3250 if (origin_value.empty()) {
3251 EXPECT_FALSE(
3252 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
3253 } else {
3254 std::string origin_header;
3255 EXPECT_TRUE(req->extra_request_headers().GetHeader(
3256 HttpRequestHeaders::kOrigin, &origin_header));
3257 EXPECT_EQ(origin_value, origin_header);
3258 }
3259 }
3260
[email protected]762d2db2010-01-11 19:03:013261 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013262 const int kMsgSize = 20000; // multiple of 10
3263 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483264 char* uploadBytes = new char[kMsgSize+1];
3265 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013266 char marker = 'a';
3267 for (int idx = 0; idx < kMsgSize/10; idx++) {
3268 memcpy(ptr, "----------", 10);
3269 ptr += 10;
3270 if (idx % 100 == 0) {
3271 ptr--;
3272 *ptr++ = marker;
3273 if (++marker > 'z')
3274 marker = 'a';
3275 }
3276 }
3277 uploadBytes[kMsgSize] = '\0';
3278
[email protected]762d2db2010-01-11 19:03:013279 for (int i = 0; i < kIterations; ++i) {
3280 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363281 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553282 test_server_.GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193283 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013284
mmenkecbc2b712014-10-09 20:29:073285 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013286
[email protected]f7022f32014-08-21 16:32:193287 r->Start();
3288 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013289
[email protected]255620da2013-08-19 13:14:293290 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013291
maksim.sisovb53724b52016-09-16 05:30:503292 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
3293 << d.request_status();
[email protected]762d2db2010-01-11 19:03:013294
3295 EXPECT_FALSE(d.received_data_before_response());
3296 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013297 }
3298 delete[] uploadBytes;
3299 }
3300
[email protected]ede03212012-09-07 12:52:263301 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343302 TestDelegate d;
danakj8522a25b2016-04-16 00:17:363303 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:553304 test_server_.GetURL("/set-many-cookies?" +
davidben151423e2015-03-23 18:48:363305 base::IntToString(num_cookies)),
3306 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:343307
[email protected]f7022f32014-08-21 16:32:193308 r->Start();
3309 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343310
[email protected]255620da2013-08-19 13:14:293311 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343312
maksim.sisovb53724b52016-09-16 05:30:503313 if (d.request_status() != OK) {
3314 EXPECT_EQ(ERR_RESPONSE_HEADERS_TOO_BIG, d.request_status());
3315 return false;
3316 }
[email protected]263163f2012-06-14 22:40:343317
maksim.sisovb53724b52016-09-16 05:30:503318 return true;
[email protected]263163f2012-06-14 22:40:343319 }
3320
tommycli59a63432015-11-06 00:10:553321 LocalHttpTestServer* http_test_server() { return &test_server_; }
bengr1bf8e942014-11-07 01:36:503322
tommycli59a63432015-11-06 00:10:553323 private:
[email protected]1700c6a2012-02-22 18:07:073324 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353325};
3326
tommycli59a63432015-11-06 00:10:553327namespace {
3328
danakj8522a25b2016-04-16 00:17:363329std::unique_ptr<test_server::HttpResponse> HandleRedirectConnect(
tommycli59a63432015-11-06 00:10:553330 const test_server::HttpRequest& request) {
3331 if (request.headers.find("Host") == request.headers.end() ||
3332 request.headers.at("Host") != "www.redirect.com" ||
3333 request.method != test_server::METHOD_CONNECT) {
3334 return nullptr;
3335 }
3336
danakj8522a25b2016-04-16 00:17:363337 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:553338 new test_server::BasicHttpResponse);
3339 http_response->set_code(HTTP_FOUND);
3340 http_response->AddCustomHeader("Location",
3341 "http://www.destination.com/foo.js");
dchengc7eeda422015-12-26 03:56:483342 return std::move(http_response);
tommycli59a63432015-11-06 00:10:553343}
3344
3345} // namespace
3346
nharperb7441ef2016-01-25 23:54:143347class TestSSLConfigService : public SSLConfigService {
3348 public:
3349 TestSSLConfigService(bool ev_enabled,
3350 bool online_rev_checking,
3351 bool rev_checking_required_local_anchors,
3352 bool token_binding_enabled)
3353 : ev_enabled_(ev_enabled),
3354 online_rev_checking_(online_rev_checking),
3355 rev_checking_required_local_anchors_(
3356 rev_checking_required_local_anchors),
3357 token_binding_enabled_(token_binding_enabled),
davidben5a312152016-06-27 22:11:473358 min_version_(kDefaultSSLVersionMin) {}
nharperb7441ef2016-01-25 23:54:143359
3360 void set_min_version(uint16_t version) { min_version_ = version; }
3361
nharperb7441ef2016-01-25 23:54:143362 // SSLConfigService:
3363 void GetSSLConfig(SSLConfig* config) override {
3364 *config = SSLConfig();
3365 config->rev_checking_enabled = online_rev_checking_;
3366 config->verify_ev_cert = ev_enabled_;
3367 config->rev_checking_required_local_anchors =
3368 rev_checking_required_local_anchors_;
nharperb7441ef2016-01-25 23:54:143369 if (min_version_) {
3370 config->version_min = min_version_;
3371 }
3372 if (token_binding_enabled_) {
3373 config->token_binding_params.push_back(TB_PARAM_ECDSAP256);
3374 }
3375 }
3376
3377 protected:
3378 ~TestSSLConfigService() override {}
3379
3380 private:
3381 const bool ev_enabled_;
3382 const bool online_rev_checking_;
3383 const bool rev_checking_required_local_anchors_;
3384 const bool token_binding_enabled_;
3385 uint16_t min_version_;
nharperb7441ef2016-01-25 23:54:143386};
3387
3388// TODO(svaldez): Update tests to use EmbeddedTestServer.
3389#if !defined(OS_IOS)
3390class TokenBindingURLRequestTest : public URLRequestTestHTTP {
3391 public:
3392 void SetUp() override {
3393 default_context_.set_ssl_config_service(
3394 new TestSSLConfigService(false, false, false, true));
3395 channel_id_service_.reset(new ChannelIDService(
3396 new DefaultChannelIDStore(NULL), base::ThreadTaskRunnerHandle::Get()));
3397 default_context_.set_channel_id_service(channel_id_service_.get());
3398 URLRequestTestHTTP::SetUp();
3399 }
3400
3401 protected:
danakj8522a25b2016-04-16 00:17:363402 std::unique_ptr<ChannelIDService> channel_id_service_;
nharperb7441ef2016-01-25 23:54:143403};
3404
3405TEST_F(TokenBindingURLRequestTest, TokenBindingTest) {
3406 SpawnedTestServer::SSLOptions ssl_options;
3407 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3408 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3409 ssl_options,
3410 base::FilePath(kTestFilePath));
3411 ASSERT_TRUE(https_test_server.Start());
3412
3413 TestDelegate d;
3414 {
danakj8522a25b2016-04-16 00:17:363415 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
nharperb7441ef2016-01-25 23:54:143416 https_test_server.GetURL("tokbind-ekm"), DEFAULT_PRIORITY, &d));
3417 r->Start();
3418 EXPECT_TRUE(r->is_pending());
3419
3420 base::RunLoop().Run();
3421
maksim.sisovb53724b52016-09-16 05:30:503422 EXPECT_EQ(OK, d.request_status());
nharperb7441ef2016-01-25 23:54:143423
3424 HttpRequestHeaders headers;
3425 std::string token_binding_header, token_binding_message;
3426 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3427 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3428 &token_binding_header));
3429 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353430 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperb7441ef2016-01-25 23:54:143431 &token_binding_message));
nharperd6e65822016-03-30 23:05:483432 std::vector<TokenBinding> token_bindings;
3433 ASSERT_TRUE(
3434 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3435 ASSERT_EQ(1ull, token_bindings.size());
nharperb7441ef2016-01-25 23:54:143436
3437 EXPECT_GT(d.bytes_received(), 0);
3438 std::string ekm = d.data_received();
3439
nharperd6e65822016-03-30 23:05:483440 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353441 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3442 token_bindings[0].signature,
3443 TokenBindingType::PROVIDED, ekm));
nharperb7441ef2016-01-25 23:54:143444 }
3445}
nharperd6e65822016-03-30 23:05:483446
3447TEST_F(TokenBindingURLRequestTest, ForwardTokenBinding) {
3448 SpawnedTestServer::SSLOptions ssl_options;
3449 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3450 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3451 ssl_options,
3452 base::FilePath(kTestFilePath));
3453 ASSERT_TRUE(https_test_server.Start());
3454
3455 TestDelegate d;
3456 {
3457 GURL redirect_url =
3458 https_test_server.GetURL("forward-tokbind?/tokbind-ekm");
danakj8522a25b2016-04-16 00:17:363459 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483460 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3461 r->Start();
3462 EXPECT_TRUE(r->is_pending());
3463
3464 base::RunLoop().Run();
3465
maksim.sisovb53724b52016-09-16 05:30:503466 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483467
3468 HttpRequestHeaders headers;
3469 std::string token_binding_header, token_binding_message;
3470 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3471 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3472 &token_binding_header));
3473 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353474 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483475 &token_binding_message));
3476 std::vector<TokenBinding> token_bindings;
3477 ASSERT_TRUE(
3478 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3479 ASSERT_EQ(2ull, token_bindings.size());
3480
3481 EXPECT_GT(d.bytes_received(), 0);
3482 std::string ekm = d.data_received();
3483
3484 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353485 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3486 token_bindings[0].signature,
3487 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483488 EXPECT_EQ(TokenBindingType::REFERRED, token_bindings[1].type);
nharper78e6d2b2016-09-21 05:42:353489 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[1].ec_point,
3490 token_bindings[1].signature,
3491 TokenBindingType::REFERRED, ekm));
nharperd6e65822016-03-30 23:05:483492 }
3493}
3494
3495// TODO(nharper): Remove this #ifdef and replace SpawnedTestServer with
3496// EmbeddedTestServer once crbug.com/599187 is resolved.
3497#if !defined(OS_ANDROID)
3498TEST_F(TokenBindingURLRequestTest, DontForwardHeaderFromHttp) {
3499 SpawnedTestServer http_server(SpawnedTestServer::TYPE_HTTP,
3500 SpawnedTestServer::kLocalhost,
3501 base::FilePath());
3502 ASSERT_TRUE(http_server.Start());
3503 SpawnedTestServer::SSLOptions ssl_options;
3504 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3505 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3506 ssl_options,
3507 base::FilePath(kTestFilePath));
3508 ASSERT_TRUE(https_test_server.Start());
3509
3510 TestDelegate d;
3511 {
3512 GURL redirect_url = http_server.GetURL(
3513 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363514 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483515 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3516 r->Start();
3517 EXPECT_TRUE(r->is_pending());
3518
3519 base::RunLoop().Run();
3520
maksim.sisovb53724b52016-09-16 05:30:503521 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483522
3523 HttpRequestHeaders headers;
3524 std::string token_binding_header, token_binding_message;
3525 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3526 EXPECT_TRUE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3527 &token_binding_header));
3528 EXPECT_TRUE(base::Base64UrlDecode(
nharper78e6d2b2016-09-21 05:42:353529 token_binding_header, base::Base64UrlDecodePolicy::DISALLOW_PADDING,
nharperd6e65822016-03-30 23:05:483530 &token_binding_message));
3531 std::vector<TokenBinding> token_bindings;
3532 ASSERT_TRUE(
3533 ParseTokenBindingMessage(token_binding_message, &token_bindings));
3534 ASSERT_EQ(1ull, token_bindings.size());
3535
3536 EXPECT_GT(d.bytes_received(), 0);
3537 std::string ekm = d.data_received();
3538
3539 EXPECT_EQ(TokenBindingType::PROVIDED, token_bindings[0].type);
nharper78e6d2b2016-09-21 05:42:353540 EXPECT_TRUE(VerifyTokenBindingSignature(token_bindings[0].ec_point,
3541 token_bindings[0].signature,
3542 TokenBindingType::PROVIDED, ekm));
nharperd6e65822016-03-30 23:05:483543 }
3544}
3545
3546// Test that if a server supporting Token Binding redirects (with
nharper86f0be22016-07-14 00:49:363547// Include-Referred-Token-Binding-ID) to an https url on a server that does not
nharperd6e65822016-03-30 23:05:483548// support Token Binding, then we do not send a Sec-Token-Binding when following
3549// the redirect.
3550TEST_F(TokenBindingURLRequestTest, ForwardWithoutTokenBinding) {
3551 SpawnedTestServer::SSLOptions ssl_options;
3552 SpawnedTestServer https_test_server(SpawnedTestServer::TYPE_HTTPS,
3553 ssl_options,
3554 base::FilePath(kTestFilePath));
3555 ASSERT_TRUE(https_test_server.Start());
3556 ssl_options.supported_token_binding_params.push_back(TB_PARAM_ECDSAP256);
3557 SpawnedTestServer token_binding_test_server(SpawnedTestServer::TYPE_HTTPS,
3558 ssl_options,
3559 base::FilePath(kTestFilePath));
3560 ASSERT_TRUE(token_binding_test_server.Start());
3561
3562 TestDelegate d;
3563 {
3564 GURL redirect_url = token_binding_test_server.GetURL(
3565 "forward-tokbind?" + https_test_server.GetURL("tokbind-ekm").spec());
danakj8522a25b2016-04-16 00:17:363566 std::unique_ptr<URLRequest> r(
nharperd6e65822016-03-30 23:05:483567 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
3568 r->Start();
3569 EXPECT_TRUE(r->is_pending());
3570
3571 base::RunLoop().Run();
3572
maksim.sisovb53724b52016-09-16 05:30:503573 EXPECT_EQ(OK, d.request_status());
nharperd6e65822016-03-30 23:05:483574
3575 HttpRequestHeaders headers;
3576 std::string token_binding_header, token_binding_message;
3577 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3578 EXPECT_FALSE(headers.GetHeader(HttpRequestHeaders::kTokenBinding,
3579 &token_binding_header));
3580 }
3581}
3582#endif // !defined(OS_ANDROID)
nharperb7441ef2016-01-25 23:54:143583#endif // !defined(OS_IOS)
3584
3585// In this unit test, we're using the HTTPTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:113586// issuing a CONNECT request with the magic host name "www.redirect.com".
tommycli59a63432015-11-06 00:10:553587// The EmbeddedTestServer will return a 302 response, which we should not
[email protected]95409e12010-08-17 20:07:113588// follow.
[email protected]f2f31b32013-01-16 23:24:093589TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
tommycli59a63432015-11-06 00:10:553590 http_test_server()->RegisterRequestHandler(
3591 base::Bind(&HandleRedirectConnect));
3592 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:113593
[email protected]ceefd7fd2012-11-29 00:36:243594 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043595 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553596 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503597
[email protected]d1ec59082009-02-11 02:48:153598 TestDelegate d;
3599 {
danakj8522a25b2016-04-16 00:17:363600 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363601 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193602 r->Start();
3603 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153604
[email protected]255620da2013-08-19 13:14:293605 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153606
[email protected]d8fc4722014-06-13 13:17:153607 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473608 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503609 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:083610 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153611 // We should not have followed the redirect.
3612 EXPECT_EQ(0, d.received_redirect_count());
3613 }
3614}
3615
[email protected]8202d0c2011-02-23 08:31:143616// This is the same as the previous test, but checks that the network delegate
3617// registers the error.
[email protected]c044616e2013-02-20 02:01:263618TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
tommycli59a63432015-11-06 00:10:553619 ASSERT_TRUE(http_test_server()->Start());
[email protected]8202d0c2011-02-23 08:31:143620
[email protected]ceefd7fd2012-11-29 00:36:243621 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043622 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553623 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503624
[email protected]8202d0c2011-02-23 08:31:143625 TestDelegate d;
3626 {
danakj8522a25b2016-04-16 00:17:363627 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363628 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193629 r->Start();
3630 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143631
[email protected]255620da2013-08-19 13:14:293632 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143633
[email protected]d8fc4722014-06-13 13:17:153634 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:473635 EXPECT_FALSE(r->proxy_server().is_valid());
[email protected]8202d0c2011-02-23 08:31:143636 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:503637 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]8202d0c2011-02-23 08:31:143638 // We should not have followed the redirect.
3639 EXPECT_EQ(0, d.received_redirect_count());
3640
3641 EXPECT_EQ(1, network_delegate.error_count());
robpercival214763f2016-07-01 23:27:013642 EXPECT_THAT(network_delegate.last_error(),
3643 IsError(ERR_TUNNEL_CONNECTION_FAILED));
[email protected]8202d0c2011-02-23 08:31:143644 }
3645}
3646
[email protected]dc5a5cf2012-09-26 02:49:303647// Tests that we can block and asynchronously return OK in various stages.
3648TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3649 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3650 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3651 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3652 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3653 };
3654 static const size_t blocking_stages_length = arraysize(blocking_stages);
3655
tommycli59a63432015-11-06 00:10:553656 ASSERT_TRUE(http_test_server()->Start());
[email protected]dc5a5cf2012-09-26 02:49:303657
3658 TestDelegate d;
3659 BlockingNetworkDelegate network_delegate(
3660 BlockingNetworkDelegate::USER_CALLBACK);
3661 network_delegate.set_block_on(
3662 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3663 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3664 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3665
3666 TestURLRequestContext context(true);
3667 context.set_network_delegate(&network_delegate);
3668 context.Init();
3669
3670 {
danakj8522a25b2016-04-16 00:17:363671 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553672 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303673
[email protected]f7022f32014-08-21 16:32:193674 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303675 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293676 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303677 EXPECT_EQ(blocking_stages[i],
3678 network_delegate.stage_blocked_for_callback());
3679 network_delegate.DoCallback(OK);
3680 }
[email protected]255620da2013-08-19 13:14:293681 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193682 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:503683 EXPECT_EQ(OK, d.request_status());
[email protected]dc5a5cf2012-09-26 02:49:303684 EXPECT_EQ(1, network_delegate.created_requests());
3685 EXPECT_EQ(0, network_delegate.destroyed_requests());
3686 }
3687 EXPECT_EQ(1, network_delegate.destroyed_requests());
3688}
3689
[email protected]4c76d7c2011-04-15 19:14:123690// Tests that the network delegate can block and cancel a request.
3691TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
tommycli59a63432015-11-06 00:10:553692 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123693
3694 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303695 BlockingNetworkDelegate network_delegate(
3696 BlockingNetworkDelegate::AUTO_CALLBACK);
3697 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3698 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123699
[email protected]d5a4dd62012-05-23 01:41:043700 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553701 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503702
[email protected]4c76d7c2011-04-15 19:14:123703 {
danakj8522a25b2016-04-16 00:17:363704 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:553705 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123706
[email protected]f7022f32014-08-21 16:32:193707 r->Start();
[email protected]255620da2013-08-19 13:14:293708 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123709
[email protected]d8fc4722014-06-13 13:17:153710 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473711 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:503712 EXPECT_EQ(ERR_EMPTY_RESPONSE, d.request_status());
[email protected]4c76d7c2011-04-15 19:14:123713 EXPECT_EQ(1, network_delegate.created_requests());
3714 EXPECT_EQ(0, network_delegate.destroyed_requests());
3715 }
3716 EXPECT_EQ(1, network_delegate.destroyed_requests());
3717}
3718
[email protected]b4438d32012-09-27 06:15:303719// Helper function for NetworkDelegateCancelRequestAsynchronously and
3720// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3721// delegate operating in |block_mode| and a request for |url|. It blocks the
3722// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3723void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3724 BlockingNetworkDelegate::Stage stage,
3725 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363726 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303727 BlockingNetworkDelegate network_delegate(block_mode);
3728 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3729 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363730
[email protected]b4438d32012-09-27 06:15:303731 TestURLRequestContext context(true);
3732 context.set_network_delegate(&network_delegate);
3733 context.Init();
[email protected]3cd384c602011-08-31 16:12:363734
3735 {
danakj8522a25b2016-04-16 00:17:363736 std::unique_ptr<URLRequest> r(
3737 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363738
[email protected]f7022f32014-08-21 16:32:193739 r->Start();
[email protected]255620da2013-08-19 13:14:293740 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363741
[email protected]d8fc4722014-06-13 13:17:153742 // The proxy server is not set before cancellation.
tbansal2ecbbc72016-10-06 17:15:473743 if (stage == BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST ||
3744 stage == BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS) {
3745 EXPECT_FALSE(r->proxy_server().is_valid());
3746 } else if (stage == BlockingNetworkDelegate::ON_HEADERS_RECEIVED) {
3747 EXPECT_TRUE(r->proxy_server().is_direct());
3748 } else {
3749 NOTREACHED();
3750 }
maksim.sisovb53724b52016-09-16 05:30:503751 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, d.request_status());
[email protected]3cd384c602011-08-31 16:12:363752 EXPECT_EQ(1, network_delegate.created_requests());
3753 EXPECT_EQ(0, network_delegate.destroyed_requests());
3754 }
3755 EXPECT_EQ(1, network_delegate.destroyed_requests());
3756}
3757
[email protected]b4438d32012-09-27 06:15:303758// The following 3 tests check that the network delegate can cancel a request
3759// synchronously in various stages of the request.
3760TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
tommycli59a63432015-11-06 00:10:553761 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303762 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3763 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553764 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303765}
3766
3767TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
tommycli59a63432015-11-06 00:10:553768 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303769 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3770 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553771 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303772}
3773
3774TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
tommycli59a63432015-11-06 00:10:553775 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303776 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3777 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553778 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303779}
3780
3781// The following 3 tests check that the network delegate can cancel a request
3782// asynchronously in various stages of the request.
3783TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
tommycli59a63432015-11-06 00:10:553784 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303785 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3786 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
tommycli59a63432015-11-06 00:10:553787 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303788}
3789
3790TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
tommycli59a63432015-11-06 00:10:553791 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303792 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3793 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
tommycli59a63432015-11-06 00:10:553794 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303795}
3796
3797TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
tommycli59a63432015-11-06 00:10:553798 ASSERT_TRUE(http_test_server()->Start());
[email protected]b4438d32012-09-27 06:15:303799 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3800 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
tommycli59a63432015-11-06 00:10:553801 http_test_server()->GetURL("/"));
[email protected]b4438d32012-09-27 06:15:303802}
3803
[email protected]4c76d7c2011-04-15 19:14:123804// Tests that the network delegate can block and redirect a request to a new
3805// URL.
3806TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
tommycli59a63432015-11-06 00:10:553807 ASSERT_TRUE(http_test_server()->Start());
[email protected]4c76d7c2011-04-15 19:14:123808
3809 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303810 BlockingNetworkDelegate network_delegate(
3811 BlockingNetworkDelegate::AUTO_CALLBACK);
3812 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553813 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]4c76d7c2011-04-15 19:14:123814 network_delegate.set_redirect_url(redirect_url);
3815
[email protected]d5a4dd62012-05-23 01:41:043816 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553817 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503818
[email protected]4c76d7c2011-04-15 19:14:123819 {
tommycli59a63432015-11-06 00:10:553820 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363821 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363822 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123823
[email protected]6be6fa92014-08-06 23:44:563824 // Quit after hitting the redirect, so can check the headers.
3825 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193826 r->Start();
[email protected]255620da2013-08-19 13:14:293827 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123828
[email protected]6be6fa92014-08-06 23:44:563829 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193830 EXPECT_EQ(307, r->GetResponseCode());
3831 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563832 std::string location;
[email protected]f7022f32014-08-21 16:32:193833 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3834 &location));
[email protected]6be6fa92014-08-06 23:44:563835 EXPECT_EQ(redirect_url, GURL(location));
3836
3837 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193838 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563839 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:503840 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473841 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3842 http_test_server()->host_port_pair()),
3843 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093844 // before_send_headers_with_proxy_count only increments for headers sent
3845 // through an untunneled proxy.
3846 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553847 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3848 http_test_server()->host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273849
maksim.sisovb53724b52016-09-16 05:30:503850 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193851 EXPECT_EQ(redirect_url, r->url());
3852 EXPECT_EQ(original_url, r->original_url());
3853 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123854 EXPECT_EQ(1, network_delegate.created_requests());
3855 EXPECT_EQ(0, network_delegate.destroyed_requests());
3856 }
3857 EXPECT_EQ(1, network_delegate.destroyed_requests());
3858}
3859
[email protected]b813ed72012-04-05 08:21:363860// Tests that the network delegate can block and redirect a request to a new
3861// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3862TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
tommycli59a63432015-11-06 00:10:553863 ASSERT_TRUE(http_test_server()->Start());
[email protected]b813ed72012-04-05 08:21:363864
3865 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303866 BlockingNetworkDelegate network_delegate(
3867 BlockingNetworkDelegate::SYNCHRONOUS);
tommycli59a63432015-11-06 00:10:553868 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]b813ed72012-04-05 08:21:363869 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363870
[email protected]d5a4dd62012-05-23 01:41:043871 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553872 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363873
3874 {
tommycli59a63432015-11-06 00:10:553875 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363876 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363877 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363878
[email protected]6be6fa92014-08-06 23:44:563879 // Quit after hitting the redirect, so can check the headers.
3880 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193881 r->Start();
[email protected]255620da2013-08-19 13:14:293882 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363883
[email protected]6be6fa92014-08-06 23:44:563884 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193885 EXPECT_EQ(307, r->GetResponseCode());
3886 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563887 std::string location;
[email protected]f7022f32014-08-21 16:32:193888 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3889 &location));
[email protected]6be6fa92014-08-06 23:44:563890 EXPECT_EQ(redirect_url, GURL(location));
3891
3892 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193893 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563894 base::RunLoop().Run();
3895
maksim.sisovb53724b52016-09-16 05:30:503896 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473897 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3898 http_test_server()->host_port_pair()),
3899 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093900 // before_send_headers_with_proxy_count only increments for headers sent
3901 // through an untunneled proxy.
3902 EXPECT_EQ(1, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:553903 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
3904 http_test_server()->host_port_pair()));
maksim.sisovb53724b52016-09-16 05:30:503905 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193906 EXPECT_EQ(redirect_url, r->url());
3907 EXPECT_EQ(original_url, r->original_url());
3908 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363909 EXPECT_EQ(1, network_delegate.created_requests());
3910 EXPECT_EQ(0, network_delegate.destroyed_requests());
3911 }
3912 EXPECT_EQ(1, network_delegate.destroyed_requests());
3913}
3914
[email protected]3c5ca8c2011-09-29 01:14:513915// Tests that redirects caused by the network delegate preserve POST data.
3916TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
tommycli59a63432015-11-06 00:10:553917 ASSERT_TRUE(http_test_server()->Start());
[email protected]3c5ca8c2011-09-29 01:14:513918
3919 const char kData[] = "hello world";
3920
3921 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303922 BlockingNetworkDelegate network_delegate(
3923 BlockingNetworkDelegate::AUTO_CALLBACK);
3924 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
tommycli59a63432015-11-06 00:10:553925 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]3c5ca8c2011-09-29 01:14:513926 network_delegate.set_redirect_url(redirect_url);
3927
[email protected]ef2bf422012-05-11 03:27:093928 TestURLRequestContext context(true);
3929 context.set_network_delegate(&network_delegate);
3930 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513931
3932 {
tommycli59a63432015-11-06 00:10:553933 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363934 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363935 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193936 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073937 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513938 HttpRequestHeaders headers;
3939 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:513940 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193941 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563942
3943 // Quit after hitting the redirect, so can check the headers.
3944 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193945 r->Start();
[email protected]255620da2013-08-19 13:14:293946 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513947
[email protected]6be6fa92014-08-06 23:44:563948 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193949 EXPECT_EQ(307, r->GetResponseCode());
3950 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563951 std::string location;
[email protected]f7022f32014-08-21 16:32:193952 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3953 &location));
[email protected]6be6fa92014-08-06 23:44:563954 EXPECT_EQ(redirect_url, GURL(location));
3955
3956 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193957 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563958 base::RunLoop().Run();
3959
maksim.sisovb53724b52016-09-16 05:30:503960 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:193961 EXPECT_EQ(redirect_url, r->url());
3962 EXPECT_EQ(original_url, r->original_url());
3963 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513964 EXPECT_EQ(1, network_delegate.created_requests());
3965 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193966 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513967 EXPECT_EQ(kData, d.data_received());
3968 }
3969 EXPECT_EQ(1, network_delegate.destroyed_requests());
3970}
3971
[email protected]5f714132014-03-26 10:41:163972// Tests that the network delegate can block and redirect a request to a new
3973// URL during OnHeadersReceived.
3974TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
tommycli59a63432015-11-06 00:10:553975 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:163976
3977 TestDelegate d;
3978 BlockingNetworkDelegate network_delegate(
3979 BlockingNetworkDelegate::AUTO_CALLBACK);
3980 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
tommycli59a63432015-11-06 00:10:553981 GURL redirect_url(http_test_server()->GetURL("/simple.html"));
[email protected]5f714132014-03-26 10:41:163982 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3983
3984 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:553985 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]5f714132014-03-26 10:41:163986
3987 {
tommycli59a63432015-11-06 00:10:553988 GURL original_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:363989 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:363990 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163991
[email protected]f7022f32014-08-21 16:32:193992 r->Start();
[email protected]5f714132014-03-26 10:41:163993 base::RunLoop().Run();
3994
maksim.sisovb53724b52016-09-16 05:30:503995 EXPECT_EQ(OK, d.request_status());
tbansal2ecbbc72016-10-06 17:15:473996 EXPECT_EQ(ProxyServer(ProxyServer::SCHEME_HTTP,
3997 http_test_server()->host_port_pair()),
3998 r->proxy_server());
ryansturm49a8cb12016-06-15 16:51:093999 // before_send_headers_with_proxy_count only increments for headers sent
4000 // through an untunneled proxy.
4001 EXPECT_EQ(2, network_delegate.before_send_headers_with_proxy_count());
tommycli59a63432015-11-06 00:10:554002 EXPECT_TRUE(network_delegate.last_observed_proxy().Equals(
4003 http_test_server()->host_port_pair()));
[email protected]f7022f32014-08-21 16:32:194004
maksim.sisovb53724b52016-09-16 05:30:504005 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194006 EXPECT_EQ(redirect_url, r->url());
4007 EXPECT_EQ(original_url, r->original_url());
4008 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:164009 EXPECT_EQ(2, network_delegate.created_requests());
4010 EXPECT_EQ(0, network_delegate.destroyed_requests());
4011 }
4012 EXPECT_EQ(1, network_delegate.destroyed_requests());
4013}
4014
[email protected]c2911d72011-10-03 22:16:364015// Tests that the network delegate can synchronously complete OnAuthRequired
4016// by taking no action. This indicates that the NetworkDelegate does not want to
4017// handle the challenge, and is passing the buck along to the
4018// URLRequest::Delegate.
4019TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
tommycli59a63432015-11-06 00:10:554020 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364021
4022 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304023 BlockingNetworkDelegate network_delegate(
4024 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:364025
[email protected]ef2bf422012-05-11 03:27:094026 TestURLRequestContext context(true);
4027 context.set_network_delegate(&network_delegate);
4028 context.Init();
[email protected]c2911d72011-10-03 22:16:364029
[email protected]f3cf9802011-10-28 18:44:584030 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364031
4032 {
tommycli59a63432015-11-06 00:10:554033 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364034 std::unique_ptr<URLRequest> r(
4035 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194036 r->Start();
[email protected]79e1fd62013-06-20 06:50:044037
[email protected]255620da2013-08-19 13:14:294038 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044039
maksim.sisovb53724b52016-09-16 05:30:504040 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194041 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044042 EXPECT_TRUE(d.auth_required_called());
4043 EXPECT_EQ(1, network_delegate.created_requests());
4044 EXPECT_EQ(0, network_delegate.destroyed_requests());
4045 }
4046 EXPECT_EQ(1, network_delegate.destroyed_requests());
4047}
4048
4049TEST_F(URLRequestTestHTTP,
4050 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554051 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044052
4053 TestDelegate d;
4054 BlockingNetworkDelegate network_delegate(
4055 BlockingNetworkDelegate::SYNCHRONOUS);
4056
4057 TestURLRequestContext context(true);
4058 context.set_network_delegate(&network_delegate);
4059 context.Init();
4060
4061 d.set_credentials(AuthCredentials(kUser, kSecret));
4062
4063 {
tommycli59a63432015-11-06 00:10:554064 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364065 std::unique_ptr<URLRequest> r(
4066 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194067 r->Start();
[email protected]79e1fd62013-06-20 06:50:044068
4069 {
4070 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194071 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044072 EXPECT_FALSE(headers.HasHeader("Authorization"));
4073 }
4074
[email protected]255620da2013-08-19 13:14:294075 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364076
maksim.sisovb53724b52016-09-16 05:30:504077 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194078 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364079 EXPECT_TRUE(d.auth_required_called());
4080 EXPECT_EQ(1, network_delegate.created_requests());
4081 EXPECT_EQ(0, network_delegate.destroyed_requests());
4082 }
4083 EXPECT_EQ(1, network_delegate.destroyed_requests());
4084}
4085
4086// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:404087// by setting credentials.
[email protected]c2911d72011-10-03 22:16:364088TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
tommycli59a63432015-11-06 00:10:554089 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364090
4091 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304092 BlockingNetworkDelegate network_delegate(
4093 BlockingNetworkDelegate::SYNCHRONOUS);
4094 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364095 network_delegate.set_auth_retval(
4096 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4097
[email protected]f3cf9802011-10-28 18:44:584098 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364099
[email protected]ef2bf422012-05-11 03:27:094100 TestURLRequestContext context(true);
4101 context.set_network_delegate(&network_delegate);
4102 context.Init();
[email protected]c2911d72011-10-03 22:16:364103
4104 {
tommycli59a63432015-11-06 00:10:554105 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364106 std::unique_ptr<URLRequest> r(
4107 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194108 r->Start();
[email protected]255620da2013-08-19 13:14:294109 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364110
maksim.sisovb53724b52016-09-16 05:30:504111 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194112 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364113 EXPECT_FALSE(d.auth_required_called());
4114 EXPECT_EQ(1, network_delegate.created_requests());
4115 EXPECT_EQ(0, network_delegate.destroyed_requests());
4116 }
4117 EXPECT_EQ(1, network_delegate.destroyed_requests());
4118}
4119
[email protected]79e1fd62013-06-20 06:50:044120// Same as above, but also tests that GetFullRequestHeaders returns the proper
4121// headers (for the first or second request) when called at the proper times.
4122TEST_F(URLRequestTestHTTP,
4123 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554124 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044125
4126 TestDelegate d;
4127 BlockingNetworkDelegate network_delegate(
4128 BlockingNetworkDelegate::SYNCHRONOUS);
4129 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
4130 network_delegate.set_auth_retval(
4131 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4132
4133 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
4134
4135 TestURLRequestContext context(true);
4136 context.set_network_delegate(&network_delegate);
4137 context.Init();
4138
4139 {
tommycli59a63432015-11-06 00:10:554140 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364141 std::unique_ptr<URLRequest> r(
4142 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194143 r->Start();
[email protected]255620da2013-08-19 13:14:294144 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044145
maksim.sisovb53724b52016-09-16 05:30:504146 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194147 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:044148 EXPECT_FALSE(d.auth_required_called());
4149 EXPECT_EQ(1, network_delegate.created_requests());
4150 EXPECT_EQ(0, network_delegate.destroyed_requests());
4151
4152 {
4153 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194154 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044155 EXPECT_TRUE(headers.HasHeader("Authorization"));
4156 }
4157 }
4158 EXPECT_EQ(1, network_delegate.destroyed_requests());
4159}
4160
[email protected]c2911d72011-10-03 22:16:364161// Tests that the network delegate can synchronously complete OnAuthRequired
4162// by cancelling authentication.
4163TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
tommycli59a63432015-11-06 00:10:554164 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364165
4166 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304167 BlockingNetworkDelegate network_delegate(
4168 BlockingNetworkDelegate::SYNCHRONOUS);
4169 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364170 network_delegate.set_auth_retval(
4171 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4172
[email protected]ef2bf422012-05-11 03:27:094173 TestURLRequestContext context(true);
4174 context.set_network_delegate(&network_delegate);
4175 context.Init();
[email protected]c2911d72011-10-03 22:16:364176
4177 {
tommycli59a63432015-11-06 00:10:554178 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364179 std::unique_ptr<URLRequest> r(
4180 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194181 r->Start();
[email protected]255620da2013-08-19 13:14:294182 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364183
maksim.sisovb53724b52016-09-16 05:30:504184 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194185 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364186 EXPECT_FALSE(d.auth_required_called());
4187 EXPECT_EQ(1, network_delegate.created_requests());
4188 EXPECT_EQ(0, network_delegate.destroyed_requests());
4189 }
4190 EXPECT_EQ(1, network_delegate.destroyed_requests());
4191}
4192
4193// Tests that the network delegate can asynchronously complete OnAuthRequired
4194// by taking no action. This indicates that the NetworkDelegate does not want
4195// to handle the challenge, and is passing the buck along to the
4196// URLRequest::Delegate.
4197TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
tommycli59a63432015-11-06 00:10:554198 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364199
4200 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304201 BlockingNetworkDelegate network_delegate(
4202 BlockingNetworkDelegate::AUTO_CALLBACK);
4203 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364204
[email protected]ef2bf422012-05-11 03:27:094205 TestURLRequestContext context(true);
4206 context.set_network_delegate(&network_delegate);
4207 context.Init();
[email protected]c2911d72011-10-03 22:16:364208
[email protected]f3cf9802011-10-28 18:44:584209 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:364210
4211 {
tommycli59a63432015-11-06 00:10:554212 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364213 std::unique_ptr<URLRequest> r(
4214 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194215 r->Start();
[email protected]255620da2013-08-19 13:14:294216 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364217
maksim.sisovb53724b52016-09-16 05:30:504218 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194219 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364220 EXPECT_TRUE(d.auth_required_called());
4221 EXPECT_EQ(1, network_delegate.created_requests());
4222 EXPECT_EQ(0, network_delegate.destroyed_requests());
4223 }
4224 EXPECT_EQ(1, network_delegate.destroyed_requests());
4225}
4226
4227// Tests that the network delegate can asynchronously complete OnAuthRequired
4228// by setting credentials.
4229TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
tommycli59a63432015-11-06 00:10:554230 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364231
4232 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304233 BlockingNetworkDelegate network_delegate(
4234 BlockingNetworkDelegate::AUTO_CALLBACK);
4235 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364236 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364237 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4238
[email protected]f3cf9802011-10-28 18:44:584239 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:364240 network_delegate.set_auth_credentials(auth_credentials);
4241
[email protected]ef2bf422012-05-11 03:27:094242 TestURLRequestContext context(true);
4243 context.set_network_delegate(&network_delegate);
4244 context.Init();
[email protected]c2911d72011-10-03 22:16:364245
4246 {
tommycli59a63432015-11-06 00:10:554247 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364248 std::unique_ptr<URLRequest> r(
4249 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194250 r->Start();
[email protected]255620da2013-08-19 13:14:294251 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364252
maksim.sisovb53724b52016-09-16 05:30:504253 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194254 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364255 EXPECT_FALSE(d.auth_required_called());
4256 EXPECT_EQ(1, network_delegate.created_requests());
4257 EXPECT_EQ(0, network_delegate.destroyed_requests());
4258 }
4259 EXPECT_EQ(1, network_delegate.destroyed_requests());
4260}
4261
4262// Tests that the network delegate can asynchronously complete OnAuthRequired
4263// by cancelling authentication.
4264TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
tommycli59a63432015-11-06 00:10:554265 ASSERT_TRUE(http_test_server()->Start());
[email protected]c2911d72011-10-03 22:16:364266
4267 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304268 BlockingNetworkDelegate network_delegate(
4269 BlockingNetworkDelegate::AUTO_CALLBACK);
4270 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:364271 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:364272 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
4273
[email protected]ef2bf422012-05-11 03:27:094274 TestURLRequestContext context(true);
4275 context.set_network_delegate(&network_delegate);
4276 context.Init();
[email protected]c2911d72011-10-03 22:16:364277
4278 {
tommycli59a63432015-11-06 00:10:554279 GURL url(http_test_server()->GetURL("/auth-basic"));
danakj8522a25b2016-04-16 00:17:364280 std::unique_ptr<URLRequest> r(
4281 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194282 r->Start();
[email protected]255620da2013-08-19 13:14:294283 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:364284
maksim.sisovb53724b52016-09-16 05:30:504285 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:194286 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:364287 EXPECT_FALSE(d.auth_required_called());
4288 EXPECT_EQ(1, network_delegate.created_requests());
4289 EXPECT_EQ(0, network_delegate.destroyed_requests());
4290 }
4291 EXPECT_EQ(1, network_delegate.destroyed_requests());
4292}
4293
[email protected]9045b8822012-01-13 20:35:354294// Tests that we can handle when a network request was canceled while we were
4295// waiting for the network delegate.
4296// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
4297TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
tommycli59a63432015-11-06 00:10:554298 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354299
4300 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304301 BlockingNetworkDelegate network_delegate(
4302 BlockingNetworkDelegate::USER_CALLBACK);
4303 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:354304
[email protected]ef2bf422012-05-11 03:27:094305 TestURLRequestContext context(true);
4306 context.set_network_delegate(&network_delegate);
4307 context.Init();
[email protected]9045b8822012-01-13 20:35:354308
4309 {
danakj8522a25b2016-04-16 00:17:364310 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554311 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354312
[email protected]f7022f32014-08-21 16:32:194313 r->Start();
[email protected]255620da2013-08-19 13:14:294314 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304315 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4316 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354317 EXPECT_EQ(0, network_delegate.completed_requests());
4318 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194319 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354320 // Ensure that network delegate is notified.
4321 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504322 EXPECT_EQ(1, network_delegate.canceled_requests());
[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());
maksim.sisovb53724b52016-09-16 05:30:504359 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354360 EXPECT_EQ(1, network_delegate.created_requests());
4361 EXPECT_EQ(0, network_delegate.destroyed_requests());
4362 }
4363 EXPECT_EQ(1, network_delegate.destroyed_requests());
4364}
4365
4366// Tests that we can handle when a network request was canceled while we were
4367// waiting for the network delegate.
4368// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4369TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
tommycli59a63432015-11-06 00:10:554370 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354371
4372 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304373 BlockingNetworkDelegate network_delegate(
4374 BlockingNetworkDelegate::USER_CALLBACK);
4375 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354376
[email protected]ef2bf422012-05-11 03:27:094377 TestURLRequestContext context(true);
4378 context.set_network_delegate(&network_delegate);
4379 context.Init();
[email protected]9045b8822012-01-13 20:35:354380
4381 {
danakj8522a25b2016-04-16 00:17:364382 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554383 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354384
[email protected]f7022f32014-08-21 16:32:194385 r->Start();
[email protected]255620da2013-08-19 13:14:294386 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304387 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4388 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354389 EXPECT_EQ(0, network_delegate.completed_requests());
4390 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194391 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354392 // Ensure that network delegate is notified.
4393 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504394 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354395 EXPECT_EQ(1, network_delegate.created_requests());
4396 EXPECT_EQ(0, network_delegate.destroyed_requests());
4397 }
4398 EXPECT_EQ(1, network_delegate.destroyed_requests());
4399}
4400
4401// Tests that we can handle when a network request was canceled while we were
4402// waiting for the network delegate.
4403// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024404TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
tommycli59a63432015-11-06 00:10:554405 ASSERT_TRUE(http_test_server()->Start());
[email protected]9045b8822012-01-13 20:35:354406
4407 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304408 BlockingNetworkDelegate network_delegate(
4409 BlockingNetworkDelegate::USER_CALLBACK);
4410 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354411
[email protected]ef2bf422012-05-11 03:27:094412 TestURLRequestContext context(true);
4413 context.set_network_delegate(&network_delegate);
4414 context.Init();
[email protected]9045b8822012-01-13 20:35:354415
4416 {
danakj8522a25b2016-04-16 00:17:364417 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554418 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:354419
[email protected]f7022f32014-08-21 16:32:194420 r->Start();
[email protected]255620da2013-08-19 13:14:294421 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304422 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4423 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354424 EXPECT_EQ(0, network_delegate.completed_requests());
4425 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194426 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354427 // Ensure that network delegate is notified.
4428 EXPECT_EQ(1, network_delegate.completed_requests());
maksim.sisovb53724b52016-09-16 05:30:504429 EXPECT_EQ(1, network_delegate.canceled_requests());
[email protected]9045b8822012-01-13 20:35:354430 EXPECT_EQ(1, network_delegate.created_requests());
4431 EXPECT_EQ(0, network_delegate.destroyed_requests());
4432 }
4433 EXPECT_EQ(1, network_delegate.destroyed_requests());
4434}
4435
tommycli59a63432015-11-06 00:10:554436namespace {
4437
danakj8522a25b2016-04-16 00:17:364438std::unique_ptr<test_server::HttpResponse> HandleServerAuthConnect(
tommycli59a63432015-11-06 00:10:554439 const test_server::HttpRequest& request) {
4440 if (request.headers.find("Host") == request.headers.end() ||
4441 request.headers.at("Host") != "www.server-auth.com" ||
4442 request.method != test_server::METHOD_CONNECT) {
4443 return nullptr;
4444 }
4445
danakj8522a25b2016-04-16 00:17:364446 std::unique_ptr<test_server::BasicHttpResponse> http_response(
tommycli59a63432015-11-06 00:10:554447 new test_server::BasicHttpResponse);
4448 http_response->set_code(HTTP_UNAUTHORIZED);
4449 http_response->AddCustomHeader("WWW-Authenticate",
4450 "Basic realm=\"WallyWorld\"");
dchengc7eeda422015-12-26 03:56:484451 return std::move(http_response);
tommycli59a63432015-11-06 00:10:554452}
4453
4454} // namespace
4455
4456// In this unit test, we're using the EmbeddedTestServer as a proxy server and
[email protected]95409e12010-08-17 20:07:114457// issuing a CONNECT request with the magic host name "www.server-auth.com".
tommycli59a63432015-11-06 00:10:554458// The EmbeddedTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354459TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
tommycli59a63432015-11-06 00:10:554460 http_test_server()->RegisterRequestHandler(
4461 base::Bind(&HandleServerAuthConnect));
4462 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114463
[email protected]ceefd7fd2012-11-29 00:36:244464 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044465 TestURLRequestContextWithProxy context(
tommycli59a63432015-11-06 00:10:554466 http_test_server()->host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504467
[email protected]dc651782009-02-14 01:45:084468 TestDelegate d;
4469 {
danakj8522a25b2016-04-16 00:17:364470 std::unique_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:364471 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:084472
[email protected]f7022f32014-08-21 16:32:194473 r->Start();
4474 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084475
[email protected]255620da2013-08-19 13:14:294476 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084477
[email protected]d8fc4722014-06-13 13:17:154478 // The proxy server is not set before failure.
tbansal2ecbbc72016-10-06 17:15:474479 EXPECT_FALSE(r->proxy_server().is_valid());
maksim.sisovb53724b52016-09-16 05:30:504480 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, d.request_status());
[email protected]dc651782009-02-14 01:45:084481 }
4482}
4483
[email protected]b89290212009-08-14 22:37:354484TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
tommycli59a63432015-11-06 00:10:554485 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114486
initial.commit586acc5fe2008-07-26 22:42:524487 TestDelegate d;
4488 {
danakj8522a25b2016-04-16 00:17:364489 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554490 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524491
[email protected]f7022f32014-08-21 16:32:194492 r->Start();
4493 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524494
[email protected]255620da2013-08-19 13:14:294495 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524496
4497 EXPECT_EQ(1, d.response_started_count());
4498 EXPECT_FALSE(d.received_data_before_response());
4499 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554500 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194501 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554502 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194503 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164504
[email protected]9e743cd2010-03-16 07:03:534505 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524506 }
initial.commit586acc5fe2008-07-26 22:42:524507}
4508
[email protected]263163f2012-06-14 22:40:344509// This test has the server send a large number of cookies to the client.
4510// To ensure that no number of cookies causes a crash, a galloping binary
4511// search is used to estimate that maximum number of cookies that are accepted
4512// by the browser. Beyond the maximum number, the request will fail with
4513// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304514#if defined(OS_WIN)
4515// http://crbug.com/177916
4516#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4517#else
4518#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4519#endif // defined(OS_WIN)
4520TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
tommycli59a63432015-11-06 00:10:554521 ASSERT_TRUE(http_test_server()->Start());
[email protected]263163f2012-06-14 22:40:344522
4523 int lower_bound = 0;
4524 int upper_bound = 1;
4525
4526 // Double the number of cookies until the response header limits are
4527 // exceeded.
4528 while (DoManyCookiesRequest(upper_bound)) {
4529 lower_bound = upper_bound;
4530 upper_bound *= 2;
4531 ASSERT_LT(upper_bound, 1000000);
4532 }
4533
pkasting6b68a162014-12-01 22:10:294534 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:344535 if (tolerance < 2)
4536 tolerance = 2;
4537
4538 // Perform a binary search to find the highest possible number of cookies,
4539 // within the desired tolerance.
4540 while (upper_bound - lower_bound >= tolerance) {
4541 int num_cookies = (lower_bound + upper_bound) / 2;
4542
4543 if (DoManyCookiesRequest(num_cookies))
4544 lower_bound = num_cookies;
4545 else
4546 upper_bound = num_cookies;
4547 }
4548 // Success: the test did not crash.
4549}
4550
[email protected]b89290212009-08-14 22:37:354551TEST_F(URLRequestTestHTTP, GetTest) {
tommycli59a63432015-11-06 00:10:554552 ASSERT_TRUE(http_test_server()->Start());
[email protected]95409e12010-08-17 20:07:114553
initial.commit586acc5fe2008-07-26 22:42:524554 TestDelegate d;
4555 {
danakj8522a25b2016-04-16 00:17:364556 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554557 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:524558
[email protected]f7022f32014-08-21 16:32:194559 r->Start();
4560 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524561
[email protected]255620da2013-08-19 13:14:294562 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524563
4564 EXPECT_EQ(1, d.response_started_count());
4565 EXPECT_FALSE(d.received_data_before_response());
4566 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554567 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194568 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554569 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194570 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524571 }
[email protected]5d7b373e2009-09-02 07:19:034572}
4573
[email protected]79e1fd62013-06-20 06:50:044574TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:554575 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:044576
4577 TestDelegate d;
4578 {
tommycli59a63432015-11-06 00:10:554579 GURL test_url(http_test_server()->GetURL("/defaultresponse"));
danakj8522a25b2016-04-16 00:17:364580 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:364581 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:044582
4583 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194584 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044585
[email protected]f7022f32014-08-21 16:32:194586 r->Start();
4587 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044588
[email protected]255620da2013-08-19 13:14:294589 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044590
4591 EXPECT_EQ(1, d.response_started_count());
4592 EXPECT_FALSE(d.received_data_before_response());
4593 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554594 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194595 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554596 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194597 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044598
4599 EXPECT_TRUE(d.have_full_request_headers());
4600 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4601 }
4602}
4603
[email protected]58e32bb2013-01-21 18:23:254604TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
tommycli59a63432015-11-06 00:10:554605 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254606
4607 TestDelegate d;
4608 {
danakj8522a25b2016-04-16 00:17:364609 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:554610 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:254611
[email protected]f7022f32014-08-21 16:32:194612 r->Start();
4613 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254614
[email protected]255620da2013-08-19 13:14:294615 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254616
4617 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194618 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254619 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4620
4621 EXPECT_EQ(1, d.response_started_count());
4622 EXPECT_FALSE(d.received_data_before_response());
4623 EXPECT_NE(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:554624 EXPECT_EQ(http_test_server()->host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194625 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:554626 EXPECT_EQ(http_test_server()->host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194627 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254628 }
4629}
4630
tommycli59a63432015-11-06 00:10:554631// TODO(svaldez): Update tests to use EmbeddedTestServer.
4632#if !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394633TEST_F(URLRequestTestHTTP, GetZippedTest) {
tommycli59a63432015-11-06 00:10:554634 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
4635 SpawnedTestServer::kLocalhost,
4636 base::FilePath(kTestFilePath));
4637
4638 ASSERT_TRUE(test_server.Start());
[email protected]aad63572011-05-24 20:14:394639
4640 // Parameter that specifies the Content-Length field in the response:
4641 // C - Compressed length.
4642 // U - Uncompressed length.
4643 // L - Large length (larger than both C & U).
4644 // M - Medium length (between C & U).
4645 // S - Small length (smaller than both C & U).
4646 const char test_parameters[] = "CULMS";
4647 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4648 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444649 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394650 // S has too little data, but we seem to accept it.
4651 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374652 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394653
xunjielifb4da222016-07-14 18:38:594654 base::FilePath file_path;
4655 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
4656 file_path = file_path.Append(kTestFilePath);
4657 file_path = file_path.Append(FILE_PATH_LITERAL("BullRunSpeech.txt"));
4658 std::string expected_content;
4659 ASSERT_TRUE(base::ReadFileToString(file_path, &expected_content));
4660
4661 for (int i = 0; i < num_tests; i++) {
[email protected]aad63572011-05-24 20:14:394662 TestDelegate d;
4663 {
tommycli59a63432015-11-06 00:10:554664 std::string test_file = base::StringPrintf(
4665 "compressedfiles/BullRunSpeech.txt?%c", test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394666
[email protected]ceefd7fd2012-11-29 00:36:244667 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094668 TestURLRequestContext context(true);
4669 context.set_network_delegate(&network_delegate);
4670 context.Init();
[email protected]87a09a92011-07-14 15:50:504671
danakj8522a25b2016-04-16 00:17:364672 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:554673 test_server.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194674 r->Start();
4675 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394676
[email protected]255620da2013-08-19 13:14:294677 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394678
4679 EXPECT_EQ(1, d.response_started_count());
4680 EXPECT_FALSE(d.received_data_before_response());
4681 VLOG(1) << " Received " << d.bytes_received() << " bytes"
maksim.sisovb53724b52016-09-16 05:30:504682 << " error = " << d.request_status();
[email protected]aad63572011-05-24 20:14:394683 if (test_expect_success[i]) {
maksim.sisovb53724b52016-09-16 05:30:504684 EXPECT_EQ(OK, d.request_status()) << " Parameter = \"" << test_file
4685 << "\"";
xunjielifb4da222016-07-14 18:38:594686 if (test_parameters[i] == 'S') {
4687 // When content length is smaller than both compressed length and
4688 // uncompressed length, HttpStreamParser might not read the full
4689 // response body.
4690 continue;
4691 }
4692 EXPECT_EQ(expected_content, d.data_received());
[email protected]aad63572011-05-24 20:14:394693 } else {
maksim.sisovb53724b52016-09-16 05:30:504694 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, d.request_status())
[email protected]aad63572011-05-24 20:14:394695 << " Parameter = \"" << test_file << "\"";
4696 }
4697 }
4698 }
4699}
tommycli59a63432015-11-06 00:10:554700#endif // !defined(OS_IOS)
[email protected]aad63572011-05-24 20:14:394701
[email protected]58e32bb2013-01-21 18:23:254702TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
tommycli59a63432015-11-06 00:10:554703 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:254704
tommycli59a63432015-11-06 00:10:554705 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454706 GURL original_url =
tommycli59a63432015-11-06 00:10:554707 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254708 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364709 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364710 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194711 req->Start();
[email protected]255620da2013-08-19 13:14:294712 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254713
4714 EXPECT_EQ(1, d.response_started_count());
4715 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194716 EXPECT_EQ(destination_url, req->url());
4717 EXPECT_EQ(original_url, req->original_url());
4718 ASSERT_EQ(2U, req->url_chain().size());
4719 EXPECT_EQ(original_url, req->url_chain()[0]);
4720 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254721
4722 LoadTimingInfo load_timing_info_before_redirect;
4723 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4724 &load_timing_info_before_redirect));
4725 TestLoadTimingNotReused(load_timing_info_before_redirect,
4726 CONNECT_TIMING_HAS_DNS_TIMES);
4727
4728 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194729 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254730 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4731
4732 // Check that a new socket was used on redirect, since the server does not
4733 // supposed keep-alive sockets, and that the times before the redirect are
4734 // before the ones recorded for the second request.
4735 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4736 load_timing_info.socket_log_id);
4737 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4738 load_timing_info.connect_timing.connect_start);
4739}
4740
[email protected]8f1ac082011-04-19 21:14:134741TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
tommycli59a63432015-11-06 00:10:554742 ASSERT_TRUE(http_test_server()->Start());
[email protected]8f1ac082011-04-19 21:14:134743
tommycli59a63432015-11-06 00:10:554744 GURL destination_url = http_test_server()->GetURL("/");
[email protected]007b3f82013-04-09 08:46:454745 GURL middle_redirect_url =
tommycli59a63432015-11-06 00:10:554746 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
4747 GURL original_url = http_test_server()->GetURL("/server-redirect?" +
4748 middle_redirect_url.spec());
[email protected]8f1ac082011-04-19 21:14:134749 TestDelegate d;
danakj8522a25b2016-04-16 00:17:364750 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:364751 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194752 req->Start();
[email protected]255620da2013-08-19 13:14:294753 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134754
4755 EXPECT_EQ(1, d.response_started_count());
4756 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194757 EXPECT_EQ(destination_url, req->url());
4758 EXPECT_EQ(original_url, req->original_url());
4759 ASSERT_EQ(3U, req->url_chain().size());
4760 EXPECT_EQ(original_url, req->url_chain()[0]);
4761 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4762 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134763}
4764
[email protected]abe1c4a2013-10-25 19:28:514765// First and second pieces of information logged by delegates to URLRequests.
4766const char kFirstDelegateInfo[] = "Wonderful delegate";
4767const char kSecondDelegateInfo[] = "Exciting delegate";
4768
4769// Logs delegate information to a URLRequest. The first string is logged
4770// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4771// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4772// another asynchronous call is used to clear the delegate information
4773// before calling a callback. The object then deletes itself.
4774class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4775 public:
4776 typedef base::Callback<void()> Callback;
4777
4778 // Each time delegate information is added to the URLRequest, the resulting
4779 // load state is checked. The expected load state after each request is
4780 // passed in as an argument.
4781 static void Run(URLRequest* url_request,
4782 LoadState expected_first_load_state,
4783 LoadState expected_second_load_state,
4784 LoadState expected_third_load_state,
4785 const Callback& callback) {
4786 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4787 url_request,
4788 expected_first_load_state,
4789 expected_second_load_state,
4790 expected_third_load_state,
4791 callback);
4792 logger->Start();
4793 }
4794
4795 // Checks that the log entries, starting with log_position, contain the
4796 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4797 // recorded. Returns the index of entry after the expected number of
4798 // events this logged, or entries.size() if there aren't enough entries.
mmenke43758e62015-05-04 21:09:464799 static size_t CheckDelegateInfo(const TestNetLogEntry::List& entries,
vishal.b62985ca92015-04-17 08:45:514800 size_t log_position) {
[email protected]abe1c4a2013-10-25 19:28:514801 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4802 if (log_position + 3 >= entries.size()) {
4803 ADD_FAILURE() << "Not enough log entries";
4804 return entries.size();
4805 }
4806 std::string delegate_info;
mikecirone8b85c432016-09-08 19:11:004807 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4808 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514809 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4810 &delegate_info));
4811 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4812
4813 ++log_position;
mikecirone8b85c432016-09-08 19:11:004814 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4815 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514816
4817 ++log_position;
mikecirone8b85c432016-09-08 19:11:004818 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4819 EXPECT_EQ(NetLogEventPhase::BEGIN, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514820 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4821 &delegate_info));
4822 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4823
4824 ++log_position;
mikecirone8b85c432016-09-08 19:11:004825 EXPECT_EQ(NetLogEventType::DELEGATE_INFO, entries[log_position].type);
4826 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:514827
4828 return log_position + 1;
4829 }
4830
4831 private:
4832 friend class base::RefCounted<AsyncDelegateLogger>;
4833
4834 AsyncDelegateLogger(URLRequest* url_request,
4835 LoadState expected_first_load_state,
4836 LoadState expected_second_load_state,
4837 LoadState expected_third_load_state,
4838 const Callback& callback)
4839 : url_request_(url_request),
4840 expected_first_load_state_(expected_first_load_state),
4841 expected_second_load_state_(expected_second_load_state),
4842 expected_third_load_state_(expected_third_load_state),
4843 callback_(callback) {
4844 }
4845
4846 ~AsyncDelegateLogger() {}
4847
4848 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534849 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514850 LoadStateWithParam load_state = url_request_->GetLoadState();
4851 EXPECT_EQ(expected_first_load_state_, load_state.state);
4852 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
skyostil4891b25b2015-06-11 11:43:454853 base::ThreadTaskRunnerHandle::Get()->PostTask(
4854 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
[email protected]abe1c4a2013-10-25 19:28:514855 }
4856
4857 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534858 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514859 LoadStateWithParam load_state = url_request_->GetLoadState();
4860 EXPECT_EQ(expected_second_load_state_, load_state.state);
4861 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4862 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4863 } else {
4864 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4865 }
skyostil4891b25b2015-06-11 11:43:454866 base::ThreadTaskRunnerHandle::Get()->PostTask(
4867 FROM_HERE, base::Bind(&AsyncDelegateLogger::LogComplete, this));
[email protected]abe1c4a2013-10-25 19:28:514868 }
4869
4870 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534871 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514872 LoadStateWithParam load_state = url_request_->GetLoadState();
4873 EXPECT_EQ(expected_third_load_state_, load_state.state);
4874 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084875 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514876 callback_.Run();
4877 }
4878
4879 URLRequest* url_request_;
4880 const int expected_first_load_state_;
4881 const int expected_second_load_state_;
4882 const int expected_third_load_state_;
4883 const Callback callback_;
4884
4885 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4886};
4887
4888// NetworkDelegate that logs delegate information before a request is started,
4889// before headers are sent, when headers are read, and when auth information
4890// is requested. Uses AsyncDelegateLogger.
4891class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4892 public:
4893 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204894 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514895
4896 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204897 int OnBeforeURLRequest(URLRequest* request,
4898 const CompletionCallback& callback,
4899 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514900 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4901 return RunCallbackAsynchronously(request, callback);
4902 }
4903
ryansturm2343cb62016-06-15 01:09:004904 int OnBeforeStartTransaction(URLRequest* request,
4905 const CompletionCallback& callback,
4906 HttpRequestHeaders* headers) override {
4907 TestNetworkDelegate::OnBeforeStartTransaction(request, callback, headers);
[email protected]abe1c4a2013-10-25 19:28:514908 return RunCallbackAsynchronously(request, callback);
4909 }
4910
dchengb03027d2014-10-21 12:00:204911 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514912 URLRequest* request,
4913 const CompletionCallback& callback,
4914 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164915 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134916 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164917 TestNetworkDelegate::OnHeadersReceived(request,
4918 callback,
[email protected]abe1c4a2013-10-25 19:28:514919 original_response_headers,
[email protected]5f714132014-03-26 10:41:164920 override_response_headers,
4921 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514922 return RunCallbackAsynchronously(request, callback);
4923 }
4924
dchengb03027d2014-10-21 12:00:204925 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514926 URLRequest* request,
4927 const AuthChallengeInfo& auth_info,
4928 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134929 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514930 AsyncDelegateLogger::Run(
4931 request,
4932 LOAD_STATE_WAITING_FOR_DELEGATE,
4933 LOAD_STATE_WAITING_FOR_DELEGATE,
4934 LOAD_STATE_WAITING_FOR_DELEGATE,
4935 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4936 callback, credentials));
4937 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4938 }
4939
4940 private:
4941 static int RunCallbackAsynchronously(
4942 URLRequest* request,
4943 const CompletionCallback& callback) {
4944 AsyncDelegateLogger::Run(
4945 request,
4946 LOAD_STATE_WAITING_FOR_DELEGATE,
4947 LOAD_STATE_WAITING_FOR_DELEGATE,
4948 LOAD_STATE_WAITING_FOR_DELEGATE,
4949 base::Bind(callback, OK));
4950 return ERR_IO_PENDING;
4951 }
4952
4953 static void SetAuthAndResume(const AuthCallback& callback,
4954 AuthCredentials* credentials) {
4955 *credentials = AuthCredentials(kUser, kSecret);
4956 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4957 }
4958
4959 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4960};
4961
4962// URLRequest::Delegate that logs delegate information when the headers
4963// are received, when each read completes, and during redirects. Uses
4964// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4965//
4966// Inherits from TestDelegate to reuse the TestDelegate code to handle
4967// advancing to the next step in most cases, as well as cancellation.
4968class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4969 public:
4970 enum CancelStage {
4971 NO_CANCEL = 0,
4972 CANCEL_ON_RECEIVED_REDIRECT,
4973 CANCEL_ON_RESPONSE_STARTED,
4974 CANCEL_ON_READ_COMPLETED
4975 };
4976
4977 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4978 : cancel_stage_(cancel_stage) {
4979 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4980 set_cancel_in_received_redirect(true);
4981 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4982 set_cancel_in_response_started(true);
4983 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4984 set_cancel_in_received_data(true);
4985 }
dchengb03027d2014-10-21 12:00:204986 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514987
4988 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204989 void OnReceivedRedirect(URLRequest* request,
4990 const RedirectInfo& redirect_info,
4991 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514992 *defer_redirect = true;
4993 AsyncDelegateLogger::Run(
4994 request,
4995 LOAD_STATE_WAITING_FOR_DELEGATE,
4996 LOAD_STATE_WAITING_FOR_DELEGATE,
4997 LOAD_STATE_WAITING_FOR_DELEGATE,
4998 base::Bind(
4999 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:595000 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:515001 }
5002
maksim.sisov0f4aa142016-09-05 05:55:285003 void OnResponseStarted(URLRequest* request, int net_error) override {
[email protected]abe1c4a2013-10-25 19:28:515004 AsyncDelegateLogger::Run(
maksim.sisov0f4aa142016-09-05 05:55:285005 request, LOAD_STATE_WAITING_FOR_DELEGATE,
5006 LOAD_STATE_WAITING_FOR_DELEGATE, LOAD_STATE_WAITING_FOR_DELEGATE,
5007 base::Bind(
5008 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
5009 base::Unretained(this), request, net_error));
[email protected]abe1c4a2013-10-25 19:28:515010 }
5011
dchengb03027d2014-10-21 12:00:205012 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:515013 AsyncDelegateLogger::Run(
5014 request,
5015 LOAD_STATE_IDLE,
5016 LOAD_STATE_IDLE,
5017 LOAD_STATE_IDLE,
5018 base::Bind(
5019 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
5020 base::Unretained(this), request, bytes_read));
5021 }
5022
5023 private:
5024 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:595025 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:515026 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:595027 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:515028 // FollowDeferredRedirect should not be called after cancellation.
5029 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
5030 return;
5031 if (!defer_redirect)
5032 request->FollowDeferredRedirect();
5033 }
5034
maksim.sisov0f4aa142016-09-05 05:55:285035 void OnResponseStartedLoggingComplete(URLRequest* request, int net_error) {
[email protected]abe1c4a2013-10-25 19:28:515036 // The parent class continues the request.
maksim.sisov0f4aa142016-09-05 05:55:285037 TestDelegate::OnResponseStarted(request, net_error);
[email protected]abe1c4a2013-10-25 19:28:515038 }
5039
5040 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
5041 // The parent class continues the request.
5042 TestDelegate::OnReadCompleted(request, bytes_read);
5043 }
5044
5045 const CancelStage cancel_stage_;
5046
5047 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
5048};
5049
5050// Tests handling of delegate info before a request starts.
5051TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
tommycli59a63432015-11-06 00:10:555052 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515053
5054 TestDelegate request_delegate;
5055 TestURLRequestContext context(true);
5056 context.set_network_delegate(NULL);
5057 context.set_net_log(&net_log_);
5058 context.Init();
5059
5060 {
danakj8522a25b2016-04-16 00:17:365061 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555062 context.CreateRequest(http_test_server()->GetURL("/defaultresponse"),
davidben151423e2015-03-23 18:48:365063 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195064 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515065 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085066 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515067
5068 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:195069 r.get(),
[email protected]abe1c4a2013-10-25 19:28:515070 LOAD_STATE_WAITING_FOR_DELEGATE,
5071 LOAD_STATE_WAITING_FOR_DELEGATE,
5072 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:195073 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:515074
5075 base::RunLoop().Run();
5076
[email protected]f7022f32014-08-21 16:32:195077 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505078 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515079 }
5080
mmenke43758e62015-05-04 21:09:465081 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515082 net_log_.GetEntries(&entries);
5083 size_t log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005084 entries, 0, NetLogEventType::DELEGATE_INFO, NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515085
5086 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
5087
5088 // Nothing else should add any delegate info to the request.
mikecirone8b85c432016-09-08 19:11:005089 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5090 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515091}
5092
5093// Tests handling of delegate info from a network delegate.
5094TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
tommycli59a63432015-11-06 00:10:555095 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515096
5097 TestDelegate request_delegate;
5098 AsyncLoggingNetworkDelegate network_delegate;
5099 TestURLRequestContext context(true);
5100 context.set_network_delegate(&network_delegate);
5101 context.set_net_log(&net_log_);
5102 context.Init();
5103
5104 {
danakj8522a25b2016-04-16 00:17:365105 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555106 context.CreateRequest(http_test_server()->GetURL("/simple.html"),
davidben151423e2015-03-23 18:48:365107 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195108 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515109 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085110 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515111
[email protected]f7022f32014-08-21 16:32:195112 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515113 base::RunLoop().Run();
5114
[email protected]f7022f32014-08-21 16:32:195115 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505116 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515117 EXPECT_EQ(1, network_delegate.created_requests());
5118 EXPECT_EQ(0, network_delegate.destroyed_requests());
5119 }
5120 EXPECT_EQ(1, network_delegate.destroyed_requests());
5121
5122 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465123 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515124 net_log_.GetEntries(&entries);
5125 for (size_t i = 0; i < 3; ++i) {
5126 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005127 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5128 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515129
5130 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5131 log_position + 1);
5132
5133 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005134 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5135 entries[log_position].type);
5136 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515137 }
5138
mikecirone8b85c432016-09-08 19:11:005139 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5140 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515141}
5142
5143// Tests handling of delegate info from a network delegate in the case of an
5144// HTTP redirect.
5145TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
tommycli59a63432015-11-06 00:10:555146 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515147
5148 TestDelegate request_delegate;
5149 AsyncLoggingNetworkDelegate network_delegate;
5150 TestURLRequestContext context(true);
5151 context.set_network_delegate(&network_delegate);
5152 context.set_net_log(&net_log_);
5153 context.Init();
5154
5155 {
danakj8522a25b2016-04-16 00:17:365156 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555157 http_test_server()->GetURL("/server-redirect?simple.html"),
5158 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195159 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515160 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085161 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515162
[email protected]f7022f32014-08-21 16:32:195163 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515164 base::RunLoop().Run();
5165
[email protected]f7022f32014-08-21 16:32:195166 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505167 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515168 EXPECT_EQ(2, network_delegate.created_requests());
5169 EXPECT_EQ(0, network_delegate.destroyed_requests());
5170 }
5171 EXPECT_EQ(1, network_delegate.destroyed_requests());
5172
5173 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465174 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515175 net_log_.GetEntries(&entries);
5176 // The NetworkDelegate logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005177 // OnBeforeStartTransaction, and OnHeadersReceived.
[email protected]abe1c4a2013-10-25 19:28:515178 for (size_t i = 0; i < 3; ++i) {
5179 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005180 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5181 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515182
5183 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5184 log_position + 1);
5185
5186 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005187 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5188 entries[log_position].type);
5189 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515190 }
5191
5192 // The URLRequest::Delegate then gets informed about the redirect.
5193 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005194 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5195 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515196
5197 // The NetworkDelegate logged information in the same three events as before.
5198 for (size_t i = 0; i < 3; ++i) {
5199 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005200 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5201 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515202
5203 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5204 log_position + 1);
5205
5206 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005207 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5208 entries[log_position].type);
5209 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515210 }
5211
mikecirone8b85c432016-09-08 19:11:005212 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5213 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515214}
5215
5216// Tests handling of delegate info from a network delegate in the case of HTTP
5217// AUTH.
5218TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
tommycli59a63432015-11-06 00:10:555219 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515220
5221 TestDelegate request_delegate;
5222 AsyncLoggingNetworkDelegate network_delegate;
5223 TestURLRequestContext context(true);
5224 context.set_network_delegate(&network_delegate);
5225 context.set_net_log(&net_log_);
5226 context.Init();
5227
5228 {
danakj8522a25b2016-04-16 00:17:365229 std::unique_ptr<URLRequest> r(
tommycli59a63432015-11-06 00:10:555230 context.CreateRequest(http_test_server()->GetURL("/auth-basic"),
davidben151423e2015-03-23 18:48:365231 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195232 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:515233 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:085234 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:515235
[email protected]f7022f32014-08-21 16:32:195236 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515237 base::RunLoop().Run();
5238
[email protected]f7022f32014-08-21 16:32:195239 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505240 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515241 EXPECT_EQ(1, network_delegate.created_requests());
5242 EXPECT_EQ(0, network_delegate.destroyed_requests());
5243 }
5244 EXPECT_EQ(1, network_delegate.destroyed_requests());
5245
5246 size_t log_position = 0;
mmenke43758e62015-05-04 21:09:465247 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515248 net_log_.GetEntries(&entries);
5249 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
ryansturm2343cb62016-06-15 01:09:005250 // OnBeforeStartTransaction, OnHeadersReceived, OnAuthRequired, and then again
5251 // in
5252 // OnBeforeURLRequest and OnBeforeStartTransaction.
[email protected]abe1c4a2013-10-25 19:28:515253 for (size_t i = 0; i < 6; ++i) {
5254 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005255 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5256 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515257
5258 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5259 log_position + 1);
5260
5261 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005262 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5263 entries[log_position].type);
5264 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515265 }
5266
mikecirone8b85c432016-09-08 19:11:005267 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5268 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515269}
5270
tommycli59a63432015-11-06 00:10:555271// TODO(svaldez): Update tests to use EmbeddedTestServer.
5272#if !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515273// Tests handling of delegate info from a URLRequest::Delegate.
5274TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
tommycli59a63432015-11-06 00:10:555275 SpawnedTestServer test_server(SpawnedTestServer::TYPE_HTTP,
5276 SpawnedTestServer::kLocalhost,
5277 base::FilePath(kTestFilePath));
5278
5279 ASSERT_TRUE(test_server.Start());
[email protected]abe1c4a2013-10-25 19:28:515280
5281 AsyncLoggingUrlRequestDelegate request_delegate(
5282 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5283 TestURLRequestContext context(true);
5284 context.set_network_delegate(NULL);
5285 context.set_net_log(&net_log_);
5286 context.Init();
5287
5288 {
5289 // A chunked response with delays between chunks is used to make sure that
5290 // attempts by the URLRequest delegate to log information while reading the
5291 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485292 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515293 // that it occurs.
danakj8522a25b2016-04-16 00:17:365294 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555295 test_server.GetURL("/chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:365296 &request_delegate));
[email protected]f7022f32014-08-21 16:32:195297 LoadStateWithParam load_state = r->GetLoadState();
5298 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515299 base::RunLoop().Run();
5300
[email protected]f7022f32014-08-21 16:32:195301 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505302 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515303 }
5304
mmenke43758e62015-05-04 21:09:465305 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515306 net_log_.GetEntries(&entries);
5307
[email protected]1826a402014-01-08 15:40:485308 size_t log_position = 0;
5309
[email protected]abe1c4a2013-10-25 19:28:515310 // The delegate info should only have been logged on header complete. Other
5311 // times it should silently be ignored.
mikecirone8b85c432016-09-08 19:11:005312 log_position = ExpectLogContainsSomewhereAfter(
5313 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE,
5314 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515315
5316 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5317 log_position + 1);
5318
5319 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005320 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE, entries[log_position].type);
5321 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515322
mikecirone8b85c432016-09-08 19:11:005323 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5324 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515325 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005326 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515327}
tommycli59a63432015-11-06 00:10:555328#endif // !defined(OS_IOS)
[email protected]abe1c4a2013-10-25 19:28:515329
5330// Tests handling of delegate info from a URLRequest::Delegate in the case of
5331// an HTTP redirect.
5332TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
tommycli59a63432015-11-06 00:10:555333 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515334
5335 AsyncLoggingUrlRequestDelegate request_delegate(
5336 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5337 TestURLRequestContext context(true);
5338 context.set_network_delegate(NULL);
5339 context.set_net_log(&net_log_);
5340 context.Init();
5341
5342 {
danakj8522a25b2016-04-16 00:17:365343 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555344 http_test_server()->GetURL("/server-redirect?simple.html"),
5345 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195346 LoadStateWithParam load_state = r->GetLoadState();
5347 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515348 base::RunLoop().Run();
5349
[email protected]f7022f32014-08-21 16:32:195350 EXPECT_EQ(200, r->GetResponseCode());
maksim.sisovb53724b52016-09-16 05:30:505351 EXPECT_EQ(OK, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515352 }
5353
mmenke43758e62015-05-04 21:09:465354 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515355 net_log_.GetEntries(&entries);
5356
5357 // Delegate info should only have been logged in OnReceivedRedirect and
5358 // OnResponseStarted.
5359 size_t log_position = 0;
5360 for (int i = 0; i < 2; ++i) {
5361 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005362 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5363 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515364
5365 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5366 log_position + 1);
5367
5368 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005369 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5370 entries[log_position].type);
5371 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515372 }
5373
mikecirone8b85c432016-09-08 19:11:005374 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5375 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515376 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005377 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515378}
5379
5380// Tests handling of delegate info from a URLRequest::Delegate in the case of
5381// an HTTP redirect, with cancellation at various points.
5382TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
tommycli59a63432015-11-06 00:10:555383 ASSERT_TRUE(http_test_server()->Start());
[email protected]abe1c4a2013-10-25 19:28:515384
5385 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5386 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5387 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5388 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5389 };
5390
5391 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5392 ++test_case) {
5393 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5394 TestURLRequestContext context(true);
vishal.b62985ca92015-04-17 08:45:515395 TestNetLog net_log;
[email protected]abe1c4a2013-10-25 19:28:515396 context.set_network_delegate(NULL);
5397 context.set_net_log(&net_log);
5398 context.Init();
5399
5400 {
danakj8522a25b2016-04-16 00:17:365401 std::unique_ptr<URLRequest> r(context.CreateRequest(
tommycli59a63432015-11-06 00:10:555402 http_test_server()->GetURL("/server-redirect?simple.html"),
5403 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:195404 LoadStateWithParam load_state = r->GetLoadState();
5405 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515406 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505407 EXPECT_EQ(ERR_ABORTED, request_delegate.request_status());
[email protected]abe1c4a2013-10-25 19:28:515408 }
5409
mmenke43758e62015-05-04 21:09:465410 TestNetLogEntry::List entries;
[email protected]abe1c4a2013-10-25 19:28:515411 net_log.GetEntries(&entries);
5412
5413 // Delegate info is always logged in both OnReceivedRedirect and
5414 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5415 // OnResponseStarted delegate call is after cancellation, but logging is
5416 // still currently supported in that call.
5417 size_t log_position = 0;
5418 for (int i = 0; i < 2; ++i) {
5419 log_position = ExpectLogContainsSomewhereAfter(
mikecirone8b85c432016-09-08 19:11:005420 entries, log_position, NetLogEventType::URL_REQUEST_DELEGATE,
5421 NetLogEventPhase::BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515422
5423 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5424 log_position + 1);
5425
5426 ASSERT_LT(log_position, entries.size());
mikecirone8b85c432016-09-08 19:11:005427 EXPECT_EQ(NetLogEventType::URL_REQUEST_DELEGATE,
5428 entries[log_position].type);
5429 EXPECT_EQ(NetLogEventPhase::END, entries[log_position].phase);
[email protected]abe1c4a2013-10-25 19:28:515430 }
5431
mikecirone8b85c432016-09-08 19:11:005432 EXPECT_FALSE(LogContainsEntryWithTypeAfter(entries, log_position + 1,
5433 NetLogEventType::DELEGATE_INFO));
[email protected]abe1c4a2013-10-25 19:28:515434 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
mikecirone8b85c432016-09-08 19:11:005435 entries, log_position + 1, NetLogEventType::URL_REQUEST_DELEGATE));
[email protected]abe1c4a2013-10-25 19:28:515436 }
5437}
5438
[email protected]847c0fa92012-11-06 16:37:425439namespace {
5440
5441const char kExtraHeader[] = "Allow-Snafu";
5442const char kExtraValue[] = "fubar";
5443
5444class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205445 void OnReceivedRedirect(URLRequest* request,
5446 const RedirectInfo& redirect_info,
5447 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595448 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425449 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5450 }
5451};
5452
5453} // namespace
5454
5455TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
tommycli59a63432015-11-06 00:10:555456 ASSERT_TRUE(http_test_server()->Start());
[email protected]847c0fa92012-11-06 16:37:425457
tommycli59a63432015-11-06 00:10:555458 GURL destination_url =
5459 http_test_server()->GetURL("/echoheader?" + std::string(kExtraHeader));
5460 GURL original_url =
5461 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]847c0fa92012-11-06 16:37:425462 RedirectWithAdditionalHeadersDelegate d;
danakj8522a25b2016-04-16 00:17:365463 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365464 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195465 req->Start();
[email protected]255620da2013-08-19 13:14:295466 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425467
5468 std::string value;
[email protected]f7022f32014-08-21 16:32:195469 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425470 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5471 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195472 EXPECT_FALSE(req->is_pending());
5473 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425474 EXPECT_EQ(kExtraValue, d.data_received());
5475}
5476
[email protected]251a1b92012-11-13 11:01:095477namespace {
5478
5479const char kExtraHeaderToRemove[] = "To-Be-Removed";
5480
5481class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205482 void OnReceivedRedirect(URLRequest* request,
5483 const RedirectInfo& redirect_info,
5484 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595485 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095486 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5487 }
5488};
5489
5490} // namespace
5491
5492TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
tommycli59a63432015-11-06 00:10:555493 ASSERT_TRUE(http_test_server()->Start());
[email protected]251a1b92012-11-13 11:01:095494
tommycli59a63432015-11-06 00:10:555495 GURL destination_url = http_test_server()->GetURL(
5496 "/echoheader?" + std::string(kExtraHeaderToRemove));
5497 GURL original_url =
5498 http_test_server()->GetURL("/server-redirect?" + destination_url.spec());
[email protected]251a1b92012-11-13 11:01:095499 RedirectWithHeaderRemovalDelegate d;
danakj8522a25b2016-04-16 00:17:365500 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:365501 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195502 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5503 req->Start();
[email protected]255620da2013-08-19 13:14:295504 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095505
5506 std::string value;
[email protected]f7022f32014-08-21 16:32:195507 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095508 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195509 EXPECT_FALSE(req->is_pending());
5510 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095511 EXPECT_EQ("None", d.data_received());
5512}
5513
[email protected]316c1e5e2012-09-12 15:17:445514TEST_F(URLRequestTestHTTP, CancelTest) {
5515 TestDelegate d;
5516 {
danakj8522a25b2016-04-16 00:17:365517 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365518 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445519
[email protected]f7022f32014-08-21 16:32:195520 r->Start();
5521 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445522
[email protected]f7022f32014-08-21 16:32:195523 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445524
[email protected]255620da2013-08-19 13:14:295525 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445526
5527 // We expect to receive OnResponseStarted even though the request has been
5528 // cancelled.
5529 EXPECT_EQ(1, d.response_started_count());
5530 EXPECT_EQ(0, d.bytes_received());
5531 EXPECT_FALSE(d.received_data_before_response());
5532 }
5533}
5534
5535TEST_F(URLRequestTestHTTP, CancelTest2) {
tommycli59a63432015-11-06 00:10:555536 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445537
5538 TestDelegate d;
5539 {
danakj8522a25b2016-04-16 00:17:365540 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555541 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445542
5543 d.set_cancel_in_response_started(true);
5544
[email protected]f7022f32014-08-21 16:32:195545 r->Start();
5546 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445547
[email protected]255620da2013-08-19 13:14:295548 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445549
5550 EXPECT_EQ(1, d.response_started_count());
5551 EXPECT_EQ(0, d.bytes_received());
5552 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505553 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445554 }
5555}
5556
5557TEST_F(URLRequestTestHTTP, CancelTest3) {
tommycli59a63432015-11-06 00:10:555558 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445559
5560 TestDelegate d;
5561 {
danakj8522a25b2016-04-16 00:17:365562 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555563 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445564
5565 d.set_cancel_in_received_data(true);
5566
[email protected]f7022f32014-08-21 16:32:195567 r->Start();
5568 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445569
[email protected]255620da2013-08-19 13:14:295570 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445571
5572 EXPECT_EQ(1, d.response_started_count());
5573 // There is no guarantee about how much data was received
5574 // before the cancel was issued. It could have been 0 bytes,
5575 // or it could have been all the bytes.
5576 // EXPECT_EQ(0, d.bytes_received());
5577 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:505578 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445579 }
5580}
5581
5582TEST_F(URLRequestTestHTTP, CancelTest4) {
tommycli59a63432015-11-06 00:10:555583 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445584
5585 TestDelegate d;
5586 {
danakj8522a25b2016-04-16 00:17:365587 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555588 http_test_server()->GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445589
[email protected]f7022f32014-08-21 16:32:195590 r->Start();
5591 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445592
5593 // The request will be implicitly canceled when it is destroyed. The
5594 // test delegate must not post a quit message when this happens because
5595 // this test doesn't actually have a message loop. The quit message would
5596 // get put on this thread's message queue and the next test would exit
5597 // early, causing problems.
5598 d.set_quit_on_complete(false);
5599 }
5600 // expect things to just cleanup properly.
5601
kimwjdalsl2bb4ff02015-12-16 22:06:025602 // we won't actually get a received response here because we've never run the
[email protected]316c1e5e2012-09-12 15:17:445603 // message loop
5604 EXPECT_FALSE(d.received_data_before_response());
5605 EXPECT_EQ(0, d.bytes_received());
5606}
5607
5608TEST_F(URLRequestTestHTTP, CancelTest5) {
tommycli59a63432015-11-06 00:10:555609 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445610
5611 // populate cache
5612 {
5613 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365614 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555615 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195616 r->Start();
[email protected]255620da2013-08-19 13:14:295617 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:505618 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445619 }
5620
5621 // cancel read from cache (see bug 990242)
5622 {
5623 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365624 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555625 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195626 r->Start();
5627 r->Cancel();
[email protected]255620da2013-08-19 13:14:295628 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445629
maksim.sisovb53724b52016-09-16 05:30:505630 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:445631 EXPECT_EQ(1, d.response_started_count());
5632 EXPECT_EQ(0, d.bytes_received());
5633 EXPECT_FALSE(d.received_data_before_response());
5634 }
5635}
5636
5637TEST_F(URLRequestTestHTTP, PostTest) {
tommycli59a63432015-11-06 00:10:555638 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445639 HTTPUploadDataOperationTest("POST");
5640}
5641
5642TEST_F(URLRequestTestHTTP, PutTest) {
tommycli59a63432015-11-06 00:10:555643 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445644 HTTPUploadDataOperationTest("PUT");
5645}
5646
5647TEST_F(URLRequestTestHTTP, PostEmptyTest) {
tommycli59a63432015-11-06 00:10:555648 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445649
5650 TestDelegate d;
5651 {
danakj8522a25b2016-04-16 00:17:365652 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555653 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195654 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445655
[email protected]f7022f32014-08-21 16:32:195656 r->Start();
5657 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445658
[email protected]255620da2013-08-19 13:14:295659 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445660
maksim.sisovb53724b52016-09-16 05:30:505661 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5662 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445663
5664 EXPECT_FALSE(d.received_data_before_response());
5665 EXPECT_TRUE(d.data_received().empty());
5666 }
5667}
5668
5669TEST_F(URLRequestTestHTTP, PostFileTest) {
tommycli59a63432015-11-06 00:10:555670 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445671
5672 TestDelegate d;
5673 {
danakj8522a25b2016-04-16 00:17:365674 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555675 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195676 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445677
[email protected]6cdfd7f2013-02-08 20:40:155678 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445679 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025680 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445681
danakj8522a25b2016-04-16 00:17:365682 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445683
[email protected]6cdfd7f2013-02-08 20:40:155684 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445685 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:475686 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:445687 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
ricea2deef682016-09-09 08:04:075688 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
avibf0746c2015-12-09 19:53:145689 base::ThreadTaskRunnerHandle::Get().get(), path, 0,
ricea2deef682016-09-09 08:04:075690 std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365691 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225692 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]316c1e5e2012-09-12 15:17:445693
[email protected]f7022f32014-08-21 16:32:195694 r->Start();
5695 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445696
[email protected]255620da2013-08-19 13:14:295697 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445698
avibf0746c2015-12-09 19:53:145699 int64_t size64 = 0;
pkasting6b68a162014-12-01 22:10:295700 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5701 ASSERT_LE(size64, std::numeric_limits<int>::max());
5702 int size = static_cast<int>(size64);
danakj8522a25b2016-04-16 00:17:365703 std::unique_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445704
[email protected]7600d0b2013-12-08 21:43:305705 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445706
maksim.sisovb53724b52016-09-16 05:30:505707 ASSERT_EQ(1, d.response_started_count()) << "request failed. Error: "
5708 << d.request_status();
[email protected]316c1e5e2012-09-12 15:17:445709
5710 EXPECT_FALSE(d.received_data_before_response());
5711
[email protected]329b68b2012-11-14 17:54:275712 EXPECT_EQ(size, d.bytes_received());
5713 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445714 }
5715}
5716
[email protected]999dd8c2013-11-12 06:45:545717TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
tommycli59a63432015-11-06 00:10:555718 ASSERT_TRUE(http_test_server()->Start());
[email protected]999dd8c2013-11-12 06:45:545719
5720 TestDelegate d;
5721 {
danakj8522a25b2016-04-16 00:17:365722 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555723 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195724 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545725
danakj8522a25b2016-04-16 00:17:365726 std::vector<std::unique_ptr<UploadElementReader>> element_readers;
[email protected]999dd8c2013-11-12 06:45:545727
ricea2deef682016-09-09 08:04:075728 element_readers.push_back(base::MakeUnique<UploadFileElementReader>(
skyostil4891b25b2015-06-11 11:43:455729 base::ThreadTaskRunnerHandle::Get().get(),
[email protected]999dd8c2013-11-12 06:45:545730 base::FilePath(FILE_PATH_LITERAL(
5731 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
ricea2deef682016-09-09 08:04:075732 0, std::numeric_limits<uint64_t>::max(), base::Time()));
danakj8522a25b2016-04-16 00:17:365733 r->set_upload(base::WrapUnique<UploadDataStream>(
olli.raula6df48b2a2015-11-26 07:40:225734 new ElementsUploadDataStream(std::move(element_readers), 0)));
[email protected]999dd8c2013-11-12 06:45:545735
[email protected]f7022f32014-08-21 16:32:195736 r->Start();
5737 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545738
5739 base::RunLoop().Run();
5740
[email protected]999dd8c2013-11-12 06:45:545741 EXPECT_TRUE(d.request_failed());
5742 EXPECT_FALSE(d.received_data_before_response());
5743 EXPECT_EQ(0, d.bytes_received());
maksim.sisovb53724b52016-09-16 05:30:505744 EXPECT_EQ(ERR_FILE_NOT_FOUND, d.request_status());
[email protected]999dd8c2013-11-12 06:45:545745 }
5746}
5747
mmenke56b0cbb912016-03-28 21:34:535748namespace {
5749
5750// Adds a standard set of data to an upload for chunked upload integration
5751// tests.
5752void AddDataToUpload(ChunkedUploadDataStream::Writer* writer) {
5753 writer->AppendData("a", 1, false);
5754 writer->AppendData("bcd", 3, false);
5755 writer->AppendData("this is a longer chunk than before.", 35, false);
5756 writer->AppendData("\r\n\r\n", 4, false);
5757 writer->AppendData("0", 1, false);
5758 writer->AppendData("2323", 4, true);
5759}
5760
5761// Checks that the upload data added in AddChunksToUpload() was echoed back from
5762// the server.
5763void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
5764 // This should match the chunks sent by AddChunksToUpload().
5765 const std::string expected_data =
5766 "abcdthis is a longer chunk than before.\r\n\r\n02323";
5767
maksim.sisovb53724b52016-09-16 05:30:505768 ASSERT_EQ(1, d->response_started_count()) << "request failed. Error: "
5769 << d->request_status();
mmenke56b0cbb912016-03-28 21:34:535770
5771 EXPECT_FALSE(d->received_data_before_response());
5772
5773 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
5774 EXPECT_EQ(expected_data, d->data_received());
5775}
5776
5777} // namespace
5778
[email protected]316c1e5e2012-09-12 15:17:445779TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
tommycli59a63432015-11-06 00:10:555780 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445781
5782 TestDelegate d;
5783 {
danakj8522a25b2016-04-16 00:17:365784 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555785 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365786 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535787 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365788 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535789 upload_data_stream->CreateWriter();
5790 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195791 r->set_method("POST");
mmenke56b0cbb912016-03-28 21:34:535792 AddDataToUpload(writer.get());
[email protected]f7022f32014-08-21 16:32:195793 r->Start();
5794 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445795
[email protected]255620da2013-08-19 13:14:295796 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445797
[email protected]f7022f32014-08-21 16:32:195798 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445799 }
5800}
5801
[email protected]329b68b2012-11-14 17:54:275802TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
tommycli59a63432015-11-06 00:10:555803 ASSERT_TRUE(http_test_server()->Start());
[email protected]329b68b2012-11-14 17:54:275804
5805 TestDelegate d;
5806 {
danakj8522a25b2016-04-16 00:17:365807 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555808 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365809 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535810 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365811 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535812 upload_data_stream->CreateWriter();
danakj8522a25b2016-04-16 00:17:365813 r->set_upload(base::WrapUnique(upload_data_stream.release()));
[email protected]f7022f32014-08-21 16:32:195814 r->set_method("POST");
5815 r->Start();
5816 EXPECT_TRUE(r->is_pending());
mmenke56b0cbb912016-03-28 21:34:535817 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295818 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275819
[email protected]f7022f32014-08-21 16:32:195820 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275821 }
5822}
5823
[email protected]316c1e5e2012-09-12 15:17:445824TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
tommycli59a63432015-11-06 00:10:555825 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445826
5827 TestDelegate d;
5828 {
danakj8522a25b2016-04-16 00:17:365829 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555830 http_test_server()->GetURL("/echo"), DEFAULT_PRIORITY, &d));
danakj8522a25b2016-04-16 00:17:365831 std::unique_ptr<ChunkedUploadDataStream> upload_data_stream(
mmenke56b0cbb912016-03-28 21:34:535832 new ChunkedUploadDataStream(0));
danakj8522a25b2016-04-16 00:17:365833 std::unique_ptr<ChunkedUploadDataStream::Writer> writer =
mmenke56b0cbb912016-03-28 21:34:535834 upload_data_stream->CreateWriter();
5835 r->set_upload(std::move(upload_data_stream));
[email protected]f7022f32014-08-21 16:32:195836 r->set_method("POST");
5837 r->Start();
5838 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445839
[email protected]255620da2013-08-19 13:14:295840 base::RunLoop().RunUntilIdle();
mmenke56b0cbb912016-03-28 21:34:535841 AddDataToUpload(writer.get());
[email protected]255620da2013-08-19 13:14:295842 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445843
[email protected]f7022f32014-08-21 16:32:195844 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445845 }
5846}
5847
5848TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
tommycli59a63432015-11-06 00:10:555849 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:445850
5851 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365852 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555853 http_test_server()->GetURL("/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195854 req->Start();
[email protected]255620da2013-08-19 13:14:295855 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445856
[email protected]f7022f32014-08-21 16:32:195857 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445858
5859 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195860 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445861
5862 std::string header;
5863 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5864 EXPECT_EQ("private", header);
5865
5866 header.clear();
5867 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5868 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5869
5870 // The response has two "X-Multiple-Entries" headers.
5871 // This verfies our output has them concatenated together.
5872 header.clear();
5873 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5874 EXPECT_EQ("a, b", header);
5875}
5876
tommycli59a63432015-11-06 00:10:555877// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
5878// security state. (see http://crbug.com/550977).
5879#if !defined(OS_IOS)
[email protected]242d8562012-10-30 21:20:465880TEST_F(URLRequestTestHTTP, ProcessSTS) {
tommycli59a63432015-11-06 00:10:555881 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5882 https_test_server.SetSSLConfig(
5883 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5884 https_test_server.ServeFilesFromSourceDirectory(
5885 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:465886 ASSERT_TRUE(https_test_server.Start());
5887
tommycli59a63432015-11-06 00:10:555888 std::string test_server_hostname = https_test_server.GetURL("/").host();
[email protected]242d8562012-10-30 21:20:465889 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365890 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555891 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195892 request->Start();
[email protected]255620da2013-08-19 13:14:295893 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465894
5895 TransportSecurityState* security_state =
5896 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405897 TransportSecurityState::STSState sts_state;
5898 TransportSecurityState::PKPState pkp_state;
5899 EXPECT_TRUE(
5900 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5901 EXPECT_FALSE(
5902 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5903 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
5904 sts_state.upgrade_mode);
5905 EXPECT_TRUE(sts_state.include_subdomains);
5906 EXPECT_FALSE(pkp_state.include_subdomains);
mathpc992e602015-10-21 20:34:035907#if defined(OS_ANDROID)
5908 // Android's CertVerifyProc does not (yet) handle pins.
5909#else
martijnc0d6b622015-06-30 19:14:405910 EXPECT_FALSE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:035911#endif
[email protected]37fd55fb2013-06-29 13:13:275912}
5913
estarka5da76702015-04-09 04:00:165914TEST_F(URLRequestTestHTTP, STSNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:555915 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5916 https_test_server.ServeFilesFromSourceDirectory(
5917 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:165918 ASSERT_TRUE(https_test_server.Start());
5919 // Make sure this test fails if the test server is changed to not
5920 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:555921 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
5922 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165923
5924 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365925 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555926 https_test_server.GetURL("/hsts-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:165927 request->Start();
5928 base::RunLoop().Run();
estarka5da76702015-04-09 04:00:165929 TransportSecurityState* security_state =
5930 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405931 TransportSecurityState::STSState sts_state;
5932 EXPECT_FALSE(
5933 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
estarka5da76702015-04-09 04:00:165934}
5935
estark06e0dac2015-08-07 21:56:015936namespace {
estark1614475f2016-03-10 03:46:475937const char kExpectCTStaticHostname[] = "preloaded-expect-ct.badssl.com";
dadriand476e652016-07-26 21:33:245938const char kExpectStapleStaticHostname[] = "preloaded-expect-staple.badssl.com";
5939const char kExpectStapleReportURI[] = "https://report.badssl.com/expect-staple";
estark06e0dac2015-08-07 21:56:015940const char kHPKPReportUri[] = "https://hpkp-report.test";
5941} // namespace
5942
[email protected]37fd55fb2013-06-29 13:13:275943// Tests that enabling HPKP on a domain does not affect the HSTS
5944// validity/expiration.
dadrian2faf2062016-07-16 00:03:175945TEST_F(URLRequestTestHTTP, ProcessPKP) {
estark06e0dac2015-08-07 21:56:015946 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555947 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5948 https_test_server.SetSSLConfig(
5949 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5950 https_test_server.ServeFilesFromSourceDirectory(
5951 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:275952 ASSERT_TRUE(https_test_server.Start());
5953
tommycli59a63432015-11-06 00:10:555954 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:165955
[email protected]37fd55fb2013-06-29 13:13:275956 TestDelegate d;
danakj8522a25b2016-04-16 00:17:365957 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:555958 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195959 request->Start();
[email protected]255620da2013-08-19 13:14:295960 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275961 TransportSecurityState* security_state =
5962 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:405963 TransportSecurityState::STSState sts_state;
5964 TransportSecurityState::PKPState pkp_state;
5965 EXPECT_FALSE(
5966 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
5967 EXPECT_TRUE(
5968 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
5969 EXPECT_EQ(TransportSecurityState::STSState::MODE_DEFAULT,
5970 sts_state.upgrade_mode);
5971 EXPECT_FALSE(sts_state.include_subdomains);
5972 EXPECT_FALSE(pkp_state.include_subdomains);
5973 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
estark06e0dac2015-08-07 21:56:015974 EXPECT_EQ(report_uri, pkp_state.report_uri);
martijnc0d6b622015-06-30 19:14:405975 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]242d8562012-10-30 21:20:465976}
5977
estark06e0dac2015-08-07 21:56:015978// Tests that reports get sent on HPKP violations when a report-uri is set.
dadrian2faf2062016-07-16 00:03:175979TEST_F(URLRequestTestHTTP, ProcessPKPAndSendReport) {
estark06e0dac2015-08-07 21:56:015980 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:555981 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
5982 https_test_server.SetSSLConfig(
5983 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
5984 https_test_server.ServeFilesFromSourceDirectory(
5985 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:015986 ASSERT_TRUE(https_test_server.Start());
5987
tommycli59a63432015-11-06 00:10:555988 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:015989
5990 // Set up a pin for |test_server_hostname|.
5991 TransportSecurityState security_state;
5992 const base::Time current_time(base::Time::Now());
5993 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(1000);
5994 HashValueVector hashes;
5995 HashValue hash1;
5996 HashValue hash2;
5997 // The values here don't matter, as long as they are different from
5998 // the mocked CertVerifyResult below.
svaldez35d0dca2015-08-24 16:12:445999 ASSERT_TRUE(
6000 hash1.FromString("sha256/1111111111111111111111111111111111111111111="));
6001 ASSERT_TRUE(
6002 hash2.FromString("sha256/2222222222222222222222222222222222222222222="));
estark06e0dac2015-08-07 21:56:016003 hashes.push_back(hash1);
6004 hashes.push_back(hash2);
6005 security_state.AddHPKP(test_server_hostname, expiry,
6006 false, /* include subdomains */
6007 hashes, report_uri);
6008
6009 MockCertificateReportSender mock_report_sender;
6010 security_state.SetReportSender(&mock_report_sender);
6011
6012 // Set up a MockCertVerifier to trigger a violation of the previously
6013 // set pin.
6014 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6015 ASSERT_TRUE(cert);
6016
6017 MockCertVerifier cert_verifier;
6018 CertVerifyResult verify_result;
6019 verify_result.verified_cert = cert;
6020 verify_result.is_issued_by_known_root = true;
6021 HashValue hash3;
svaldez35d0dca2015-08-24 16:12:446022 ASSERT_TRUE(
6023 hash3.FromString("sha256/3333333333333333333333333333333333333333333="));
estark06e0dac2015-08-07 21:56:016024 verify_result.public_key_hashes.push_back(hash3);
6025 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6026
6027 TestNetworkDelegate network_delegate;
6028 TestURLRequestContext context(true);
6029 context.set_transport_security_state(&security_state);
6030 context.set_network_delegate(&network_delegate);
6031 context.set_cert_verifier(&cert_verifier);
6032 context.Init();
6033
6034 // Now send a request to trigger the violation.
6035 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366036 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556037 https_test_server.GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
estark06e0dac2015-08-07 21:56:016038 violating_request->Start();
6039 base::RunLoop().Run();
6040
6041 // Check that a report was sent.
6042 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6043 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446044 EXPECT_EQ("application/json; charset=utf-8",
6045 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366046 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016047 base::JSONReader::Read(mock_report_sender.latest_report()));
6048 ASSERT_TRUE(value);
6049 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6050 base::DictionaryValue* report_dict;
6051 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6052 std::string report_hostname;
6053 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6054 EXPECT_EQ(test_server_hostname, report_hostname);
6055}
6056
6057// Tests that reports get sent on requests with
6058// Public-Key-Pins-Report-Only headers.
dadrian2faf2062016-07-16 00:03:176059TEST_F(URLRequestTestHTTP, ProcessPKPReportOnly) {
estark06e0dac2015-08-07 21:56:016060 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556061 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6062 https_test_server.SetSSLConfig(
6063 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6064 https_test_server.ServeFilesFromSourceDirectory(
6065 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016066 ASSERT_TRUE(https_test_server.Start());
6067
tommycli59a63432015-11-06 00:10:556068 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016069
6070 TransportSecurityState security_state;
6071 MockCertificateReportSender mock_report_sender;
6072 security_state.SetReportSender(&mock_report_sender);
6073
6074 // Set up a MockCertVerifier to violate the pin in the Report-Only
6075 // header.
6076 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6077 ASSERT_TRUE(cert);
6078
6079 MockCertVerifier cert_verifier;
6080 CertVerifyResult verify_result;
6081 verify_result.verified_cert = cert;
6082 verify_result.is_issued_by_known_root = true;
6083 HashValue hash;
6084 // This value doesn't matter, as long as it is different from the pins
6085 // for the request to hpkp-headers-report-only.html.
svaldez35d0dca2015-08-24 16:12:446086 ASSERT_TRUE(
6087 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
estark06e0dac2015-08-07 21:56:016088 verify_result.public_key_hashes.push_back(hash);
6089 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6090
6091 TestNetworkDelegate network_delegate;
6092 TestURLRequestContext context(true);
6093 context.set_transport_security_state(&security_state);
6094 context.set_network_delegate(&network_delegate);
6095 context.set_cert_verifier(&cert_verifier);
6096 context.Init();
6097
6098 // Now send a request to trigger the violation.
6099 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366100 std::unique_ptr<URLRequest> violating_request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556101 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016102 DEFAULT_PRIORITY, &d));
6103 violating_request->Start();
6104 base::RunLoop().Run();
6105
6106 // Check that a report was sent.
6107 EXPECT_EQ(report_uri, mock_report_sender.latest_report_uri());
6108 ASSERT_FALSE(mock_report_sender.latest_report().empty());
estarkb1716e22016-09-28 06:03:446109 EXPECT_EQ("application/json; charset=utf-8",
6110 mock_report_sender.latest_content_type());
danakj8522a25b2016-04-16 00:17:366111 std::unique_ptr<base::Value> value(
estark06e0dac2015-08-07 21:56:016112 base::JSONReader::Read(mock_report_sender.latest_report()));
6113 ASSERT_TRUE(value);
6114 ASSERT_TRUE(value->IsType(base::Value::TYPE_DICTIONARY));
6115 base::DictionaryValue* report_dict;
6116 ASSERT_TRUE(value->GetAsDictionary(&report_dict));
6117 std::string report_hostname;
6118 EXPECT_TRUE(report_dict->GetString("hostname", &report_hostname));
6119 EXPECT_EQ(test_server_hostname, report_hostname);
6120}
6121
6122// Tests that reports do not get sent on requests with
6123// Public-Key-Pins-Report-Only headers that don't have pin violations.
dadrian2faf2062016-07-16 00:03:176124TEST_F(URLRequestTestHTTP, ProcessPKPReportOnlyWithNoViolation) {
estark06e0dac2015-08-07 21:56:016125 GURL report_uri(kHPKPReportUri);
tommycli59a63432015-11-06 00:10:556126 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6127 https_test_server.SetSSLConfig(
6128 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6129 https_test_server.ServeFilesFromSourceDirectory(
6130 base::FilePath(kTestFilePath));
estark06e0dac2015-08-07 21:56:016131 ASSERT_TRUE(https_test_server.Start());
6132
tommycli59a63432015-11-06 00:10:556133 std::string test_server_hostname = https_test_server.GetURL("/").host();
estark06e0dac2015-08-07 21:56:016134
6135 TransportSecurityState security_state;
6136 MockCertificateReportSender mock_report_sender;
6137 security_state.SetReportSender(&mock_report_sender);
6138
6139 TestNetworkDelegate network_delegate;
6140 MockCertVerifier mock_cert_verifier;
6141 TestURLRequestContext context(true);
6142 context.set_transport_security_state(&security_state);
6143 context.set_network_delegate(&network_delegate);
6144 context.set_cert_verifier(&mock_cert_verifier);
6145 mock_cert_verifier.set_default_result(OK);
6146 context.Init();
6147
6148 // Now send a request that does not trigger the violation.
6149 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366150 std::unique_ptr<URLRequest> request(context.CreateRequest(
tommycli59a63432015-11-06 00:10:556151 https_test_server.GetURL("/hpkp-headers-report-only.html"),
estark06e0dac2015-08-07 21:56:016152 DEFAULT_PRIORITY, &d));
6153 request->Start();
6154 base::RunLoop().Run();
6155
6156 // Check that a report was not sent.
6157 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
6158 EXPECT_EQ(std::string(), mock_report_sender.latest_report());
6159}
6160
estarka5da76702015-04-09 04:00:166161TEST_F(URLRequestTestHTTP, PKPNotProcessedOnIP) {
tommycli59a63432015-11-06 00:10:556162 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6163 https_test_server.ServeFilesFromSourceDirectory(
6164 base::FilePath(kTestFilePath));
estarka5da76702015-04-09 04:00:166165 ASSERT_TRUE(https_test_server.Start());
6166 // Make sure this test fails if the test server is changed to not
6167 // listen on an IP by default.
tommycli59a63432015-11-06 00:10:556168 ASSERT_TRUE(https_test_server.GetURL("/").HostIsIPAddress());
6169 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166170
6171 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366172 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556173 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
estarka5da76702015-04-09 04:00:166174 request->Start();
6175 base::RunLoop().Run();
6176
6177 TransportSecurityState* security_state =
6178 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406179 TransportSecurityState::PKPState pkp_state;
6180 EXPECT_FALSE(
6181 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
estarka5da76702015-04-09 04:00:166182}
6183
dadriandf302c42016-06-10 18:48:596184TEST_F(URLRequestTestHTTP, PKPBypassRecorded) {
6185 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6186 https_test_server.SetSSLConfig(
6187 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6188 https_test_server.ServeFilesFromSourceDirectory(
6189 base::FilePath(kTestFilePath));
6190 ASSERT_TRUE(https_test_server.Start());
6191
6192 // Set up a MockCertVerifier to be a local root that violates the pin
6193 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6194 ASSERT_TRUE(cert);
6195
6196 MockCertVerifier cert_verifier;
6197 CertVerifyResult verify_result;
6198 verify_result.verified_cert = cert;
6199 verify_result.is_issued_by_known_root = false;
6200 HashValue hash;
6201 ASSERT_TRUE(
6202 hash.FromString("sha256/1111111111111111111111111111111111111111111="));
6203 verify_result.public_key_hashes.push_back(hash);
6204 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6205 cert_verifier.set_default_result(OK);
6206
6207 std::string test_server_hostname = https_test_server.GetURL("/").host();
6208
6209 // Set up HPKP
6210 base::Time current_time = base::Time::Now();
6211 const base::Time expiry = current_time + base::TimeDelta::FromSeconds(10000);
6212 HashValue pin;
6213 ASSERT_TRUE(
6214 pin.FromString("sha256/2222222222222222222222222222222222222222222="));
6215 HashValueVector hashes;
6216 hashes.push_back(pin);
6217 GURL report_uri(kHPKPReportUri);
6218 TransportSecurityState security_state;
6219 security_state.AddHPKP(test_server_hostname, expiry,
6220 false, /* include subdomains */
6221 hashes, report_uri);
6222
6223 TestNetworkDelegate network_delegate;
6224 TestURLRequestContext context(true);
6225 context.set_transport_security_state(&security_state);
6226 context.set_network_delegate(&network_delegate);
6227 context.set_cert_verifier(&cert_verifier);
6228 context.Init();
6229
6230 TestDelegate d;
6231 std::unique_ptr<URLRequest> request(context.CreateRequest(
6232 https_test_server.GetURL("/hpkp-headers.html"), DEFAULT_PRIORITY, &d));
6233 request->Start();
6234 base::RunLoop().Run();
6235
6236 TransportSecurityState::PKPState pkp_state;
6237 EXPECT_TRUE(
6238 security_state.GetDynamicPKPState(test_server_hostname, &pkp_state));
6239 EXPECT_TRUE(request->ssl_info().pkp_bypassed);
6240}
6241
[email protected]242d8562012-10-30 21:20:466242TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
tommycli59a63432015-11-06 00:10:556243 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6244 https_test_server.SetSSLConfig(
6245 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6246 https_test_server.ServeFilesFromSourceDirectory(
6247 base::FilePath(kTestFilePath));
[email protected]242d8562012-10-30 21:20:466248 ASSERT_TRUE(https_test_server.Start());
6249
tommycli59a63432015-11-06 00:10:556250 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166251
[email protected]242d8562012-10-30 21:20:466252 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366253 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556254 https_test_server.GetURL("/hsts-multiple-headers.html"), DEFAULT_PRIORITY,
6255 &d));
[email protected]f7022f32014-08-21 16:32:196256 request->Start();
[email protected]255620da2013-08-19 13:14:296257 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:466258
6259 // We should have set parameters from the first header, not the second.
6260 TransportSecurityState* security_state =
6261 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406262 TransportSecurityState::STSState sts_state;
6263 EXPECT_TRUE(
6264 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6265 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6266 sts_state.upgrade_mode);
6267 EXPECT_FALSE(sts_state.include_subdomains);
6268 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]242d8562012-10-30 21:20:466269}
6270
[email protected]9f972ec2013-04-10 20:24:366271TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
tommycli59a63432015-11-06 00:10:556272 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6273 https_test_server.SetSSLConfig(
6274 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6275 https_test_server.ServeFilesFromSourceDirectory(
6276 base::FilePath(kTestFilePath));
[email protected]9f972ec2013-04-10 20:24:366277 ASSERT_TRUE(https_test_server.Start());
6278
tommycli59a63432015-11-06 00:10:556279 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166280
[email protected]9f972ec2013-04-10 20:24:366281 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366282 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556283 https_test_server.GetURL("/hsts-and-hpkp-headers.html"), DEFAULT_PRIORITY,
6284 &d));
[email protected]f7022f32014-08-21 16:32:196285 request->Start();
[email protected]255620da2013-08-19 13:14:296286 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:366287
6288 // We should have set parameters from the first header, not the second.
6289 TransportSecurityState* security_state =
6290 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406291 TransportSecurityState::STSState sts_state;
6292 TransportSecurityState::PKPState pkp_state;
6293 EXPECT_TRUE(
6294 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6295 EXPECT_TRUE(
6296 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6297 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6298 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036299#if defined(OS_ANDROID)
6300 // Android's CertVerifyProc does not (yet) handle pins.
6301#else
martijnc0d6b622015-06-30 19:14:406302 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036303#endif
martijnc0d6b622015-06-30 19:14:406304 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]9f972ec2013-04-10 20:24:366305
[email protected]a165f092013-06-12 16:10:056306 // Even though there is an HSTS header asserting includeSubdomains, it is
6307 // the *second* such header, and we MUST process only the first.
martijnc0d6b622015-06-30 19:14:406308 EXPECT_FALSE(sts_state.include_subdomains);
[email protected]a165f092013-06-12 16:10:056309 // includeSubdomains does not occur in the test HPKP header.
martijnc0d6b622015-06-30 19:14:406310 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:366311}
6312
[email protected]37fd55fb2013-06-29 13:13:276313// Tests that when multiple HPKP headers are present, asserting different
6314// policies, that only the first such policy is processed.
6315TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
tommycli59a63432015-11-06 00:10:556316 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6317 https_test_server.SetSSLConfig(
6318 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6319 https_test_server.ServeFilesFromSourceDirectory(
6320 base::FilePath(kTestFilePath));
[email protected]37fd55fb2013-06-29 13:13:276321 ASSERT_TRUE(https_test_server.Start());
6322
tommycli59a63432015-11-06 00:10:556323 std::string test_server_hostname = https_test_server.GetURL("/").host();
estarka5da76702015-04-09 04:00:166324
[email protected]37fd55fb2013-06-29 13:13:276325 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366326 std::unique_ptr<URLRequest> request(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556327 https_test_server.GetURL("/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:366328 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196329 request->Start();
[email protected]255620da2013-08-19 13:14:296330 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:276331
6332 TransportSecurityState* security_state =
6333 default_context_.transport_security_state();
martijnc0d6b622015-06-30 19:14:406334 TransportSecurityState::STSState sts_state;
6335 TransportSecurityState::PKPState pkp_state;
6336 EXPECT_TRUE(
6337 security_state->GetDynamicSTSState(test_server_hostname, &sts_state));
6338 EXPECT_TRUE(
6339 security_state->GetDynamicPKPState(test_server_hostname, &pkp_state));
6340 EXPECT_EQ(TransportSecurityState::STSState::MODE_FORCE_HTTPS,
6341 sts_state.upgrade_mode);
mathpc992e602015-10-21 20:34:036342#if defined(OS_ANDROID)
6343 // Android's CertVerifyProc does not (yet) handle pins.
6344#else
martijnc0d6b622015-06-30 19:14:406345 EXPECT_TRUE(pkp_state.HasPublicKeyPins());
mathpc992e602015-10-21 20:34:036346#endif
martijnc0d6b622015-06-30 19:14:406347 EXPECT_NE(sts_state.expiry, pkp_state.expiry);
[email protected]37fd55fb2013-06-29 13:13:276348
martijnc0d6b622015-06-30 19:14:406349 EXPECT_TRUE(sts_state.include_subdomains);
6350 EXPECT_FALSE(pkp_state.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:276351}
6352
estark1614475f2016-03-10 03:46:476353// An ExpectCTReporter that records the number of times OnExpectCTFailed() was
6354// called.
6355class MockExpectCTReporter : public TransportSecurityState::ExpectCTReporter {
6356 public:
6357 MockExpectCTReporter() : num_failures_(0) {}
6358 ~MockExpectCTReporter() override {}
6359
6360 void OnExpectCTFailed(const HostPortPair& host_port_pair,
6361 const GURL& report_uri,
6362 const net::SSLInfo& ssl_info) override {
6363 num_failures_++;
6364 }
6365
6366 uint32_t num_failures() { return num_failures_; }
6367
6368 private:
6369 uint32_t num_failures_;
6370};
6371
6372// A CTVerifier that returns net::OK for every certificate.
6373class MockCTVerifier : public CTVerifier {
6374 public:
6375 MockCTVerifier() {}
6376 ~MockCTVerifier() override {}
6377
6378 int Verify(X509Certificate* cert,
6379 const std::string& stapled_ocsp_response,
6380 const std::string& sct_list_from_tls_extension,
eranmdcec9632016-10-10 14:16:106381 SignedCertificateTimestampAndStatusList* output_scts,
tfarina42834112016-09-22 13:38:206382 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476383 return net::OK;
6384 }
6385
6386 void SetObserver(Observer* observer) override {}
6387};
6388
6389// A CTPolicyEnforcer that returns a default CertPolicyCompliance value
6390// for every certificate.
6391class MockCTPolicyEnforcer : public CTPolicyEnforcer {
6392 public:
6393 MockCTPolicyEnforcer()
6394 : default_result_(
6395 ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS) {}
6396 ~MockCTPolicyEnforcer() override {}
6397
6398 ct::CertPolicyCompliance DoesConformToCertPolicy(
6399 X509Certificate* cert,
6400 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:206401 const NetLogWithSource& net_log) override {
estark1614475f2016-03-10 03:46:476402 return default_result_;
6403 }
6404
6405 void set_default_result(ct::CertPolicyCompliance default_result) {
6406 default_result_ = default_result;
6407 }
6408
6409 private:
6410 ct::CertPolicyCompliance default_result_;
6411};
6412
6413// Tests that Expect CT headers are processed correctly.
6414TEST_F(URLRequestTestHTTP, ExpectCTHeader) {
6415 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
6416 https_test_server.SetSSLConfig(
6417 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
6418 https_test_server.ServeFilesFromSourceDirectory(
6419 base::FilePath(kTestFilePath));
6420 ASSERT_TRUE(https_test_server.Start());
6421
6422 MockExpectCTReporter reporter;
6423 TransportSecurityState transport_security_state;
6424 transport_security_state.enable_static_expect_ct_ = true;
6425 transport_security_state.SetExpectCTReporter(&reporter);
6426
6427 // Set up a MockCertVerifier to accept the certificate that the server sends.
6428 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
6429 ASSERT_TRUE(cert);
6430 MockCertVerifier cert_verifier;
6431 CertVerifyResult verify_result;
6432 verify_result.verified_cert = cert;
6433 verify_result.is_issued_by_known_root = true;
6434 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
6435
6436 // Set up a MockCTVerifier and MockCTPolicyEnforcer to trigger an Expect CT
6437 // violation.
6438 MockCTVerifier ct_verifier;
6439 MockCTPolicyEnforcer ct_policy_enforcer;
6440 ct_policy_enforcer.set_default_result(
6441 ct::CertPolicyCompliance::CERT_POLICY_NOT_ENOUGH_SCTS);
6442
6443 TestNetworkDelegate network_delegate;
6444 // Use a MockHostResolver (which by default maps all hosts to
6445 // 127.0.0.1) so that the request can be sent to a site on the Expect
6446 // CT preload list.
6447 MockHostResolver host_resolver;
6448 TestURLRequestContext context(true);
6449 context.set_host_resolver(&host_resolver);
6450 context.set_transport_security_state(&transport_security_state);
6451 context.set_network_delegate(&network_delegate);
6452 context.set_cert_verifier(&cert_verifier);
6453 context.set_cert_transparency_verifier(&ct_verifier);
rsleevid6de8302016-06-21 01:33:206454 context.set_ct_policy_enforcer(std::move(&ct_policy_enforcer));
estark1614475f2016-03-10 03:46:476455 context.Init();
6456
6457 // Now send a request to trigger the violation.
6458 TestDelegate d;
6459 GURL url = https_test_server.GetURL("/expect-ct-header.html");
6460 GURL::Replacements replace_host;
6461 replace_host.SetHostStr(kExpectCTStaticHostname);
6462 url = url.ReplaceComponents(replace_host);
danakj8522a25b2016-04-16 00:17:366463 std::unique_ptr<URLRequest> violating_request(
estark1614475f2016-03-10 03:46:476464 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
6465 violating_request->Start();
6466 base::RunLoop().Run();
6467
6468 EXPECT_EQ(1u, reporter.num_failures());
6469}
6470
tommycli59a63432015-11-06 00:10:556471#endif // !defined(OS_IOS)
6472
[email protected]316c1e5e2012-09-12 15:17:446473TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
tommycli59a63432015-11-06 00:10:556474 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446475
6476 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366477 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556478 http_test_server()->GetURL("/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:366479 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196480 req->Start();
[email protected]255620da2013-08-19 13:14:296481 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446482
6483 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196484 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446485 EXPECT_EQ("text/html", mime_type);
6486
6487 std::string charset;
[email protected]f7022f32014-08-21 16:32:196488 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:446489 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:196490 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:446491}
6492
[email protected]02494ec2014-05-07 15:05:296493TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:346494 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:346495 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:346496 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:026497 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346498
6499 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506500 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:346501}
6502
[email protected]02494ec2014-05-07 15:05:296503#if !defined(DISABLE_FILE_SUPPORT)
6504TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
6505 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
6506 GURL file_url("file:///foo.txt");
skyostil4891b25b2015-06-11 11:43:456507 FileProtocolHandler file_protocol_handler(
6508 base::ThreadTaskRunnerHandle::Get());
[email protected]02494ec2014-05-07 15:05:296509 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
6510
6511 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:506512 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:296513}
6514
[email protected]588614c22013-08-16 00:09:026515TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
tommycli59a63432015-11-06 00:10:556516 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446517
6518 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366519 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556520 http_test_server()->GetURL("/redirect-to-file.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366521 &d));
[email protected]f7022f32014-08-21 16:32:196522 req->Start();
[email protected]255620da2013-08-19 13:14:296523 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446524
maksim.sisovb53724b52016-09-16 05:30:506525 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446526}
[email protected]02494ec2014-05-07 15:05:296527#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:446528
[email protected]588614c22013-08-16 00:09:026529TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
tommycli59a63432015-11-06 00:10:556530 ASSERT_TRUE(http_test_server()->Start());
[email protected]588614c22013-08-16 00:09:026531
6532 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366533 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556534 http_test_server()->GetURL("/redirect-to-data.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366535 &d));
[email protected]f7022f32014-08-21 16:32:196536 req->Start();
fdoray5eeb7642016-06-22 16:11:286537 base::RunLoop().Run();
[email protected]588614c22013-08-16 00:09:026538
maksim.sisovb53724b52016-09-16 05:30:506539 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]588614c22013-08-16 00:09:026540}
6541
[email protected]316c1e5e2012-09-12 15:17:446542TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
tommycli59a63432015-11-06 00:10:556543 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446544
6545 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366546 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556547 http_test_server()->GetURL("/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:366548 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196549 req->Start();
[email protected]255620da2013-08-19 13:14:296550 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446551
maksim.sisovb53724b52016-09-16 05:30:506552 EXPECT_EQ(ERR_INVALID_URL, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446553}
6554
[email protected]e50efea2014-03-24 18:41:006555// Make sure redirects are cached, despite not reading their bodies.
6556TEST_F(URLRequestTestHTTP, CacheRedirect) {
tommycli59a63432015-11-06 00:10:556557 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006558 GURL redirect_url =
tommycli59a63432015-11-06 00:10:556559 http_test_server()->GetURL("/redirect302-to-echo-cacheable");
[email protected]e50efea2014-03-24 18:41:006560
6561 {
6562 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366563 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366564 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196565 req->Start();
[email protected]e50efea2014-03-24 18:41:006566 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506567 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006568 EXPECT_EQ(1, d.received_redirect_count());
tommycli59a63432015-11-06 00:10:556569 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006570 }
6571
6572 {
6573 TestDelegate d;
6574 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366575 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366576 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196577 req->Start();
[email protected]e50efea2014-03-24 18:41:006578 base::RunLoop().Run();
6579
6580 EXPECT_EQ(1, d.received_redirect_count());
6581 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:196582 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006583
[email protected]f7022f32014-08-21 16:32:196584 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:006585 base::RunLoop().Run();
6586 EXPECT_EQ(1, d.received_redirect_count());
6587 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:506588 EXPECT_EQ(OK, d.request_status());
tommycli59a63432015-11-06 00:10:556589 EXPECT_EQ(http_test_server()->GetURL("/echo"), req->url());
[email protected]e50efea2014-03-24 18:41:006590 }
6591}
6592
6593// Make sure a request isn't cached when a NetworkDelegate forces a redirect
6594// when the headers are read, since the body won't have been read.
6595TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
tommycli59a63432015-11-06 00:10:556596 ASSERT_TRUE(http_test_server()->Start());
[email protected]e50efea2014-03-24 18:41:006597 // URL that is normally cached.
tommycli59a63432015-11-06 00:10:556598 GURL initial_url = http_test_server()->GetURL("/cachetime");
[email protected]e50efea2014-03-24 18:41:006599
6600 {
6601 // Set up the TestNetworkDelegate tp force a redirect.
tommycli59a63432015-11-06 00:10:556602 GURL redirect_to_url = http_test_server()->GetURL("/echo");
[email protected]e50efea2014-03-24 18:41:006603 default_network_delegate_.set_redirect_on_headers_received_url(
6604 redirect_to_url);
6605
6606 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366607 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366608 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196609 req->Start();
[email protected]e50efea2014-03-24 18:41:006610 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:506611 EXPECT_EQ(OK, d.request_status());
[email protected]e50efea2014-03-24 18:41:006612 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196613 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:006614 }
6615
6616 {
6617 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366618 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366619 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196620 req->Start();
[email protected]e50efea2014-03-24 18:41:006621 base::RunLoop().Run();
6622
maksim.sisovb53724b52016-09-16 05:30:506623 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196624 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:006625 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196626 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:006627 }
6628}
6629
[email protected]5f714132014-03-26 10:41:166630// Tests that redirection to an unsafe URL is allowed when it has been marked as
6631// safe.
6632TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
tommycli59a63432015-11-06 00:10:556633 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166634
6635 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
6636 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6637 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6638
6639 TestDelegate d;
6640 {
danakj8522a25b2016-04-16 00:17:366641 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556642 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166643
[email protected]f7022f32014-08-21 16:32:196644 r->Start();
[email protected]5f714132014-03-26 10:41:166645 base::RunLoop().Run();
6646
maksim.sisovb53724b52016-09-16 05:30:506647 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196648 EXPECT_EQ(2U, r->url_chain().size());
[email protected]f7022f32014-08-21 16:32:196649 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:166650 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
6651 }
6652}
6653
6654// Tests that a redirect to a different unsafe URL is blocked, even after adding
6655// some other URL to the whitelist.
6656TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
tommycli59a63432015-11-06 00:10:556657 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166658
6659 GURL unsafe_url("data:text/html,something");
6660 GURL different_unsafe_url("data:text/html,something-else");
6661 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6662 default_network_delegate_.set_allowed_unsafe_redirect_url(
6663 different_unsafe_url);
6664
6665 TestDelegate d;
6666 {
danakj8522a25b2016-04-16 00:17:366667 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556668 http_test_server()->GetURL("/whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166669
[email protected]f7022f32014-08-21 16:32:196670 r->Start();
[email protected]5f714132014-03-26 10:41:166671 base::RunLoop().Run();
6672
maksim.sisovb53724b52016-09-16 05:30:506673 EXPECT_EQ(ERR_UNSAFE_REDIRECT, d.request_status());
[email protected]5f714132014-03-26 10:41:166674 }
6675}
6676
[email protected]5f714132014-03-26 10:41:166677// Redirects from an URL with fragment to an unsafe URL with fragment should
6678// be allowed, and the reference fragment of the target URL should be preserved.
6679TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
tommycli59a63432015-11-06 00:10:556680 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166681
tommycli59a63432015-11-06 00:10:556682 GURL original_url(http_test_server()->GetURL("/original#fragment1"));
[email protected]5f714132014-03-26 10:41:166683 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6684 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
6685
6686 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
6687 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6688
6689 TestDelegate d;
6690 {
danakj8522a25b2016-04-16 00:17:366691 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366692 default_context_.CreateRequest(original_url, 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(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506698 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196699 EXPECT_EQ(original_url, r->original_url());
6700 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:166701 }
6702}
6703
6704// When a delegate has specified a safe redirect URL, but it does not match the
6705// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:146706TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
tommycli59a63432015-11-06 00:10:556707 ASSERT_TRUE(http_test_server()->Start());
[email protected]5f714132014-03-26 10:41:166708
tommycli59a63432015-11-06 00:10:556709 GURL original_url(http_test_server()->GetURL("/original#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166710 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
tommycli59a63432015-11-06 00:10:556711 GURL redirect_url(http_test_server()->GetURL("/target"));
6712 GURL expected_redirect_url(
6713 http_test_server()->GetURL("/target#expected-fragment"));
[email protected]5f714132014-03-26 10:41:166714
6715 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6716 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
6717
6718 TestDelegate d;
6719 {
danakj8522a25b2016-04-16 00:17:366720 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366721 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:166722
[email protected]f7022f32014-08-21 16:32:196723 r->Start();
[email protected]5f714132014-03-26 10:41:166724 base::RunLoop().Run();
6725
[email protected]f7022f32014-08-21 16:32:196726 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506727 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196728 EXPECT_EQ(original_url, r->original_url());
6729 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166730 }
6731}
6732
[email protected]f878230e2014-04-03 15:36:146733// When a delegate has specified a safe redirect URL, assume that the redirect
6734// URL should not be changed. In particular, the reference fragment should not
6735// be modified.
6736TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
tommycli59a63432015-11-06 00:10:556737 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:146738
tommycli59a63432015-11-06 00:10:556739 GURL original_url(
6740 http_test_server()->GetURL("/original#should-not-be-appended"));
[email protected]f878230e2014-04-03 15:36:146741 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6742
6743 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6744 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6745
6746 TestDelegate d;
6747 {
danakj8522a25b2016-04-16 00:17:366748 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366749 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146750
[email protected]f7022f32014-08-21 16:32:196751 r->Start();
[email protected]f878230e2014-04-03 15:36:146752 base::RunLoop().Run();
6753
[email protected]f7022f32014-08-21 16:32:196754 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:506755 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196756 EXPECT_EQ(original_url, r->original_url());
6757 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146758 }
6759}
6760
6761// When a URLRequestRedirectJob is created, the redirection must be followed and
6762// the reference fragment of the target URL must not be modified.
6763TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
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"));
6768 GURL redirect_url(http_test_server()->GetURL("/echo"));
[email protected]f878230e2014-04-03 15:36:146769
6770 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366771 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:366772 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146773
danakj8522a25b2016-04-16 00:17:366774 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196775 r.get(), &default_network_delegate_, redirect_url,
mmenkeed0498b2015-12-08 23:20:426776 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
6777 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]f878230e2014-04-03 15:36:146778
[email protected]f7022f32014-08-21 16:32:196779 r->Start();
[email protected]f878230e2014-04-03 15:36:146780 base::RunLoop().Run();
6781
maksim.sisovb53724b52016-09-16 05:30:506782 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:196783 EXPECT_EQ(original_url, r->original_url());
6784 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146785}
6786
lizeb5120f6dc2016-02-19 09:29:446787TEST_F(URLRequestTestHTTP, UnsupportedReferrerScheme) {
6788 ASSERT_TRUE(http_test_server()->Start());
6789
6790 const std::string referrer("foobar://totally.legit.referrer");
6791 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366792 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
lizeb5120f6dc2016-02-19 09:29:446793 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
6794 req->SetReferrer(referrer);
6795 req->Start();
6796 base::RunLoop().Run();
6797
6798 EXPECT_EQ(std::string("None"), d.data_received());
6799}
6800
[email protected]316c1e5e2012-09-12 15:17:446801TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
tommycli59a63432015-11-06 00:10:556802 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446803
6804 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366805 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556806 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196807 req->SetReferrer("http://user:[email protected]/");
6808 req->Start();
[email protected]255620da2013-08-19 13:14:296809 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446810
6811 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6812}
6813
[email protected]99ecf6e2013-04-10 22:46:136814TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
tommycli59a63432015-11-06 00:10:556815 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136816
6817 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366818 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556819 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196820 req->SetReferrer("http://foo.com/test#fragment");
6821 req->Start();
[email protected]255620da2013-08-19 13:14:296822 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136823
6824 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6825}
6826
6827TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
tommycli59a63432015-11-06 00:10:556828 ASSERT_TRUE(http_test_server()->Start());
[email protected]99ecf6e2013-04-10 22:46:136829
6830 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366831 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556832 http_test_server()->GetURL("/echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196833 req->SetReferrer("http://foo.com/test#fragment");
6834 req->SetReferrer("");
6835 req->Start();
[email protected]255620da2013-08-19 13:14:296836 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136837
6838 EXPECT_EQ(std::string("None"), d.data_received());
6839}
6840
[email protected]316c1e5e2012-09-12 15:17:446841TEST_F(URLRequestTestHTTP, CancelRedirect) {
tommycli59a63432015-11-06 00:10:556842 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446843
6844 TestDelegate d;
6845 {
6846 d.set_cancel_in_received_redirect(true);
danakj8522a25b2016-04-16 00:17:366847 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556848 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6849 &d));
[email protected]f7022f32014-08-21 16:32:196850 req->Start();
[email protected]255620da2013-08-19 13:14:296851 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446852
6853 EXPECT_EQ(1, d.response_started_count());
6854 EXPECT_EQ(0, d.bytes_received());
6855 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506856 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446857 }
6858}
6859
6860TEST_F(URLRequestTestHTTP, DeferredRedirect) {
tommycli59a63432015-11-06 00:10:556861 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446862
6863 TestDelegate d;
6864 {
6865 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556866 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366867 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366868 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046869
[email protected]f7022f32014-08-21 16:32:196870 req->Start();
[email protected]255620da2013-08-19 13:14:296871 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446872
6873 EXPECT_EQ(1, d.received_redirect_count());
6874
[email protected]f7022f32014-08-21 16:32:196875 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296876 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446877
6878 EXPECT_EQ(1, d.response_started_count());
6879 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506880 EXPECT_EQ(OK, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446881
[email protected]6cdfd7f2013-02-08 20:40:156882 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446883 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476884 path = path.Append(kTestFilePath);
[email protected]316c1e5e2012-09-12 15:17:446885 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6886
6887 std::string contents;
[email protected]82f84b92013-08-30 18:23:506888 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446889 EXPECT_EQ(contents, d.data_received());
6890 }
6891}
6892
[email protected]79e1fd62013-06-20 06:50:046893TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
tommycli59a63432015-11-06 00:10:556894 ASSERT_TRUE(http_test_server()->Start());
[email protected]79e1fd62013-06-20 06:50:046895
6896 TestDelegate d;
6897 {
6898 d.set_quit_on_redirect(true);
tommycli59a63432015-11-06 00:10:556899 GURL test_url(http_test_server()->GetURL("/redirect-test.html"));
danakj8522a25b2016-04-16 00:17:366900 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366901 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:046902
6903 EXPECT_FALSE(d.have_full_request_headers());
6904
[email protected]f7022f32014-08-21 16:32:196905 req->Start();
[email protected]255620da2013-08-19 13:14:296906 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046907
6908 EXPECT_EQ(1, d.received_redirect_count());
6909 EXPECT_TRUE(d.have_full_request_headers());
6910 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6911 d.ClearFullRequestHeaders();
6912
[email protected]f7022f32014-08-21 16:32:196913 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296914 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046915
tommycli59a63432015-11-06 00:10:556916 GURL target_url(http_test_server()->GetURL("/with-headers.html"));
[email protected]79e1fd62013-06-20 06:50:046917 EXPECT_EQ(1, d.response_started_count());
6918 EXPECT_TRUE(d.have_full_request_headers());
6919 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6920 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506921 EXPECT_EQ(OK, d.request_status());
[email protected]79e1fd62013-06-20 06:50:046922
6923 base::FilePath path;
6924 PathService::Get(base::DIR_SOURCE_ROOT, &path);
mmenke9f2ec60c2015-06-01 20:59:476925 path = path.Append(kTestFilePath);
[email protected]79e1fd62013-06-20 06:50:046926 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6927
6928 std::string contents;
[email protected]82f84b92013-08-30 18:23:506929 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046930 EXPECT_EQ(contents, d.data_received());
6931 }
6932}
6933
[email protected]316c1e5e2012-09-12 15:17:446934TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
tommycli59a63432015-11-06 00:10:556935 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446936
6937 TestDelegate d;
6938 {
6939 d.set_quit_on_redirect(true);
danakj8522a25b2016-04-16 00:17:366940 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556941 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY,
6942 &d));
[email protected]f7022f32014-08-21 16:32:196943 req->Start();
[email protected]255620da2013-08-19 13:14:296944 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446945
6946 EXPECT_EQ(1, d.received_redirect_count());
6947
[email protected]f7022f32014-08-21 16:32:196948 req->Cancel();
[email protected]255620da2013-08-19 13:14:296949 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446950
6951 EXPECT_EQ(1, d.response_started_count());
6952 EXPECT_EQ(0, d.bytes_received());
6953 EXPECT_FALSE(d.received_data_before_response());
maksim.sisovb53724b52016-09-16 05:30:506954 EXPECT_EQ(ERR_ABORTED, d.request_status());
[email protected]316c1e5e2012-09-12 15:17:446955 }
6956}
6957
6958TEST_F(URLRequestTestHTTP, VaryHeader) {
tommycli59a63432015-11-06 00:10:556959 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:446960
[email protected]3b23a222013-05-15 21:33:256961 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446962 {
6963 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366964 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556965 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6966 &d));
[email protected]316c1e5e2012-09-12 15:17:446967 HttpRequestHeaders headers;
6968 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196969 req->SetExtraRequestHeaders(headers);
6970 req->Start();
[email protected]255620da2013-08-19 13:14:296971 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256972
6973 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196974 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256975 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446976 }
6977
[email protected]3b23a222013-05-15 21:33:256978 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446979 {
6980 TestDelegate d;
danakj8522a25b2016-04-16 00:17:366981 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:556982 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
6983 &d));
[email protected]316c1e5e2012-09-12 15:17:446984 HttpRequestHeaders headers;
6985 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196986 req->SetExtraRequestHeaders(headers);
6987 req->Start();
[email protected]255620da2013-08-19 13:14:296988 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446989
[email protected]f7022f32014-08-21 16:32:196990 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256991
6992 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196993 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256994 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446995 }
6996
[email protected]3b23a222013-05-15 21:33:256997 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446998 {
6999 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367000 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557001 http_test_server()->GetURL("/echoheadercache?foo"), DEFAULT_PRIORITY,
7002 &d));
[email protected]316c1e5e2012-09-12 15:17:447003 HttpRequestHeaders headers;
7004 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:197005 req->SetExtraRequestHeaders(headers);
7006 req->Start();
[email protected]255620da2013-08-19 13:14:297007 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447008
[email protected]f7022f32014-08-21 16:32:197009 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:257010
7011 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197012 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257013 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:447014 }
7015}
7016
7017TEST_F(URLRequestTestHTTP, BasicAuth) {
tommycli59a63432015-11-06 00:10:557018 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447019
7020 // populate the cache
7021 {
7022 TestDelegate d;
7023 d.set_credentials(AuthCredentials(kUser, kSecret));
7024
danakj8522a25b2016-04-16 00:17:367025 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557026 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197027 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447028
[email protected]255620da2013-08-19 13:14:297029 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447030
7031 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7032 }
7033
7034 // repeat request with end-to-end validation. since auth-basic results in a
7035 // cachable page, we expect this test to result in a 304. in which case, the
7036 // response should be fetched from the cache.
7037 {
7038 TestDelegate d;
7039 d.set_credentials(AuthCredentials(kUser, kSecret));
7040
danakj8522a25b2016-04-16 00:17:367041 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557042 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197043 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7044 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447045
[email protected]255620da2013-08-19 13:14:297046 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447047
7048 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7049
7050 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197051 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:447052 }
7053}
7054
7055// Check that Set-Cookie headers in 401 responses are respected.
7056// http://crbug.com/6450
7057TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
tommycli59a63432015-11-06 00:10:557058 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447059
7060 GURL url_requiring_auth =
tommycli59a63432015-11-06 00:10:557061 http_test_server()->GetURL("/auth-basic?set-cookie-if-challenged");
[email protected]316c1e5e2012-09-12 15:17:447062
7063 // Request a page that will give a 401 containing a Set-Cookie header.
7064 // Verify that when the transaction is restarted, it includes the new cookie.
7065 {
[email protected]ceefd7fd2012-11-29 00:36:247066 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447067 TestURLRequestContext context(true);
7068 context.set_network_delegate(&network_delegate);
7069 context.Init();
7070
7071 TestDelegate d;
7072 d.set_credentials(AuthCredentials(kUser, kSecret));
7073
danakj8522a25b2016-04-16 00:17:367074 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367075 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197076 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447077
[email protected]255620da2013-08-19 13:14:297078 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447079
7080 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7081
7082 // Make sure we sent the cookie in the restarted transaction.
7083 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7084 != std::string::npos);
7085 }
7086
7087 // Same test as above, except this time the restart is initiated earlier
7088 // (without user intervention since identity is embedded in the URL).
7089 {
[email protected]ceefd7fd2012-11-29 00:36:247090 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447091 TestURLRequestContext context(true);
7092 context.set_network_delegate(&network_delegate);
7093 context.Init();
7094
7095 TestDelegate d;
7096
7097 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:187098 replacements.SetUsernameStr("user2");
7099 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:447100 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
7101
danakj8522a25b2016-04-16 00:17:367102 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367103 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197104 r->Start();
[email protected]316c1e5e2012-09-12 15:17:447105
[email protected]255620da2013-08-19 13:14:297106 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447107
7108 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
7109
7110 // Make sure we sent the cookie in the restarted transaction.
7111 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
7112 != std::string::npos);
7113 }
7114}
7115
[email protected]58e32bb2013-01-21 18:23:257116// Tests that load timing works as expected with auth and the cache.
7117TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
tommycli59a63432015-11-06 00:10:557118 ASSERT_TRUE(http_test_server()->Start());
[email protected]58e32bb2013-01-21 18:23:257119
7120 // populate the cache
7121 {
7122 TestDelegate d;
7123 d.set_credentials(AuthCredentials(kUser, kSecret));
7124
danakj8522a25b2016-04-16 00:17:367125 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557126 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197127 r->Start();
[email protected]58e32bb2013-01-21 18:23:257128
[email protected]255620da2013-08-19 13:14:297129 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257130
7131 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7132
7133 LoadTimingInfo load_timing_info_before_auth;
7134 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
7135 &load_timing_info_before_auth));
7136 TestLoadTimingNotReused(load_timing_info_before_auth,
7137 CONNECT_TIMING_HAS_DNS_TIMES);
7138
7139 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197140 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:257141 // The test server does not support keep alive sockets, so the second
7142 // request with auth should use a new socket.
7143 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
7144 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
7145 load_timing_info.socket_log_id);
7146 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
7147 load_timing_info.connect_timing.connect_start);
7148 }
7149
[email protected]3b23a222013-05-15 21:33:257150 // Repeat request with end-to-end validation. Since auth-basic results in a
7151 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:257152 // response should be fetched from the cache.
7153 {
7154 TestDelegate d;
7155 d.set_credentials(AuthCredentials(kUser, kSecret));
7156
danakj8522a25b2016-04-16 00:17:367157 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557158 http_test_server()->GetURL("/auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197159 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
7160 r->Start();
[email protected]58e32bb2013-01-21 18:23:257161
[email protected]255620da2013-08-19 13:14:297162 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:257163
7164 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
7165
7166 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:197167 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:257168
[email protected]3b23a222013-05-15 21:33:257169 // Since there was a request that went over the wire, the load timing
7170 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:257171 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:197172 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:257173 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:257174 }
7175}
7176
[email protected]316c1e5e2012-09-12 15:17:447177// In this test, we do a POST which the server will 302 redirect.
7178// The subsequent transaction should use GET, and should not send the
7179// Content-Type header.
7180// http://code.google.com/p/chromium/issues/detail?id=843
7181TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
tommycli59a63432015-11-06 00:10:557182 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447183
7184 const char kData[] = "hello world";
7185
7186 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367187 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557188 http_test_server()->GetURL("/redirect-to-echoall"), DEFAULT_PRIORITY,
7189 &d));
[email protected]f7022f32014-08-21 16:32:197190 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077191 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447192
7193 // Set headers (some of which are specific to the POST).
7194 HttpRequestHeaders headers;
7195 headers.AddHeadersFromString(
7196 "Content-Type: multipart/form-data; "
7197 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
7198 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
7199 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
7200 "Accept-Language: en-US,en\r\n"
7201 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
7202 "Content-Length: 11\r\n"
7203 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:197204 req->SetExtraRequestHeaders(headers);
7205 req->Start();
[email protected]255620da2013-08-19 13:14:297206 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447207
7208 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:197209 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:447210 EXPECT_EQ("text/html", mime_type);
7211
7212 const std::string& data = d.data_received();
7213
7214 // Check that the post-specific headers were stripped:
7215 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
7216 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
7217 EXPECT_FALSE(ContainsString(data, "Origin:"));
7218
7219 // These extra request headers should not have been stripped.
7220 EXPECT_TRUE(ContainsString(data, "Accept:"));
7221 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
7222 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
7223}
7224
jww5fe460ff2015-03-28 00:22:517225// The following tests check that we handle mutating the request for HTTP
7226// redirects as expected.
7227// See https://crbug.com/56373, https://crbug.com/102130, and
7228// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:447229
7230TEST_F(URLRequestTestHTTP, Redirect301Tests) {
tommycli59a63432015-11-06 00:10:557231 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447232
tommycli59a63432015-11-06 00:10:557233 const GURL url = http_test_server()->GetURL("/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:517234 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557235 http_test_server()->GetURL("/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:447236
7237 HTTPRedirectMethodTest(url, "POST", "GET", true);
7238 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7239 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517240
7241 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7242 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7243 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7244 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7245 std::string());
[email protected]316c1e5e2012-09-12 15:17:447246}
7247
7248TEST_F(URLRequestTestHTTP, Redirect302Tests) {
tommycli59a63432015-11-06 00:10:557249 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447250
tommycli59a63432015-11-06 00:10:557251 const GURL url = http_test_server()->GetURL("/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:517252 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557253 http_test_server()->GetURL("/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:447254
7255 HTTPRedirectMethodTest(url, "POST", "GET", true);
7256 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7257 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517258
7259 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7260 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7261 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7262 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7263 std::string());
[email protected]316c1e5e2012-09-12 15:17:447264}
7265
7266TEST_F(URLRequestTestHTTP, Redirect303Tests) {
tommycli59a63432015-11-06 00:10:557267 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447268
tommycli59a63432015-11-06 00:10:557269 const GURL url = http_test_server()->GetURL("/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:517270 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557271 http_test_server()->GetURL("/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:447272
7273 HTTPRedirectMethodTest(url, "POST", "GET", true);
7274 HTTPRedirectMethodTest(url, "PUT", "GET", true);
7275 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517276
7277 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7278 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7279 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
7280 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
7281 std::string());
[email protected]316c1e5e2012-09-12 15:17:447282}
7283
7284TEST_F(URLRequestTestHTTP, Redirect307Tests) {
tommycli59a63432015-11-06 00:10:557285 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447286
tommycli59a63432015-11-06 00:10:557287 const GURL url = http_test_server()->GetURL("/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:517288 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557289 http_test_server()->GetURL("/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:447290
7291 HTTPRedirectMethodTest(url, "POST", "POST", true);
7292 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7293 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517294
7295 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7296 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7297 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7298 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:447299}
7300
[email protected]0a17aab32014-04-24 03:32:377301TEST_F(URLRequestTestHTTP, Redirect308Tests) {
tommycli59a63432015-11-06 00:10:557302 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377303
tommycli59a63432015-11-06 00:10:557304 const GURL url = http_test_server()->GetURL("/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:517305 const GURL https_redirect_url =
tommycli59a63432015-11-06 00:10:557306 http_test_server()->GetURL("/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:377307
7308 HTTPRedirectMethodTest(url, "POST", "POST", true);
7309 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
7310 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:517311
7312 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
7313 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
7314 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
7315 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:377316}
7317
7318// Make sure that 308 responses without bodies are not treated as redirects.
7319// Certain legacy apis that pre-date the response code expect this behavior
7320// (Like Google Drive).
7321TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
tommycli59a63432015-11-06 00:10:557322 ASSERT_TRUE(http_test_server()->Start());
[email protected]0a17aab32014-04-24 03:32:377323
7324 TestDelegate d;
tommycli59a63432015-11-06 00:10:557325 const GURL url = http_test_server()->GetURL("/308-without-location-header");
[email protected]0a17aab32014-04-24 03:32:377326
danakj8522a25b2016-04-16 00:17:367327 std::unique_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367328 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:377329
[email protected]f7022f32014-08-21 16:32:197330 request->Start();
[email protected]0a17aab32014-04-24 03:32:377331 base::RunLoop().Run();
maksim.sisovb53724b52016-09-16 05:30:507332 EXPECT_EQ(OK, d.request_status());
[email protected]0a17aab32014-04-24 03:32:377333 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:197334 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:377335 EXPECT_EQ("This is not a redirect.", d.data_received());
7336}
7337
[email protected]f878230e2014-04-03 15:36:147338TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
tommycli59a63432015-11-06 00:10:557339 ASSERT_TRUE(http_test_server()->Start());
[email protected]f878230e2014-04-03 15:36:147340
tommycli59a63432015-11-06 00:10:557341 GURL original_url(
7342 http_test_server()->GetURL("/redirect302-to-echo#fragment"));
7343 GURL expected_url(http_test_server()->GetURL("/echo#fragment"));
[email protected]f878230e2014-04-03 15:36:147344
7345 TestDelegate d;
7346 {
danakj8522a25b2016-04-16 00:17:367347 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367348 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:147349
[email protected]f7022f32014-08-21 16:32:197350 r->Start();
[email protected]f878230e2014-04-03 15:36:147351 base::RunLoop().Run();
7352
[email protected]f7022f32014-08-21 16:32:197353 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507354 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197355 EXPECT_EQ(original_url, r->original_url());
7356 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:147357 }
7358}
7359
[email protected]cba24642014-08-15 20:49:597360TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557361 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597362
tommycli59a63432015-11-06 00:10:557363 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597364 GURL first_party_url("http://example.com");
7365
7366 TestDelegate d;
7367 {
danakj8522a25b2016-04-16 00:17:367368 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367369 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197370 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:597371
[email protected]f7022f32014-08-21 16:32:197372 r->Start();
[email protected]cba24642014-08-15 20:49:597373 base::RunLoop().Run();
7374
[email protected]f7022f32014-08-21 16:32:197375 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507376 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197377 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597378 }
7379}
7380
7381TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
tommycli59a63432015-11-06 00:10:557382 ASSERT_TRUE(http_test_server()->Start());
[email protected]cba24642014-08-15 20:49:597383
tommycli59a63432015-11-06 00:10:557384 GURL url(http_test_server()->GetURL("/redirect302-to-echo"));
[email protected]cba24642014-08-15 20:49:597385 GURL original_first_party_url("http://example.com");
tommycli59a63432015-11-06 00:10:557386 GURL expected_first_party_url(http_test_server()->GetURL("/echo"));
[email protected]cba24642014-08-15 20:49:597387
7388 TestDelegate d;
7389 {
danakj8522a25b2016-04-16 00:17:367390 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:367391 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197392 r->set_first_party_for_cookies(original_first_party_url);
7393 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:597394 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
7395
[email protected]f7022f32014-08-21 16:32:197396 r->Start();
[email protected]cba24642014-08-15 20:49:597397 base::RunLoop().Run();
7398
[email protected]f7022f32014-08-21 16:32:197399 EXPECT_EQ(2U, r->url_chain().size());
maksim.sisovb53724b52016-09-16 05:30:507400 EXPECT_EQ(OK, d.request_status());
[email protected]f7022f32014-08-21 16:32:197401 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:597402 }
7403}
7404
[email protected]316c1e5e2012-09-12 15:17:447405TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
tommycli59a63432015-11-06 00:10:557406 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447407
7408 const char kData[] = "hello world";
7409
7410 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367411 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557412 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197413 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077414 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447415 HttpRequestHeaders headers;
7416 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517417 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197418 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447419
danakj8522a25b2016-04-16 00:17:367420 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557421 req.get(), &default_network_delegate_,
7422 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427423 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7424 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447425
[email protected]f7022f32014-08-21 16:32:197426 req->Start();
[email protected]255620da2013-08-19 13:14:297427 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197428 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:447429}
7430
7431TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
tommycli59a63432015-11-06 00:10:557432 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447433
7434 const char kData[] = "hello world";
7435
7436 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367437 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557438 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197439 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077440 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:447441 HttpRequestHeaders headers;
7442 headers.SetHeader(HttpRequestHeaders::kContentLength,
riceac912aec2015-07-09 07:26:517443 base::SizeTToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:197444 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:447445
danakj8522a25b2016-04-16 00:17:367446 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557447 req.get(), &default_network_delegate_,
7448 http_test_server()->GetURL("/echo"),
[email protected]7983c4a2014-03-12 01:47:097449 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
mmenkeed0498b2015-12-08 23:20:427450 "Very Good Reason"));
7451 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]316c1e5e2012-09-12 15:17:447452
[email protected]f7022f32014-08-21 16:32:197453 req->Start();
[email protected]255620da2013-08-19 13:14:297454 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197455 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:447456 EXPECT_EQ(kData, d.data_received());
7457}
7458
7459// Check that default A-L header is sent.
7460TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557461 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447462
[email protected]8790210c2013-12-02 05:29:537463 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:247464 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447465 TestURLRequestContext context(true);
7466 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:437467 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447468 context.Init();
7469
7470 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367471 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557472 http_test_server()->GetURL("/echoheader?Accept-Language"),
7473 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197474 req->Start();
[email protected]255620da2013-08-19 13:14:297475 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447476 EXPECT_EQ("en", d.data_received());
7477}
7478
7479// Check that an empty A-L header is not sent. http://crbug.com/77365.
7480TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557481 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447482
[email protected]8790210c2013-12-02 05:29:537483 std::string empty_string; // Avoid most vexing parse on line below.
7484 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:247485 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:447486 TestURLRequestContext context(true);
7487 context.set_network_delegate(&network_delegate);
7488 context.Init();
7489 // We override the language after initialization because empty entries
7490 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:437491 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:447492
7493 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367494 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557495 http_test_server()->GetURL("/echoheader?Accept-Language"),
7496 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197497 req->Start();
[email protected]255620da2013-08-19 13:14:297498 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447499 EXPECT_EQ("None", d.data_received());
7500}
7501
7502// Check that if request overrides the A-L header, the default is not appended.
7503// See http://crbug.com/20894
7504TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
tommycli59a63432015-11-06 00:10:557505 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447506
7507 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367508 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557509 http_test_server()->GetURL("/echoheader?Accept-Language"),
7510 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447511 HttpRequestHeaders headers;
7512 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:197513 req->SetExtraRequestHeaders(headers);
7514 req->Start();
[email protected]255620da2013-08-19 13:14:297515 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447516 EXPECT_EQ(std::string("ru"), d.data_received());
7517}
7518
7519// Check that default A-E header is sent.
7520TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557521 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447522
7523 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367524 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557525 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7526 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447527 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:197528 req->SetExtraRequestHeaders(headers);
7529 req->Start();
[email protected]255620da2013-08-19 13:14:297530 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447531 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
7532}
7533
7534// Check that if request overrides the A-E header, the default is not appended.
7535// See http://crbug.com/47381
7536TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
tommycli59a63432015-11-06 00:10:557537 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447538
7539 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367540 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557541 http_test_server()->GetURL("/echoheader?Accept-Encoding"),
7542 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447543 HttpRequestHeaders headers;
7544 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:197545 req->SetExtraRequestHeaders(headers);
7546 req->Start();
[email protected]255620da2013-08-19 13:14:297547 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447548 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
7549 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
7550}
7551
[email protected]84f05432013-03-15 01:00:127552// Check that setting the A-C header sends the proper header.
7553TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
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-Charset"),
7559 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447560 HttpRequestHeaders headers;
7561 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:197562 req->SetExtraRequestHeaders(headers);
7563 req->Start();
[email protected]255620da2013-08-19 13:14:297564 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447565 EXPECT_EQ(std::string("koi-8r"), d.data_received());
7566}
7567
7568// Check that default User-Agent header is sent.
7569TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
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?User-Agent"), DEFAULT_PRIORITY,
7575 &d));
[email protected]f7022f32014-08-21 16:32:197576 req->Start();
[email protected]255620da2013-08-19 13:14:297577 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:197578 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:377579 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447580}
7581
7582// Check that if request overrides the User-Agent header,
7583// the default is not appended.
marqf14fff8d2015-12-02 15:52:297584// TODO(crbug.com/564656) This test is flaky on iOS.
7585#if defined(OS_IOS)
7586#define MAYBE_OverrideUserAgent FLAKY_OverrideUserAgent
7587#else
7588#define MAYBE_OverrideUserAgent OverrideUserAgent
7589#endif
7590TEST_F(URLRequestTestHTTP, MAYBE_OverrideUserAgent) {
tommycli59a63432015-11-06 00:10:557591 ASSERT_TRUE(http_test_server()->Start());
[email protected]316c1e5e2012-09-12 15:17:447592
7593 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367594 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557595 http_test_server()->GetURL("/echoheader?User-Agent"), DEFAULT_PRIORITY,
7596 &d));
[email protected]316c1e5e2012-09-12 15:17:447597 HttpRequestHeaders headers;
7598 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:197599 req->SetExtraRequestHeaders(headers);
7600 req->Start();
[email protected]255620da2013-08-19 13:14:297601 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:357602 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447603}
7604
[email protected]ee4c30d2012-11-07 15:08:437605// Check that a NULL HttpUserAgentSettings causes the corresponding empty
7606// User-Agent header to be sent but does not send the Accept-Language and
7607// Accept-Charset headers.
7608TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
tommycli59a63432015-11-06 00:10:557609 ASSERT_TRUE(http_test_server()->Start());
[email protected]ee4c30d2012-11-07 15:08:437610
[email protected]ceefd7fd2012-11-29 00:36:247611 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:437612 TestURLRequestContext context(true);
7613 context.set_network_delegate(&network_delegate);
7614 context.Init();
7615 // We override the HttpUserAgentSettings after initialization because empty
7616 // entries get overridden by Init().
7617 context.set_http_user_agent_settings(NULL);
7618
7619 struct {
7620 const char* request;
7621 const char* expected_response;
tommycli59a63432015-11-06 00:10:557622 } tests[] = {{"/echoheader?Accept-Language", "None"},
7623 {"/echoheader?Accept-Charset", "None"},
7624 {"/echoheader?User-Agent", ""}};
[email protected]ee4c30d2012-11-07 15:08:437625
viettrungluue4a8b882014-10-16 06:17:387626 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:437627 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367628 std::unique_ptr<URLRequest> req(context.CreateRequest(
tommycli59a63432015-11-06 00:10:557629 http_test_server()->GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197630 req->Start();
[email protected]255620da2013-08-19 13:14:297631 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:437632 EXPECT_EQ(tests[i].expected_response, d.data_received())
7633 << " Request = \"" << tests[i].request << "\"";
7634 }
7635}
7636
[email protected]5033ab82013-03-22 20:17:467637// Make sure that URLRequest passes on its priority updates to
7638// newly-created jobs after the first one.
7639TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
tommycli59a63432015-11-06 00:10:557640 ASSERT_TRUE(http_test_server()->Start());
[email protected]5033ab82013-03-22 20:17:467641
7642 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367643 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557644 http_test_server()->GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197645 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:467646
danakj8522a25b2016-04-16 00:17:367647 std::unique_ptr<URLRequestRedirectJob> redirect_job(new URLRequestRedirectJob(
tommycli59a63432015-11-06 00:10:557648 req.get(), &default_network_delegate_,
7649 http_test_server()->GetURL("/echo"),
mmenkeed0498b2015-12-08 23:20:427650 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason"));
7651 AddTestInterceptor()->set_main_intercept_job(std::move(redirect_job));
[email protected]5033ab82013-03-22 20:17:467652
[email protected]f7022f32014-08-21 16:32:197653 req->SetPriority(LOW);
7654 req->Start();
7655 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:467656
mmenkeed0498b2015-12-08 23:20:427657 RequestPriority job_priority;
danakj8522a25b2016-04-16 00:17:367658 std::unique_ptr<URLRequestJob> job(new PriorityMonitoringURLRequestJob(
mmenkeed0498b2015-12-08 23:20:427659 req.get(), &default_network_delegate_, &job_priority));
7660 AddTestInterceptor()->set_main_intercept_job(std::move(job));
[email protected]5033ab82013-03-22 20:17:467661
7662 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:297663 base::RunLoop().Run();
mmenkeed0498b2015-12-08 23:20:427664 EXPECT_EQ(LOW, job_priority);
[email protected]5033ab82013-03-22 20:17:467665}
7666
[email protected]80abdad2014-03-15 00:20:547667// Check that creating a network request while entering/exiting suspend mode
7668// fails as it should. This is the only case where an HttpTransactionFactory
7669// does not return an HttpTransaction.
7670TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
7671 // Create a new HttpNetworkLayer that thinks it's suspended.
danakj8522a25b2016-04-16 00:17:367672 std::unique_ptr<HttpNetworkLayer> network_layer(new HttpNetworkLayer(
mmenke2281f3762015-11-02 20:38:177673 default_context_.http_transaction_factory()->GetSession()));
[email protected]80abdad2014-03-15 00:20:547674 network_layer->OnSuspend();
7675
dchengc7eeda422015-12-26 03:56:487676 HttpCache http_cache(std::move(network_layer),
mmenkee65e7af2015-10-13 17:16:427677 HttpCache::DefaultBackend::InMemory(0), true);
[email protected]80abdad2014-03-15 00:20:547678
7679 TestURLRequestContext context(true);
7680 context.set_http_transaction_factory(&http_cache);
7681 context.Init();
7682
7683 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367684 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367685 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197686 req->Start();
[email protected]80abdad2014-03-15 00:20:547687 base::RunLoop().Run();
7688
7689 EXPECT_TRUE(d.request_failed());
maksim.sisovb53724b52016-09-16 05:30:507690 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, d.request_status());
[email protected]80abdad2014-03-15 00:20:547691}
7692
mmenke2281f3762015-11-02 20:38:177693namespace {
[email protected]80abdad2014-03-15 00:20:547694
mmenke2281f3762015-11-02 20:38:177695// HttpTransactionFactory that synchronously fails to create transactions.
7696class FailingHttpTransactionFactory : public HttpTransactionFactory {
7697 public:
7698 explicit FailingHttpTransactionFactory(HttpNetworkSession* network_session)
7699 : network_session_(network_session) {}
7700
7701 ~FailingHttpTransactionFactory() override {}
7702
7703 // HttpTransactionFactory methods:
7704 int CreateTransaction(RequestPriority priority,
danakj8522a25b2016-04-16 00:17:367705 std::unique_ptr<HttpTransaction>* trans) override {
mmenke2281f3762015-11-02 20:38:177706 return ERR_FAILED;
7707 }
7708
7709 HttpCache* GetCache() override { return nullptr; }
7710
7711 HttpNetworkSession* GetSession() override { return network_session_; }
7712
7713 private:
7714 HttpNetworkSession* network_session_;
7715
7716 DISALLOW_COPY_AND_ASSIGN(FailingHttpTransactionFactory);
7717};
7718
7719} // namespace
7720
7721// Check that when a request that fails to create an HttpTransaction can be
7722// cancelled while the failure notification is pending, and doesn't send two
7723// failure notifications.
7724//
7725// This currently only happens when in suspend mode and there's no cache, but
7726// just use a special HttpTransactionFactory, to avoid depending on those
7727// behaviors.
7728TEST_F(URLRequestTestHTTP, NetworkCancelAfterCreateTransactionFailsTest) {
7729 FailingHttpTransactionFactory http_transaction_factory(
7730 default_context_.http_transaction_factory()->GetSession());
[email protected]80abdad2014-03-15 00:20:547731 TestURLRequestContext context(true);
mmenke2281f3762015-11-02 20:38:177732 context.set_http_transaction_factory(&http_transaction_factory);
7733 context.set_network_delegate(default_network_delegate());
[email protected]80abdad2014-03-15 00:20:547734 context.Init();
7735
7736 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367737 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:367738 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
mmenke2281f3762015-11-02 20:38:177739 // Don't send cookies (Collecting cookies is asynchronous, and need request to
7740 // try to create an HttpNetworkTransaction synchronously on start).
7741 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
[email protected]f7022f32014-08-21 16:32:197742 req->Start();
mmenke2281f3762015-11-02 20:38:177743 req->Cancel();
[email protected]80abdad2014-03-15 00:20:547744 base::RunLoop().Run();
mmenke2281f3762015-11-02 20:38:177745 // Run pending error task, if there is one.
7746 base::RunLoop().RunUntilIdle();
[email protected]80abdad2014-03-15 00:20:547747
7748 EXPECT_TRUE(d.request_failed());
mmenke2281f3762015-11-02 20:38:177749 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:507750 EXPECT_EQ(ERR_ABORTED, d.request_status());
mmenke2281f3762015-11-02 20:38:177751
7752 // NetworkDelegate should see the cancellation, but not the error.
7753 EXPECT_EQ(1, default_network_delegate()->canceled_requests());
7754 EXPECT_EQ(0, default_network_delegate()->error_count());
[email protected]80abdad2014-03-15 00:20:547755}
7756
ttuttlec0c828492015-05-15 01:25:557757TEST_F(URLRequestTestHTTP, NetworkAccessedSetOnNetworkRequest) {
tommycli59a63432015-11-06 00:10:557758 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557759
7760 TestDelegate d;
tommycli59a63432015-11-06 00:10:557761 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367762 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557763 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7764
7765 req->Start();
7766 base::RunLoop().Run();
7767
7768 EXPECT_TRUE(req->response_info().network_accessed);
7769}
7770
7771TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnCachedResponse) {
tommycli59a63432015-11-06 00:10:557772 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557773
7774 // Populate the cache.
7775 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367776 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:557777 http_test_server()->GetURL("/cachetime"), DEFAULT_PRIORITY, &d));
ttuttlec0c828492015-05-15 01:25:557778 req->Start();
7779 base::RunLoop().Run();
7780
maksim.sisovb53724b52016-09-16 05:30:507781 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557782 EXPECT_TRUE(req->response_info().network_accessed);
7783 EXPECT_FALSE(req->response_info().was_cached);
7784
tommycli59a63432015-11-06 00:10:557785 req = default_context_.CreateRequest(http_test_server()->GetURL("/cachetime"),
ttuttlec0c828492015-05-15 01:25:557786 DEFAULT_PRIORITY, &d);
7787 req->Start();
7788 base::RunLoop().Run();
7789
maksim.sisovb53724b52016-09-16 05:30:507790 EXPECT_EQ(OK, d.request_status());
ttuttlec0c828492015-05-15 01:25:557791 EXPECT_FALSE(req->response_info().network_accessed);
7792 EXPECT_TRUE(req->response_info().was_cached);
7793}
7794
7795TEST_F(URLRequestTestHTTP, NetworkAccessedClearOnLoadOnlyFromCache) {
tommycli59a63432015-11-06 00:10:557796 ASSERT_TRUE(http_test_server()->Start());
ttuttlec0c828492015-05-15 01:25:557797
7798 TestDelegate d;
tommycli59a63432015-11-06 00:10:557799 GURL test_url(http_test_server()->GetURL("/"));
danakj8522a25b2016-04-16 00:17:367800 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:557801 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
7802 req->SetLoadFlags(LOAD_ONLY_FROM_CACHE);
7803
7804 req->Start();
7805 base::RunLoop().Run();
7806
7807 EXPECT_FALSE(req->response_info().network_accessed);
7808}
7809
rdsmith5eb6fbc2016-10-21 17:36:087810// Test that a single job with a throttled priority completes
7811// correctly in the absence of contention.
7812TEST_F(URLRequestTestHTTP, ThrottledPriority) {
7813 ASSERT_TRUE(http_test_server()->Start());
7814
7815 TestDelegate d;
7816 GURL test_url(http_test_server()->GetURL("/"));
7817 std::unique_ptr<URLRequest> req(
7818 default_context_.CreateRequest(test_url, THROTTLED, &d));
7819 req->Start();
7820 base::RunLoop().Run();
7821
7822 EXPECT_TRUE(req->status().is_success());
7823}
7824
ricea3a1c71f2016-06-17 10:05:267825TEST_F(URLRequestTestHTTP, RawBodyBytesNoContentEncoding) {
7826 ASSERT_TRUE(http_test_server()->Start());
7827
7828 TestDelegate d;
7829 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7830 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
7831 req->Start();
7832 base::RunLoop().Run();
7833
7834 EXPECT_EQ(5, req->GetRawBodyBytes());
7835}
7836
7837TEST_F(URLRequestTestHTTP, RawBodyBytesGzipEncoding) {
7838 ASSERT_TRUE(http_test_server()->Start());
7839
7840 TestDelegate d;
7841 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
7842 http_test_server()->GetURL("/gzip-encoded"), DEFAULT_PRIORITY, &d));
7843 req->Start();
7844 base::RunLoop().Run();
7845
7846 EXPECT_EQ(30, req->GetRawBodyBytes());
7847}
7848
bengr1bf8e942014-11-07 01:36:507849class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7850 public:
7851 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7852 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7853 // tests into the factory tests.
7854 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7855 }
7856
7857 void SetUpFactory() override {
7858 interceptor_ = new MockURLRequestInterceptor();
7859 job_factory_.reset(new URLRequestInterceptingJobFactory(
danakj8522a25b2016-04-16 00:17:367860 std::move(job_factory_), base::WrapUnique(interceptor_)));
bengr1bf8e942014-11-07 01:36:507861 }
7862
7863 MockURLRequestInterceptor* interceptor() const {
7864 return interceptor_;
7865 }
7866
7867 private:
7868 MockURLRequestInterceptor* interceptor_;
7869};
7870
7871TEST_F(URLRequestInterceptorTestHTTP,
7872 NetworkDelegateNotificationOnRedirectIntercept) {
7873 interceptor()->set_intercept_redirect(true);
7874 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7875 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7876
tommycli59a63432015-11-06 00:10:557877 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507878
7879 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367880 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557881 http_test_server()->GetURL("/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507882 req->Start();
7883 base::RunLoop().Run();
7884
7885 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7886 // Check we got one good response
maksim.sisovb53724b52016-09-16 05:30:507887 int status = d.request_status();
7888 EXPECT_EQ(OK, status);
7889 if (status == OK)
bengr1bf8e942014-11-07 01:36:507890 EXPECT_EQ(200, req->response_headers()->response_code());
7891
7892 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7893 EXPECT_EQ(1, d.response_started_count());
7894 EXPECT_EQ(0, d.received_redirect_count());
7895
7896 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007897 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507898 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7899}
7900
7901TEST_F(URLRequestInterceptorTestHTTP,
7902 NetworkDelegateNotificationOnErrorIntercept) {
7903 // Intercept that error and respond with an OK response.
7904 interceptor()->set_intercept_final_response(true);
7905 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7906 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7907 default_network_delegate()->set_can_be_intercepted_on_error(true);
7908
tommycli59a63432015-11-06 00:10:557909 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507910
7911 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367912 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557913 http_test_server()->GetURL("/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:367914 &d));
bengr1bf8e942014-11-07 01:36:507915 req->set_method("GET");
7916 req->Start();
7917 base::RunLoop().Run();
7918
7919 EXPECT_TRUE(interceptor()->did_intercept_final());
7920
7921 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:507922 int status = d.request_status();
7923 EXPECT_EQ(OK, status);
7924 if (status == OK)
bengr1bf8e942014-11-07 01:36:507925 EXPECT_EQ(200, req->response_headers()->response_code());
7926 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7927 EXPECT_EQ(1, d.response_started_count());
7928 EXPECT_EQ(0, d.received_redirect_count());
7929
7930 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007931 EXPECT_EQ(1, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507932 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7933}
7934
7935TEST_F(URLRequestInterceptorTestHTTP,
7936 NetworkDelegateNotificationOnResponseIntercept) {
7937 // Intercept that error and respond with an OK response.
7938 interceptor()->set_intercept_final_response(true);
7939
7940 // Intercept with a real URLRequestHttpJob.
7941 interceptor()->set_use_url_request_http_job(true);
7942
tommycli59a63432015-11-06 00:10:557943 ASSERT_TRUE(http_test_server()->Start());
bengr1bf8e942014-11-07 01:36:507944
7945 TestDelegate d;
danakj8522a25b2016-04-16 00:17:367946 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
tommycli59a63432015-11-06 00:10:557947 http_test_server()->GetURL("/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:507948 req->set_method("GET");
7949 req->Start();
7950 base::RunLoop().Run();
7951
7952 EXPECT_TRUE(interceptor()->did_intercept_final());
7953
7954 // Check we received one good response.
maksim.sisovb53724b52016-09-16 05:30:507955 int status = d.request_status();
7956 EXPECT_EQ(OK, status);
7957 if (status == OK)
bengr1bf8e942014-11-07 01:36:507958 EXPECT_EQ(200, req->response_headers()->response_code());
7959 EXPECT_EQ("hello", d.data_received());
7960 EXPECT_EQ(1, d.response_started_count());
7961 EXPECT_EQ(0, d.received_redirect_count());
7962
7963 EXPECT_EQ(1, default_network_delegate()->created_requests());
ryansturm2343cb62016-06-15 01:09:007964 EXPECT_EQ(2, default_network_delegate()->before_start_transaction_count());
bengr1bf8e942014-11-07 01:36:507965 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7966}
7967
mkwst0c5eab872014-11-21 14:18:547968class URLRequestTestReferrerPolicy : public URLRequestTest {
7969 public:
7970 URLRequestTestReferrerPolicy() {}
7971
tommycli59a63432015-11-06 00:10:557972 void InstantiateSameOriginServers(net::EmbeddedTestServer::Type type) {
7973 origin_server_.reset(new EmbeddedTestServer(type));
7974 if (type == net::EmbeddedTestServer::TYPE_HTTPS) {
7975 origin_server_->AddDefaultHandlers(
7976 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7977 } else {
7978 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7979 }
mkwst0c5eab872014-11-21 14:18:547980 ASSERT_TRUE(origin_server_->Start());
7981 }
7982
tommycli59a63432015-11-06 00:10:557983 void InstantiateCrossOriginServers(net::EmbeddedTestServer::Type origin_type,
7984 net::EmbeddedTestServer::Type dest_type) {
7985 origin_server_.reset(new EmbeddedTestServer(origin_type));
7986 if (origin_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7987 origin_server_->AddDefaultHandlers(
7988 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7989 } else {
7990 origin_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
7991 }
mkwst0c5eab872014-11-21 14:18:547992 ASSERT_TRUE(origin_server_->Start());
7993
tommycli59a63432015-11-06 00:10:557994 destination_server_.reset(new EmbeddedTestServer(dest_type));
7995 if (dest_type == net::EmbeddedTestServer::TYPE_HTTPS) {
7996 destination_server_->AddDefaultHandlers(
7997 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7998 } else {
7999 destination_server_->AddDefaultHandlers(base::FilePath(kTestFilePath));
8000 }
mkwst0c5eab872014-11-21 14:18:548001 ASSERT_TRUE(destination_server_->Start());
8002 }
8003
8004 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
8005 const GURL& referrer,
8006 const GURL& expected) {
8007 // Create and execute the request: we'll only have a |destination_server_|
8008 // if the origins are meant to be distinct. Otherwise, we'll use the
8009 // |origin_server_| for both endpoints.
8010 GURL destination_url =
tommycli59a63432015-11-06 00:10:558011 destination_server_ ? destination_server_->GetURL("/echoheader?Referer")
8012 : origin_server_->GetURL("/echoheader?Referer");
mkwst0c5eab872014-11-21 14:18:548013 GURL origin_url =
tommycli59a63432015-11-06 00:10:558014 origin_server_->GetURL("/server-redirect?" + destination_url.spec());
mkwst0c5eab872014-11-21 14:18:548015
8016 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368017 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368018 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:548019 req->set_referrer_policy(policy);
8020 req->SetReferrer(referrer.spec());
8021 req->Start();
8022 base::RunLoop().Run();
8023
8024 EXPECT_EQ(1, d.response_started_count());
8025 EXPECT_EQ(1, d.received_redirect_count());
8026 EXPECT_EQ(destination_url, req->url());
maksim.sisovb53724b52016-09-16 05:30:508027 EXPECT_EQ(OK, d.request_status());
mkwst0c5eab872014-11-21 14:18:548028 EXPECT_EQ(200, req->response_headers()->response_code());
8029
8030 EXPECT_EQ(expected.spec(), req->referrer());
8031 if (expected.is_empty())
8032 EXPECT_EQ("None", d.data_received());
8033 else
8034 EXPECT_EQ(expected.spec(), d.data_received());
8035 }
8036
tommycli59a63432015-11-06 00:10:558037 EmbeddedTestServer* origin_server() const { return origin_server_.get(); }
mkwst0c5eab872014-11-21 14:18:548038
8039 private:
danakj8522a25b2016-04-16 00:17:368040 std::unique_ptr<EmbeddedTestServer> origin_server_;
8041 std::unique_ptr<EmbeddedTestServer> destination_server_;
mkwst0c5eab872014-11-21 14:18:548042};
8043
8044TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
tommycli59a63432015-11-06 00:10:558045 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548046
8047 VerifyReferrerAfterRedirect(
8048 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558049 origin_server()->GetURL("/path/to/file.html"),
8050 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548051
8052 VerifyReferrerAfterRedirect(
8053 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558054 origin_server()->GetURL("/path/to/file.html"),
8055 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548056
8057 VerifyReferrerAfterRedirect(
8058 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558059 origin_server()->GetURL("/path/to/file.html"),
8060 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548061
8062 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558063 origin_server()->GetURL("/path/to/file.html"),
8064 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548065}
8066
tommycli59a63432015-11-06 00:10:558067TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
8068 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8069 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548070
8071 VerifyReferrerAfterRedirect(
8072 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558073 origin_server()->GetURL("/path/to/file.html"),
8074 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548075
8076 VerifyReferrerAfterRedirect(
8077 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558078 origin_server()->GetURL("/path/to/file.html"),
8079 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548080
8081 VerifyReferrerAfterRedirect(
8082 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558083 origin_server()->GetURL("/path/to/file.html"),
8084 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548085
8086 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558087 origin_server()->GetURL("/path/to/file.html"),
8088 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548089}
8090
8091TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
tommycli59a63432015-11-06 00:10:558092 InstantiateSameOriginServers(net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548093
8094 VerifyReferrerAfterRedirect(
8095 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558096 origin_server()->GetURL("/path/to/file.html"),
8097 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548098
8099 VerifyReferrerAfterRedirect(
8100 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558101 origin_server()->GetURL("/path/to/file.html"),
8102 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548103
8104 VerifyReferrerAfterRedirect(
8105 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558106 origin_server()->GetURL("/path/to/file.html"),
8107 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548108
8109 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558110 origin_server()->GetURL("/path/to/file.html"),
8111 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548112}
8113
tommycli59a63432015-11-06 00:10:558114TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
8115 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8116 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548117
8118 VerifyReferrerAfterRedirect(
8119 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558120 origin_server()->GetURL("/path/to/file.html"),
8121 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548122
8123 VerifyReferrerAfterRedirect(
8124 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558125 origin_server()->GetURL("/path/to/file.html"),
8126 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548127
8128 VerifyReferrerAfterRedirect(
8129 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558130 origin_server()->GetURL("/path/to/file.html"),
8131 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548132
8133 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558134 origin_server()->GetURL("/path/to/file.html"),
8135 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548136}
8137
tommycli59a63432015-11-06 00:10:558138TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
8139 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTP,
8140 net::EmbeddedTestServer::TYPE_HTTPS);
mkwst0c5eab872014-11-21 14:18:548141
8142 VerifyReferrerAfterRedirect(
8143 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558144 origin_server()->GetURL("/path/to/file.html"),
8145 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548146
8147 VerifyReferrerAfterRedirect(
8148 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558149 origin_server()->GetURL("/path/to/file.html"),
8150 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548151
8152 VerifyReferrerAfterRedirect(
8153 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558154 origin_server()->GetURL("/path/to/file.html"),
8155 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548156
8157 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558158 origin_server()->GetURL("/path/to/file.html"),
8159 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548160}
8161
tommycli59a63432015-11-06 00:10:558162TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
8163 InstantiateCrossOriginServers(net::EmbeddedTestServer::TYPE_HTTPS,
8164 net::EmbeddedTestServer::TYPE_HTTP);
mkwst0c5eab872014-11-21 14:18:548165
8166 VerifyReferrerAfterRedirect(
8167 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
tommycli59a63432015-11-06 00:10:558168 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548169
8170 VerifyReferrerAfterRedirect(
8171 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558172 origin_server()->GetURL("/path/to/file.html"), GURL());
mkwst0c5eab872014-11-21 14:18:548173
8174 VerifyReferrerAfterRedirect(
8175 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
tommycli59a63432015-11-06 00:10:558176 origin_server()->GetURL("/path/to/file.html"),
8177 origin_server()->GetURL("/"));
mkwst0c5eab872014-11-21 14:18:548178
8179 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
tommycli59a63432015-11-06 00:10:558180 origin_server()->GetURL("/path/to/file.html"),
8181 origin_server()->GetURL("/path/to/file.html"));
mkwst0c5eab872014-11-21 14:18:548182}
8183
[email protected]73e0bba2009-02-19 22:57:098184class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:508185 public:
[email protected]ef2bf422012-05-11 03:27:098186 HTTPSRequestTest() : default_context_(true) {
8187 default_context_.set_network_delegate(&default_network_delegate_);
8188 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:508189 }
dcheng67be2b1f2014-10-27 21:47:298190 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:508191
8192 protected:
[email protected]ceefd7fd2012-11-29 00:36:248193 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:098194 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:468195};
8196
[email protected]c044616e2013-02-20 02:01:268197TEST_F(HTTPSRequestTest, HTTPSGetTest) {
tommycli59a63432015-11-06 00:10:558198 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8199 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228200 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118201 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:468202
[email protected]ea224582008-12-07 20:25:468203 TestDelegate d;
8204 {
danakj8522a25b2016-04-16 00:17:368205 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558206 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198207 r->Start();
8208 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:468209
[email protected]255620da2013-08-19 13:14:298210 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:468211
8212 EXPECT_EQ(1, d.response_started_count());
8213 EXPECT_FALSE(d.received_data_before_response());
8214 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198215 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:198216 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198217 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198218 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198219 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:468220 }
[email protected]ea224582008-12-07 20:25:468221}
8222
[email protected]5774ada2010-07-15 06:30:548223TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
tommycli59a63432015-11-06 00:10:558224 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8225 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8226 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228227 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118228 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338229
8230 bool err_allowed = true;
8231 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8232 TestDelegate d;
8233 {
8234 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368235 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558236 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338237
[email protected]f7022f32014-08-21 16:32:198238 r->Start();
8239 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338240
[email protected]255620da2013-08-19 13:14:298241 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338242
8243 EXPECT_EQ(1, d.response_started_count());
8244 EXPECT_FALSE(d.received_data_before_response());
8245 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178246 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338247 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198248 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178249 } else {
[email protected]bacff652009-03-31 17:50:338250 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178251 }
[email protected]bacff652009-03-31 17:50:338252 }
8253 }
8254}
8255
[email protected]5774ada2010-07-15 06:30:548256TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
tommycli59a63432015-11-06 00:10:558257 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8258 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_EXPIRED);
8259 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228260 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:118261 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:338262
8263 // Iterate from false to true, just so that we do the opposite of the
8264 // previous test in order to increase test coverage.
8265 bool err_allowed = false;
8266 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
8267 TestDelegate d;
8268 {
8269 d.set_allow_certificate_errors(err_allowed);
danakj8522a25b2016-04-16 00:17:368270 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558271 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:338272
[email protected]f7022f32014-08-21 16:32:198273 r->Start();
8274 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:338275
[email protected]255620da2013-08-19 13:14:298276 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:338277
8278 EXPECT_EQ(1, d.response_started_count());
8279 EXPECT_FALSE(d.received_data_before_response());
8280 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:178281 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:338282 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:198283 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:178284 } else {
[email protected]bacff652009-03-31 17:50:338285 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:178286 }
[email protected]bacff652009-03-31 17:50:338287 }
8288 }
8289}
[email protected]73e0bba2009-02-19 22:57:098290
tommycli59a63432015-11-06 00:10:558291// TODO(svaldez): iOS tests are flaky with EmbeddedTestServer and transport
8292// security state. (see http://crbug.com/550977).
8293#if !defined(OS_IOS)
[email protected]316c1e5e2012-09-12 15:17:448294// This tests that a load of www.google.com with a certificate error sets
8295// the |certificate_errors_are_fatal| flag correctly. This flag will cause
8296// the interstitial to be fatal.
8297TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
tommycli59a63432015-11-06 00:10:558298 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8299 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8300 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448301 ASSERT_TRUE(test_server.Start());
8302
8303 // We require that the URL be www.google.com in order to pick up the
8304 // preloaded HSTS entries in the TransportSecurityState. This means that we
8305 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:248306 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448307
8308 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248309 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448310 TestURLRequestContext context(true);
8311 context.set_network_delegate(&network_delegate);
8312 context.set_host_resolver(&host_resolver);
8313 TransportSecurityState transport_security_state;
8314 context.set_transport_security_state(&transport_security_state);
8315 context.Init();
8316
8317 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368318 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198319 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368320 test_server.host_port_pair().port())),
8321 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448322
[email protected]f7022f32014-08-21 16:32:198323 r->Start();
8324 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448325
[email protected]255620da2013-08-19 13:14:298326 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448327
8328 EXPECT_EQ(1, d.response_started_count());
8329 EXPECT_FALSE(d.received_data_before_response());
8330 EXPECT_TRUE(d.have_certificate_errors());
8331 EXPECT_TRUE(d.certificate_errors_are_fatal());
8332}
8333
8334// This tests that cached HTTPS page loads do not cause any updates to the
8335// TransportSecurityState.
8336TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
8337 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
8338 // matter. It just has to be any error.
tommycli59a63432015-11-06 00:10:558339 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8340 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_MISMATCHED_NAME);
8341 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
[email protected]316c1e5e2012-09-12 15:17:448342 ASSERT_TRUE(test_server.Start());
8343
[email protected]9e6968d2014-05-07 21:46:268344 // We require that the URL be www.google.com in order to pick up the static
8345 // and dynamic STS and PKP entries in the TransportSecurityState. This means
8346 // that we have to use a MockHostResolver in order to direct www.google.com to
8347 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:448348
8349 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:248350 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:448351 TestURLRequestContext context(true);
8352 context.set_network_delegate(&network_delegate);
8353 context.set_host_resolver(&host_resolver);
8354 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:268355
martijnc0d6b622015-06-30 19:14:408356 TransportSecurityState::STSState static_sts_state;
8357 TransportSecurityState::PKPState static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268358 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408359 "www.google.com", &static_sts_state, &static_pkp_state));
[email protected]316c1e5e2012-09-12 15:17:448360 context.set_transport_security_state(&transport_security_state);
8361 context.Init();
8362
martijnc0d6b622015-06-30 19:14:408363 TransportSecurityState::STSState dynamic_sts_state;
8364 TransportSecurityState::PKPState dynamic_pkp_state;
8365 EXPECT_FALSE(transport_security_state.GetDynamicSTSState("www.google.com",
8366 &dynamic_sts_state));
8367 EXPECT_FALSE(transport_security_state.GetDynamicPKPState("www.google.com",
8368 &dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268369
[email protected]316c1e5e2012-09-12 15:17:448370 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368371 std::unique_ptr<URLRequest> r(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198372 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:368373 test_server.host_port_pair().port())),
8374 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448375
[email protected]f7022f32014-08-21 16:32:198376 r->Start();
8377 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448378
[email protected]255620da2013-08-19 13:14:298379 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448380
8381 EXPECT_EQ(1, d.response_started_count());
8382 EXPECT_FALSE(d.received_data_before_response());
8383 EXPECT_TRUE(d.have_certificate_errors());
8384 EXPECT_TRUE(d.certificate_errors_are_fatal());
8385
[email protected]9e6968d2014-05-07 21:46:268386 // Get a fresh copy of the states, and check that they haven't changed.
martijnc0d6b622015-06-30 19:14:408387 TransportSecurityState::STSState new_static_sts_state;
8388 TransportSecurityState::PKPState new_static_pkp_state;
[email protected]9e6968d2014-05-07 21:46:268389 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
martijnc0d6b622015-06-30 19:14:408390 "www.google.com", &new_static_sts_state, &new_static_pkp_state));
8391 TransportSecurityState::STSState new_dynamic_sts_state;
8392 TransportSecurityState::PKPState new_dynamic_pkp_state;
8393 EXPECT_FALSE(transport_security_state.GetDynamicSTSState(
8394 "www.google.com", &new_dynamic_sts_state));
8395 EXPECT_FALSE(transport_security_state.GetDynamicPKPState(
8396 "www.google.com", &new_dynamic_pkp_state));
[email protected]9e6968d2014-05-07 21:46:268397
martijnc0d6b622015-06-30 19:14:408398 EXPECT_EQ(new_static_sts_state.upgrade_mode, static_sts_state.upgrade_mode);
8399 EXPECT_EQ(new_static_sts_state.include_subdomains,
8400 static_sts_state.include_subdomains);
8401 EXPECT_EQ(new_static_pkp_state.include_subdomains,
8402 static_pkp_state.include_subdomains);
rsleevi91d4c9c2016-05-14 20:28:488403 EXPECT_EQ(new_static_pkp_state.spki_hashes, static_pkp_state.spki_hashes);
8404 EXPECT_EQ(new_static_pkp_state.bad_spki_hashes,
8405 static_pkp_state.bad_spki_hashes);
[email protected]316c1e5e2012-09-12 15:17:448406}
8407
[email protected]8ccc69f2012-11-28 19:52:148408// Make sure HSTS preserves a POST request's method and body.
8409TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
8410 static const char kData[] = "hello world";
8411
tommycli59a63432015-11-06 00:10:558412 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8413 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228414 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:148415 ASSERT_TRUE(test_server.Start());
8416
8417
8418 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8419 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
tommycli59a63432015-11-06 00:10:558420 // the EmbeddedTestServer. By default, MockHostResolver maps all hosts
[email protected]ce7d0cbc2013-05-03 18:57:228421 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:148422 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:148423
8424 // Force https for www.somewhere.com.
8425 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:208426 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
8427 bool include_subdomains = false;
8428 transport_security_state.AddHSTS("www.somewhere.com", expiry,
8429 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:148430
8431 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8432
8433 TestURLRequestContext context(true);
8434 context.set_host_resolver(&host_resolver);
8435 context.set_transport_security_state(&transport_security_state);
8436 context.set_network_delegate(&network_delegate);
8437 context.Init();
8438
8439 TestDelegate d;
8440 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
8441 // cause a certificate error. Ignore the error.
8442 d.set_allow_certificate_errors(true);
8443
danakj8522a25b2016-04-16 00:17:368444 std::unique_ptr<URLRequest> req(context.CreateRequest(
[email protected]f7022f32014-08-21 16:32:198445 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:368446 test_server.host_port_pair().port())),
8447 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198448 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:078449 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:148450
[email protected]f7022f32014-08-21 16:32:198451 req->Start();
[email protected]255620da2013-08-19 13:14:298452 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:148453
[email protected]f7022f32014-08-21 16:32:198454 EXPECT_EQ("https", req->url().scheme());
8455 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:148456 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:408457
8458 LoadTimingInfo load_timing_info;
8459 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
8460 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
8461 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:148462}
8463
rob4e0be1f2014-09-11 23:40:228464// Make sure that the CORS headers are added to cross-origin HSTS redirects.
8465TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
8466 static const char kOriginHeaderValue[] = "http://www.example.com";
8467
tommycli59a63432015-11-06 00:10:558468 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8469 test_server.ServeFilesFromSourceDirectory("net/data/ssl");
rob4e0be1f2014-09-11 23:40:228470 ASSERT_TRUE(test_server.Start());
8471
8472 // Per spec, TransportSecurityState expects a domain name, rather than an IP
8473 // address, so a MockHostResolver is needed to redirect example.net to the
tommycli59a63432015-11-06 00:10:558474 // EmbeddedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by
8475 // default.
rob4e0be1f2014-09-11 23:40:228476 MockHostResolver host_resolver;
8477
8478 TransportSecurityState transport_security_state;
8479 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
8480 bool include_subdomains = false;
8481 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
8482
8483 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
8484
8485 MockCertVerifier cert_verifier;
8486 cert_verifier.set_default_result(OK);
8487
8488 TestURLRequestContext context(true);
8489 context.set_host_resolver(&host_resolver);
8490 context.set_transport_security_state(&transport_security_state);
8491 context.set_network_delegate(&network_delegate);
8492 context.set_cert_verifier(&cert_verifier);
8493 context.Init();
8494
8495 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
8496 test_server.host_port_pair().port()));
8497 url::Replacements<char> replacements;
8498 const char kNewScheme[] = "https";
8499 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
8500 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
8501
8502 TestDelegate d;
8503 // Quit on redirect to allow response header inspection upon redirect.
8504 d.set_quit_on_redirect(true);
8505
danakj8522a25b2016-04-16 00:17:368506 std::unique_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:368507 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:228508 // Set Origin header to simulate a cross-origin request.
8509 HttpRequestHeaders request_headers;
8510 request_headers.SetHeader("Origin", kOriginHeaderValue);
8511 req->SetExtraRequestHeaders(request_headers);
8512
8513 req->Start();
8514 base::RunLoop().Run();
8515
8516 EXPECT_EQ(1, d.received_redirect_count());
8517
8518 const HttpResponseHeaders* headers = req->response_headers();
8519 std::string redirect_location;
8520 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
8521 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
8522
8523 std::string received_cors_header;
8524 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
8525 &received_cors_header));
8526 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
8527}
8528
davidbenb4c25b62016-06-24 02:39:278529// Test that DHE-only servers fail with the expected dedicated error code.
8530TEST_F(HTTPSRequestTest, DHE) {
8531 SpawnedTestServer::SSLOptions ssl_options;
8532 ssl_options.key_exchanges =
8533 SpawnedTestServer::SSLOptions::KEY_EXCHANGE_DHE_RSA;
8534 SpawnedTestServer test_server(
8535 SpawnedTestServer::TYPE_HTTPS, ssl_options,
8536 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8537 ASSERT_TRUE(test_server.Start());
8538
8539 TestDelegate d;
8540 {
8541 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
8542 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
8543
8544 r->Start();
8545 EXPECT_TRUE(r->is_pending());
8546
8547 base::RunLoop().Run();
8548
8549 EXPECT_EQ(1, d.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508550 EXPECT_EQ(ERR_SSL_OBSOLETE_CIPHER, d.request_status());
davidbenb4c25b62016-06-24 02:39:278551 }
8552}
8553
[email protected]316c1e5e2012-09-12 15:17:448554namespace {
8555
8556class SSLClientAuthTestDelegate : public TestDelegate {
8557 public:
8558 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
8559 }
dchengb03027d2014-10-21 12:00:208560 void OnCertificateRequested(URLRequest* request,
8561 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:448562 on_certificate_requested_count_++;
ki.stfu375812e2015-10-09 20:23:178563 base::MessageLoop::current()->QuitWhenIdle();
[email protected]316c1e5e2012-09-12 15:17:448564 }
8565 int on_certificate_requested_count() {
8566 return on_certificate_requested_count_;
8567 }
8568 private:
8569 int on_certificate_requested_count_;
8570};
8571
8572} // namespace
8573
8574// TODO(davidben): Test the rest of the code. Specifically,
8575// - Filtering which certificates to select.
8576// - Sending a certificate back.
8577// - Getting a certificate request in an SSL renegotiation sending the
8578// HTTP request.
8579TEST_F(HTTPSRequestTest, ClientAuthTest) {
tommycli59a63432015-11-06 00:10:558580 EmbeddedTestServer test_server(net::EmbeddedTestServer::TYPE_HTTPS);
8581 net::SSLServerConfig ssl_config;
ryanchung987b2ff2016-02-19 00:17:128582 ssl_config.client_cert_type =
8583 SSLServerConfig::ClientCertType::OPTIONAL_CLIENT_CERT;
tommycli59a63432015-11-06 00:10:558584 test_server.SetSSLConfig(net::EmbeddedTestServer::CERT_OK, ssl_config);
8585 test_server.AddDefaultHandlers(
[email protected]ce7d0cbc2013-05-03 18:57:228586 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448587 ASSERT_TRUE(test_server.Start());
8588
8589 SSLClientAuthTestDelegate d;
8590 {
danakj8522a25b2016-04-16 00:17:368591 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:558592 test_server.GetURL("/defaultresponse"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448593
[email protected]f7022f32014-08-21 16:32:198594 r->Start();
8595 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448596
[email protected]255620da2013-08-19 13:14:298597 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448598
8599 EXPECT_EQ(1, d.on_certificate_requested_count());
8600 EXPECT_FALSE(d.received_data_before_response());
8601 EXPECT_EQ(0, d.bytes_received());
8602
8603 // Send no certificate.
8604 // TODO(davidben): Get temporary client cert import (with keys) working on
8605 // all platforms so we can test sending a cert as well.
svaldez7872fd02015-11-19 21:10:548606 r->ContinueWithCertificate(nullptr, nullptr);
[email protected]316c1e5e2012-09-12 15:17:448607
[email protected]255620da2013-08-19 13:14:298608 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448609
8610 EXPECT_EQ(1, d.response_started_count());
8611 EXPECT_FALSE(d.received_data_before_response());
8612 EXPECT_NE(0, d.bytes_received());
8613 }
8614}
8615
8616TEST_F(HTTPSRequestTest, ResumeTest) {
8617 // Test that we attempt a session resume when making two connections to the
8618 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:228619 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448620 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228621 SpawnedTestServer test_server(
8622 SpawnedTestServer::TYPE_HTTPS,
8623 ssl_options,
8624 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448625 ASSERT_TRUE(test_server.Start());
8626
8627 SSLClientSocket::ClearSessionCache();
8628
8629 {
8630 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368631 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368632 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448633
[email protected]f7022f32014-08-21 16:32:198634 r->Start();
8635 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448636
[email protected]255620da2013-08-19 13:14:298637 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448638
8639 EXPECT_EQ(1, d.response_started_count());
8640 }
8641
8642 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8643 CloseAllConnections();
8644
8645 {
8646 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368647 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368648 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448649
[email protected]f7022f32014-08-21 16:32:198650 r->Start();
8651 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448652
[email protected]255620da2013-08-19 13:14:298653 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448654
8655 // The response will look like;
8656 // insert abc
8657 // lookup abc
8658 // insert xyz
8659 //
8660 // With a newline at the end which makes the split think that there are
8661 // four lines.
8662
8663 EXPECT_EQ(1, d.response_started_count());
brettw3a2c6902015-07-06 19:43:298664 std::vector<std::string> lines = base::SplitString(
8665 d.data_received(), "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448666 ASSERT_EQ(4u, lines.size()) << d.data_received();
8667
8668 std::string session_id;
8669
8670 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298671 std::vector<std::string> parts = base::SplitString(
8672 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
[email protected]316c1e5e2012-09-12 15:17:448673 ASSERT_EQ(2u, parts.size());
8674 if (i == 0) {
8675 EXPECT_EQ("insert", parts[0]);
8676 session_id = parts[1];
8677 } else {
8678 EXPECT_EQ("lookup", parts[0]);
8679 EXPECT_EQ(session_id, parts[1]);
8680 }
8681 }
8682 }
8683}
8684
Adam Langley32352ad2014-10-14 22:31:008685// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
8686// the result of fetching "ssl-session-cache" from the test server, indicates
8687// that exactly two different sessions were inserted, with no lookups etc.
8688static void AssertTwoDistinctSessionsInserted(const string& session_info) {
brettw3a2c6902015-07-06 19:43:298689 std::vector<std::string> lines = base::SplitString(
8690 session_info, "\n", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008691 ASSERT_EQ(3u, lines.size()) << session_info;
8692
8693 std::string session_id;
8694 for (size_t i = 0; i < 2; i++) {
brettw3a2c6902015-07-06 19:43:298695 std::vector<std::string> parts = base::SplitString(
8696 lines[i], "\t", base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL);
Adam Langley32352ad2014-10-14 22:31:008697 ASSERT_EQ(2u, parts.size());
8698 EXPECT_EQ("insert", parts[0]);
8699 if (i == 0) {
8700 session_id = parts[1];
8701 } else {
8702 EXPECT_NE(session_id, parts[1]);
8703 }
8704 }
8705}
8706
[email protected]316c1e5e2012-09-12 15:17:448707TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
8708 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
8709 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:228710 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:448711 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:228712 SpawnedTestServer test_server(
8713 SpawnedTestServer::TYPE_HTTPS,
8714 ssl_options,
8715 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:448716 ASSERT_TRUE(test_server.Start());
8717
8718 SSLClientSocket::ClearSessionCache();
8719
8720 {
8721 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368722 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368723 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448724
[email protected]f7022f32014-08-21 16:32:198725 r->Start();
8726 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448727
[email protected]255620da2013-08-19 13:14:298728 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448729
8730 EXPECT_EQ(1, d.response_started_count());
8731 }
8732
8733 // Now create a new HttpCache with a different ssl_session_cache_shard value.
8734 HttpNetworkSession::Params params;
8735 params.host_resolver = default_context_.host_resolver();
8736 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:118737 params.transport_security_state = default_context_.transport_security_state();
rsleevid6de8302016-06-21 01:33:208738 params.cert_transparency_verifier =
8739 default_context_.cert_transparency_verifier();
8740 params.ct_policy_enforcer = default_context_.ct_policy_enforcer();
[email protected]316c1e5e2012-09-12 15:17:448741 params.proxy_service = default_context_.proxy_service();
8742 params.ssl_config_service = default_context_.ssl_config_service();
8743 params.http_auth_handler_factory =
8744 default_context_.http_auth_handler_factory();
[email protected]316c1e5e2012-09-12 15:17:448745 params.http_server_properties = default_context_.http_server_properties();
[email protected]316c1e5e2012-09-12 15:17:448746
mmenkee65e7af2015-10-13 17:16:428747 HttpNetworkSession network_session(params);
danakj8522a25b2016-04-16 00:17:368748 std::unique_ptr<HttpCache> cache(new HttpCache(
mmenkee65e7af2015-10-13 17:16:428749 &network_session, HttpCache::DefaultBackend::InMemory(0), false));
[email protected]316c1e5e2012-09-12 15:17:448750
8751 default_context_.set_http_transaction_factory(cache.get());
8752
8753 {
8754 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368755 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368756 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:448757
[email protected]f7022f32014-08-21 16:32:198758 r->Start();
8759 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:448760
[email protected]255620da2013-08-19 13:14:298761 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:448762
8763 // The response will look like;
8764 // insert abc
8765 // insert xyz
8766 //
8767 // With a newline at the end which makes the split think that there are
8768 // three lines.
8769
8770 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008771 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:448772 }
8773}
8774
[email protected]48d2b7c52014-06-27 01:16:558775class HTTPSFallbackTest : public testing::Test {
8776 public:
Adam Langley32352ad2014-10-14 22:31:008777 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:298778 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:558779
8780 protected:
8781 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
8782 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:008783 context_.Init();
8784 delegate_.set_allow_certificate_errors(true);
8785
[email protected]48d2b7c52014-06-27 01:16:558786 SpawnedTestServer test_server(
8787 SpawnedTestServer::TYPE_HTTPS,
8788 ssl_options,
8789 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8790 ASSERT_TRUE(test_server.Start());
8791
tommycli59a63432015-11-06 00:10:558792 request_ = context_.CreateRequest(test_server.GetURL("/"), DEFAULT_PRIORITY,
8793 &delegate_);
[email protected]48d2b7c52014-06-27 01:16:558794 request_->Start();
8795
8796 base::RunLoop().Run();
8797 }
8798
[email protected]48d2b7c52014-06-27 01:16:558799 void ExpectFailure(int error) {
8800 EXPECT_EQ(1, delegate_.response_started_count());
maksim.sisovb53724b52016-09-16 05:30:508801 EXPECT_EQ(error, delegate_.request_status());
[email protected]48d2b7c52014-06-27 01:16:558802 }
8803
8804 private:
8805 TestDelegate delegate_;
davidben5a312152016-06-27 22:11:478806 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:368807 std::unique_ptr<URLRequest> request_;
[email protected]48d2b7c52014-06-27 01:16:558808};
8809
davidbenb127ca82015-06-15 19:05:428810// Tests the TLS 1.0 fallback doesn't happen.
8811TEST_F(HTTPSFallbackTest, TLSv1NoFallback) {
[email protected]48d2b7c52014-06-27 01:16:558812 SpawnedTestServer::SSLOptions ssl_options(
8813 SpawnedTestServer::SSLOptions::CERT_OK);
8814 ssl_options.tls_intolerant =
8815 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
8816
8817 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
davidben3b267512016-02-24 19:46:558818 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
davidbenb127ca82015-06-15 19:05:428819}
8820
davidben5a312152016-06-27 22:11:478821// Tests the TLS 1.1 fallback doesn't happen.
davidben3b267512016-02-24 19:46:558822TEST_F(HTTPSFallbackTest, TLSv1_1NoFallback) {
davidbenb127ca82015-06-15 19:05:428823 SpawnedTestServer::SSLOptions ssl_options(
8824 SpawnedTestServer::SSLOptions::CERT_OK);
8825 ssl_options.tls_intolerant =
8826 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_2;
8827
8828 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:558829 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
8830}
8831
[email protected]a8fed1742013-12-27 02:14:248832class HTTPSSessionTest : public testing::Test {
8833 public:
8834 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598835 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248836
8837 default_context_.set_network_delegate(&default_network_delegate_);
8838 default_context_.set_cert_verifier(&cert_verifier_);
8839 default_context_.Init();
8840 }
dcheng67be2b1f2014-10-27 21:47:298841 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248842
8843 protected:
8844 MockCertVerifier cert_verifier_;
8845 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8846 TestURLRequestContext default_context_;
8847};
8848
8849// Tests that session resumption is not attempted if an invalid certificate
8850// is presented.
8851TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8852 SpawnedTestServer::SSLOptions ssl_options;
8853 ssl_options.record_resume = true;
8854 SpawnedTestServer test_server(
8855 SpawnedTestServer::TYPE_HTTPS,
8856 ssl_options,
8857 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8858 ASSERT_TRUE(test_server.Start());
8859
8860 SSLClientSocket::ClearSessionCache();
8861
8862 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598863 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248864 {
8865 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368866 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368867 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248868
[email protected]f7022f32014-08-21 16:32:198869 r->Start();
8870 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248871
8872 base::RunLoop().Run();
8873
8874 EXPECT_EQ(1, d.response_started_count());
8875 }
8876
8877 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8878 CloseAllConnections();
8879
8880 // Now change the certificate to be acceptable (so that the response is
8881 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598882 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248883 {
8884 TestDelegate d;
danakj8522a25b2016-04-16 00:17:368885 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368886 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248887
[email protected]f7022f32014-08-21 16:32:198888 r->Start();
8889 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248890
8891 base::RunLoop().Run();
8892
8893 // The response will look like;
8894 // insert abc
8895 // insert xyz
8896 //
8897 // With a newline at the end which makes the split think that there are
8898 // three lines.
8899 //
8900 // If a session was presented (eg: a bug), then the response would look
8901 // like;
8902 // insert abc
8903 // lookup abc
8904 // insert xyz
8905
8906 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008907 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248908 }
8909}
8910
[email protected]dffe8242012-03-20 15:14:278911// This the fingerprint of the "Testing CA" certificate used by the testserver.
8912// See net/data/ssl/certificates/ocsp-test-root.pem.
mattm3b4376f12016-10-03 21:07:158913static const SHA1HashValue kOCSPTestCertFingerprint = {{
8914 0xa7, 0xea, 0x4b, 0x0d, 0x13, 0xc1, 0x63, 0xbf, 0xb8, 0x4e,
8915 0x9a, 0xaf, 0x33, 0x05, 0xb0, 0x8f, 0x9c, 0xbe, 0x23, 0xe9,
8916}};
[email protected]dffe8242012-03-20 15:14:278917
[email protected]51523f52013-07-31 21:57:288918// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8919// testserver.
8920static const SHA256HashValue kOCSPTestCertSPKI = { {
8921 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8922 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8923 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8924 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8925} };
8926
[email protected]dffe8242012-03-20 15:14:278927// This is the policy OID contained in the certificates that testserver
8928// generates.
8929static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8930
8931class HTTPSOCSPTest : public HTTPSRequestTest {
8932 public:
8933 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098934 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088935 ev_test_policy_(
8936 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8937 kOCSPTestCertFingerprint,
8938 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028939 }
8940
dcheng67be2b1f2014-10-27 21:47:298941 void SetUp() override {
rsleevid6de8302016-06-21 01:33:208942 context_.SetCTPolicyEnforcer(
8943 base::MakeUnique<AllowAnyCertCTPolicyEnforcer>());
8944 SetupContext();
[email protected]ef2bf422012-05-11 03:27:098945 context_.Init();
[email protected]dffe8242012-03-20 15:14:278946
[email protected]cba24642014-08-15 20:49:598947 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208948 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428949 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508950 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278951
svaldez2135be52016-04-20 16:34:538952#if defined(USE_NSS_CERTS)
[email protected]ef2bf422012-05-11 03:27:098953 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278954 EnsureNSSHttpIOInit();
8955#endif
8956 }
8957
dadrian612337a2016-07-20 22:36:588958 void DoConnectionWithDelegate(
8959 const SpawnedTestServer::SSLOptions& ssl_options,
8960 TestDelegate* delegate,
8961 SSLInfo* out_ssl_info) {
8962 // Always overwrite |out_ssl_info|.
8963 out_ssl_info->Reset();
8964
[email protected]ce7d0cbc2013-05-03 18:57:228965 SpawnedTestServer test_server(
8966 SpawnedTestServer::TYPE_HTTPS,
8967 ssl_options,
8968 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278969 ASSERT_TRUE(test_server.Start());
8970
dadrian612337a2016-07-20 22:36:588971 delegate->set_allow_certificate_errors(true);
8972 std::unique_ptr<URLRequest> r(context_.CreateRequest(
8973 test_server.GetURL("/"), DEFAULT_PRIORITY, delegate));
[email protected]f7022f32014-08-21 16:32:198974 r->Start();
[email protected]dffe8242012-03-20 15:14:278975
[email protected]255620da2013-08-19 13:14:298976 base::RunLoop().Run();
dadrian612337a2016-07-20 22:36:588977 EXPECT_EQ(1, delegate->response_started_count());
[email protected]dffe8242012-03-20 15:14:278978
dadrian612337a2016-07-20 22:36:588979 *out_ssl_info = r->ssl_info();
8980 }
8981
8982 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
8983 CertStatus* out_cert_status) {
8984 // Always overwrite |out_cert_status|.
8985 *out_cert_status = 0;
8986
8987 TestDelegate d;
8988 SSLInfo ssl_info;
8989 ASSERT_NO_FATAL_FAILURE(
8990 DoConnectionWithDelegate(ssl_options, &d, &ssl_info));
8991
8992 *out_cert_status = ssl_info.cert_status;
[email protected]dffe8242012-03-20 15:14:278993 }
8994
dcheng67be2b1f2014-10-27 21:47:298995 ~HTTPSOCSPTest() override {
svaldez2135be52016-04-20 16:34:538996#if defined(USE_NSS_CERTS)
[email protected]dffe8242012-03-20 15:14:278997 ShutdownNSSHttpIO();
8998#endif
8999 }
9000
[email protected]a13234c2012-03-20 21:45:029001 protected:
rsleevid6de8302016-06-21 01:33:209002 class AllowAnyCertCTPolicyEnforcer : public CTPolicyEnforcer {
9003 public:
9004 AllowAnyCertCTPolicyEnforcer() = default;
9005 ~AllowAnyCertCTPolicyEnforcer() override = default;
9006
9007 ct::CertPolicyCompliance DoesConformToCertPolicy(
9008 X509Certificate* cert,
9009 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209010 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209011 return ct::CertPolicyCompliance::CERT_POLICY_COMPLIES_VIA_SCTS;
9012 }
9013
9014 ct::EVPolicyCompliance DoesConformToCTEVPolicy(
9015 X509Certificate* cert,
9016 const ct::EVCertsWhitelist* ev_whitelist,
9017 const SCTList& verified_scts,
tfarina42834112016-09-22 13:38:209018 const NetLogWithSource& net_log) override {
rsleevid6de8302016-06-21 01:33:209019 return ct::EVPolicyCompliance::EV_POLICY_COMPLIES_VIA_SCTS;
9020 }
9021 };
[email protected]a13234c2012-03-20 21:45:029022 // SetupContext configures the URLRequestContext that will be used for making
9023 // connetions to testserver. This can be overridden in test subclasses for
9024 // different behaviour.
rsleevid6de8302016-06-21 01:33:209025 virtual void SetupContext() {
9026 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149027 true /* check for EV */, true /* online revocation checking */,
9028 false /* require rev. checking for local
9029 anchors */,
9030 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029031 }
9032
danakj8522a25b2016-04-16 00:17:369033 std::unique_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:099034 TestURLRequestContext context_;
danakj8522a25b2016-04-16 00:17:369035 std::unique_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:279036};
9037
[email protected]a13234c2012-03-20 21:45:029038static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
mattmaf868e72016-09-23 23:25:209039#if defined(OS_WIN) || defined(OS_MACOSX)
[email protected]a13234c2012-03-20 21:45:029040 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
9041 // have that ability on other platforms.
9042 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
9043#else
9044 return 0;
9045#endif
9046}
9047
[email protected]3a86a712013-07-30 07:16:209048// SystemSupportsHardFailRevocationChecking returns true iff the current
9049// operating system supports revocation checking and can distinguish between
9050// situations where a given certificate lacks any revocation information (eg:
9051// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
9052// revocation information cannot be obtained (eg: the CRL was unreachable).
9053// If it does not, then tests which rely on 'hard fail' behaviour should be
9054// skipped.
9055static bool SystemSupportsHardFailRevocationChecking() {
svaldez2135be52016-04-20 16:34:539056#if defined(OS_WIN) || defined(USE_NSS_CERTS)
[email protected]3a86a712013-07-30 07:16:209057 return true;
9058#else
9059 return false;
9060#endif
9061}
9062
[email protected]a13234c2012-03-20 21:45:029063// SystemUsesChromiumEVMetadata returns true iff the current operating system
9064// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
9065// several tests are effected because our testing EV certificate won't be
9066// recognised as EV.
9067static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:329068#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:579069 // http://crbug.com/117478 - OpenSSL does not support EV validation.
9070 return false;
[email protected]e1b2d732014-03-28 16:20:329071#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
9072 // On OS X and Android, we use the system to tell us whether a certificate is
9073 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:019074 return false;
9075#else
9076 return true;
9077#endif
9078}
9079
mattmaf868e72016-09-23 23:25:209080// Returns the expected CertStatus for tests that expect an online revocation
9081// check failure as a result of checking a test EV cert, which will not
9082// actually trigger an online revocation check on some platforms.
9083static CertStatus ExpectedCertStatusForFailedOnlineEVRevocationCheck() {
9084 if (SystemUsesChromiumEVMetadata()) {
9085 return ExpectedCertStatusForFailedOnlineRevocationCheck();
9086 } else {
9087 // If SystemUsesChromiumEVMetadata is false, revocation checking will not
9088 // be enabled, and thus there will not be a revocation check to fail.
9089 return 0u;
9090 }
9091}
9092
[email protected]b6f2de32012-08-17 04:35:089093static bool SystemSupportsOCSP() {
davidben7ee23542016-06-03 18:27:339094#if defined(OS_ANDROID)
[email protected]a13234c2012-03-20 21:45:029095 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
9096 return false;
9097#else
9098 return true;
9099#endif
9100}
9101
davidbend1fb2f12014-11-08 02:51:009102static bool SystemSupportsOCSPStapling() {
davidben7ee23542016-06-03 18:27:339103#if defined(USE_NSS_CERTS) || defined(OS_WIN)
mathpc992e602015-10-21 20:34:039104 return true;
mathpc992e602015-10-21 20:34:039105#else
9106 return false;
9107#endif
davidbend1fb2f12014-11-08 02:51:009108}
9109
[email protected]dffe8242012-03-20 15:14:279110TEST_F(HTTPSOCSPTest, Valid) {
9111 if (!SystemSupportsOCSP()) {
9112 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9113 return;
9114 }
9115
[email protected]ce7d0cbc2013-05-03 18:57:229116 SpawnedTestServer::SSLOptions ssl_options(
9117 SpawnedTestServer::SSLOptions::CERT_AUTO);
9118 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:279119
[email protected]924e9f92012-12-16 22:00:539120 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129121 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279122
9123 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9124
[email protected]a13234c2012-03-20 21:45:029125 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9126 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:279127
9128 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9129}
9130
9131TEST_F(HTTPSOCSPTest, Revoked) {
9132 if (!SystemSupportsOCSP()) {
9133 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9134 return;
9135 }
9136
[email protected]ce7d0cbc2013-05-03 18:57:229137 SpawnedTestServer::SSLOptions ssl_options(
9138 SpawnedTestServer::SSLOptions::CERT_AUTO);
9139 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:279140
9141 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129142 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279143
[email protected]dffe8242012-03-20 15:14:279144 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279145 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9146 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9147}
9148
9149TEST_F(HTTPSOCSPTest, Invalid) {
9150 if (!SystemSupportsOCSP()) {
9151 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9152 return;
9153 }
9154
[email protected]ce7d0cbc2013-05-03 18:57:229155 SpawnedTestServer::SSLOptions ssl_options(
9156 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589157 ssl_options.ocsp_status =
9158 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]dffe8242012-03-20 15:14:279159
[email protected]924e9f92012-12-16 22:00:539160 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129161 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:279162
[email protected]a13234c2012-03-20 21:45:029163 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:279164 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:279165
9166 // Without a positive OCSP response, we shouldn't show the EV status.
9167 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9168 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9169}
[email protected]a13234c2012-03-20 21:45:029170
davidbend1fb2f12014-11-08 02:51:009171TEST_F(HTTPSOCSPTest, ValidStapled) {
mathpc992e602015-10-21 20:34:039172 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009173 LOG(WARNING)
9174 << "Skipping test because system doesn't support OCSP stapling";
9175 return;
9176 }
9177
9178 SpawnedTestServer::SSLOptions ssl_options(
9179 SpawnedTestServer::SSLOptions::CERT_AUTO);
9180 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9181 ssl_options.staple_ocsp_response = true;
9182 ssl_options.ocsp_server_unavailable = true;
9183
9184 CertStatus cert_status;
9185 DoConnection(ssl_options, &cert_status);
9186
9187 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9188
9189 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9190 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9191
9192 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9193}
9194
davidben6c3191b2014-11-21 22:38:049195// Disabled on NSS ports. See https://crbug.com/431716.
davidben71f35ff2015-04-17 20:54:489196#if defined(USE_NSS_CERTS)
davidben6c3191b2014-11-21 22:38:049197#define MAYBE_RevokedStapled DISABLED_RevokedStapled
9198#else
9199#define MAYBE_RevokedStapled RevokedStapled
9200#endif
9201TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
mathpc992e602015-10-21 20:34:039202 if (!SystemSupportsOCSPStapling()) {
davidbend1fb2f12014-11-08 02:51:009203 LOG(WARNING)
9204 << "Skipping test because system doesn't support OCSP stapling";
9205 return;
9206 }
9207
9208 SpawnedTestServer::SSLOptions ssl_options(
9209 SpawnedTestServer::SSLOptions::CERT_AUTO);
9210 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9211 ssl_options.staple_ocsp_response = true;
9212 ssl_options.ocsp_server_unavailable = true;
9213
9214 CertStatus cert_status;
9215 DoConnection(ssl_options, &cert_status);
9216
9217 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9218 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9219 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9220}
9221
dadriand476e652016-07-26 21:33:249222TEST_F(HTTPSOCSPTest, ExpectStapleReportSentOnMissing) {
9223 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9224 https_test_server.SetSSLConfig(
9225 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9226 https_test_server.ServeFilesFromSourceDirectory(
9227 base::FilePath(kTestFilePath));
9228 ASSERT_TRUE(https_test_server.Start());
9229
9230 // Set up a MockCertVerifier to accept the certificate that the server sends,
9231 // but not provide any OCSP information.
9232 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9233 ASSERT_TRUE(cert);
9234 MockCertVerifier cert_verifier;
9235 CertVerifyResult verify_result;
9236 verify_result.verified_cert = cert;
9237 verify_result.is_issued_by_known_root = true;
9238 verify_result.ocsp_result.response_status = OCSPVerifyResult::MISSING;
9239 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9240
9241 // Catch the Expect-Staple report.
9242 TransportSecurityState transport_security_state;
9243 MockCertificateReportSender mock_report_sender;
9244 transport_security_state.SetReportSender(&mock_report_sender);
9245
9246 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9247 // that the request can be sent to a site on the Expect-Staple preload list.
9248 MockHostResolver host_resolver;
9249 TestNetworkDelegate network_delegate;
9250 TestURLRequestContext context(true);
9251 context.set_host_resolver(&host_resolver);
9252 context.set_transport_security_state(&transport_security_state);
9253 context.set_network_delegate(&network_delegate);
9254 context.set_cert_verifier(&cert_verifier);
9255 context.Init();
9256
9257 // Now send a request to trigger the violation.
9258 TestDelegate d;
9259 GURL url = https_test_server.GetURL("/");
9260 GURL::Replacements replace_host;
9261 replace_host.SetHostStr(kExpectStapleStaticHostname);
9262 url = url.ReplaceComponents(replace_host);
9263 std::unique_ptr<URLRequest> violating_request(
9264 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9265 violating_request->Start();
9266 base::RunLoop().Run();
9267
9268 // Confirm a report was sent.
9269 EXPECT_FALSE(mock_report_sender.latest_report().empty());
9270 EXPECT_EQ(GURL(kExpectStapleReportURI),
9271 mock_report_sender.latest_report_uri());
9272}
9273
9274TEST_F(HTTPSOCSPTest, ExpectStapleReportNotSentOnValid) {
9275 EmbeddedTestServer https_test_server(net::EmbeddedTestServer::TYPE_HTTPS);
9276 https_test_server.SetSSLConfig(
9277 net::EmbeddedTestServer::CERT_COMMON_NAME_IS_DOMAIN);
9278 https_test_server.ServeFilesFromSourceDirectory(
9279 base::FilePath(kTestFilePath));
9280 ASSERT_TRUE(https_test_server.Start());
9281
9282 // Set up a MockCertVerifier to accept the certificate that the server sends,
9283 // and provide GOOD revocation status.
9284 scoped_refptr<X509Certificate> cert = https_test_server.GetCertificate();
9285 ASSERT_TRUE(cert);
9286 MockCertVerifier cert_verifier;
9287 CertVerifyResult verify_result;
9288 verify_result.verified_cert = cert;
9289 verify_result.is_issued_by_known_root = true;
9290 verify_result.ocsp_result.response_status = OCSPVerifyResult::PROVIDED;
9291 verify_result.ocsp_result.revocation_status = OCSPRevocationStatus::GOOD;
9292 cert_verifier.AddResultForCert(cert.get(), verify_result, OK);
9293
9294 // Catch the Expect-Staple report.
9295 TransportSecurityState transport_security_state;
9296 MockCertificateReportSender mock_report_sender;
9297 transport_security_state.SetReportSender(&mock_report_sender);
9298
9299 // Use a MockHostResolver (which by default maps all hosts to 127.0.0.1) so
9300 // that the request can be sent to a site on the Expect-Staple preload list.
9301 MockHostResolver host_resolver;
9302 TestNetworkDelegate network_delegate;
9303 TestURLRequestContext context(true);
9304 context.set_host_resolver(&host_resolver);
9305 context.set_transport_security_state(&transport_security_state);
9306 context.set_network_delegate(&network_delegate);
9307 context.set_cert_verifier(&cert_verifier);
9308 context.Init();
9309
9310 // This request should not not trigger an Expect-Staple violation.
9311 TestDelegate d;
9312 GURL url = https_test_server.GetURL("/");
9313 GURL::Replacements replace_host;
9314 replace_host.SetHostStr(kExpectStapleStaticHostname);
9315 url = url.ReplaceComponents(replace_host);
9316 std::unique_ptr<URLRequest> ok_request(
9317 context.CreateRequest(url, DEFAULT_PRIORITY, &d));
9318 ok_request->Start();
9319 base::RunLoop().Run();
9320
9321 // Check that no report was sent.
9322 EXPECT_TRUE(mock_report_sender.latest_report().empty());
9323 EXPECT_EQ(GURL(), mock_report_sender.latest_report_uri());
9324}
9325
dadrian612337a2016-07-20 22:36:589326static const struct OCSPVerifyTestData {
9327 std::vector<SpawnedTestServer::SSLOptions::OCSPSingleResponse> ocsp_responses;
9328 SpawnedTestServer::SSLOptions::OCSPProduced ocsp_produced;
9329 OCSPVerifyResult::ResponseStatus response_status;
9330 bool has_revocation_status;
9331 OCSPRevocationStatus cert_status;
9332} kOCSPVerifyData[] = {
9333
9334 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9335 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9336 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9337 OCSPVerifyResult::PROVIDED,
9338 true,
9339 OCSPRevocationStatus::GOOD},
9340
9341 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9342 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9343 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9344 OCSPVerifyResult::INVALID_DATE,
9345 false,
9346 OCSPRevocationStatus::UNKNOWN},
9347
9348 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9349 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9350 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9351 OCSPVerifyResult::INVALID_DATE,
9352 false,
9353 OCSPRevocationStatus::UNKNOWN},
9354
9355 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9356 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9357 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9358 OCSPVerifyResult::INVALID_DATE,
9359 false,
9360 OCSPRevocationStatus::UNKNOWN},
9361
9362 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9363 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9364 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9365 OCSPVerifyResult::INVALID_DATE,
9366 false,
9367 OCSPRevocationStatus::UNKNOWN},
9368
9369 {{{SpawnedTestServer::SSLOptions::OCSP_TRY_LATER,
9370 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9371 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9372 OCSPVerifyResult::ERROR_RESPONSE,
9373 false,
9374 OCSPRevocationStatus::UNKNOWN},
9375
9376 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE,
9377 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9378 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9379 OCSPVerifyResult::PARSE_RESPONSE_ERROR,
9380 false,
9381 OCSPRevocationStatus::UNKNOWN},
9382
9383 {{{SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE_DATA,
9384 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9385 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9386 OCSPVerifyResult::PARSE_RESPONSE_DATA_ERROR,
9387 false,
9388 OCSPRevocationStatus::UNKNOWN},
9389
9390 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9391 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9392 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9393 OCSPVerifyResult::INVALID_DATE,
9394 false,
9395 OCSPRevocationStatus::UNKNOWN},
9396
9397 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9398 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9399 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9400 OCSPVerifyResult::PROVIDED,
9401 true,
9402 OCSPRevocationStatus::UNKNOWN},
9403
9404 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9405 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9406 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9407 OCSPVerifyResult::INVALID_DATE,
9408 false,
9409 OCSPRevocationStatus::UNKNOWN},
9410
9411 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9412 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9413 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9414 OCSPVerifyResult::INVALID_DATE,
9415 false,
9416 OCSPRevocationStatus::UNKNOWN},
9417
9418 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9419 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9420 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_BEFORE_CERT,
9421 OCSPVerifyResult::BAD_PRODUCED_AT,
9422 false,
9423 OCSPRevocationStatus::UNKNOWN},
9424
9425 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9426 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9427 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9428 OCSPVerifyResult::BAD_PRODUCED_AT,
9429 false,
9430 OCSPRevocationStatus::UNKNOWN},
9431
9432 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9433 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9434 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_AFTER_CERT,
9435 OCSPVerifyResult::BAD_PRODUCED_AT,
9436 false,
9437 OCSPRevocationStatus::UNKNOWN},
9438
9439 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9440 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9441 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9442 OCSPVerifyResult::PROVIDED,
9443 true,
9444 OCSPRevocationStatus::REVOKED},
9445
9446 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9447 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD}},
9448 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9449 OCSPVerifyResult::INVALID_DATE,
9450 false,
9451 OCSPRevocationStatus::UNKNOWN},
9452
9453 {{{SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9454 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9455 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9456 OCSPVerifyResult::INVALID_DATE,
9457 false,
9458 OCSPRevocationStatus::UNKNOWN},
9459
9460 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9461 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9462 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9463 OCSPVerifyResult::PROVIDED,
9464 true,
9465 OCSPRevocationStatus::GOOD},
9466
9467 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9468 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9469 {SpawnedTestServer::SSLOptions::OCSP_OK,
9470 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9471 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9472 OCSPVerifyResult::PROVIDED,
9473 true,
9474 OCSPRevocationStatus::GOOD},
9475
9476 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9477 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9478 {SpawnedTestServer::SSLOptions::OCSP_OK,
9479 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9480 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9481 OCSPVerifyResult::PROVIDED,
9482 true,
9483 OCSPRevocationStatus::GOOD},
9484
9485 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9486 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9487 {SpawnedTestServer::SSLOptions::OCSP_OK,
9488 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9489 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9490 OCSPVerifyResult::PROVIDED,
9491 true,
9492 OCSPRevocationStatus::GOOD},
9493
9494 {{{SpawnedTestServer::SSLOptions::OCSP_OK,
9495 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY},
9496 {SpawnedTestServer::SSLOptions::OCSP_OK,
9497 SpawnedTestServer::SSLOptions::OCSP_DATE_OLD},
9498 {SpawnedTestServer::SSLOptions::OCSP_OK,
9499 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG}},
9500 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9501 OCSPVerifyResult::INVALID_DATE,
9502 false,
9503 OCSPRevocationStatus::UNKNOWN},
9504
9505 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9506 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9507 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9508 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9509 {SpawnedTestServer::SSLOptions::OCSP_OK,
9510 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9511 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9512 OCSPVerifyResult::PROVIDED,
9513 true,
9514 OCSPRevocationStatus::REVOKED},
9515
9516 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9517 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9518 {SpawnedTestServer::SSLOptions::OCSP_OK,
9519 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9520 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9521 OCSPVerifyResult::PROVIDED,
9522 true,
9523 OCSPRevocationStatus::UNKNOWN},
9524
9525 {{{SpawnedTestServer::SSLOptions::OCSP_UNKNOWN,
9526 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID},
9527 {SpawnedTestServer::SSLOptions::OCSP_REVOKED,
9528 SpawnedTestServer::SSLOptions::OCSP_DATE_LONG},
9529 {SpawnedTestServer::SSLOptions::OCSP_OK,
9530 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9531 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9532 OCSPVerifyResult::PROVIDED,
9533 true,
9534 OCSPRevocationStatus::UNKNOWN},
9535
9536 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9537 SpawnedTestServer::SSLOptions::OCSP_DATE_VALID}},
9538 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9539 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9540 false,
9541 OCSPRevocationStatus::UNKNOWN},
9542
9543 {{{SpawnedTestServer::SSLOptions::OCSP_MISMATCHED_SERIAL,
9544 SpawnedTestServer::SSLOptions::OCSP_DATE_EARLY}},
9545 SpawnedTestServer::SSLOptions::OCSP_PRODUCED_VALID,
9546 OCSPVerifyResult::NO_MATCHING_RESPONSE,
9547 false,
9548 OCSPRevocationStatus::UNKNOWN},
9549
9550};
9551
9552class HTTPSOCSPVerifyTest
9553 : public HTTPSOCSPTest,
9554 public testing::WithParamInterface<OCSPVerifyTestData> {};
9555
9556TEST_P(HTTPSOCSPVerifyTest, VerifyResult) {
9557 SpawnedTestServer::SSLOptions ssl_options(
9558 SpawnedTestServer::SSLOptions::CERT_AUTO);
9559 OCSPVerifyTestData test = GetParam();
9560
9561 ssl_options.ocsp_responses = test.ocsp_responses;
9562 ssl_options.ocsp_produced = test.ocsp_produced;
9563 ssl_options.staple_ocsp_response = true;
9564
9565 SSLInfo ssl_info;
9566 OCSPErrorTestDelegate delegate;
9567 ASSERT_NO_FATAL_FAILURE(
9568 DoConnectionWithDelegate(ssl_options, &delegate, &ssl_info));
9569
9570 // The SSLInfo must be extracted from |delegate| on error, due to how
9571 // URLRequest caches certificate errors.
9572 if (delegate.have_certificate_errors()) {
9573 ASSERT_TRUE(delegate.on_ssl_certificate_error_called());
9574 ssl_info = delegate.ssl_info();
9575 }
9576
9577 EXPECT_EQ(test.response_status, ssl_info.ocsp_result.response_status);
9578
9579 if (test.has_revocation_status)
9580 EXPECT_EQ(test.cert_status, ssl_info.ocsp_result.revocation_status);
9581}
9582
9583INSTANTIATE_TEST_CASE_P(OCSPVerify,
9584 HTTPSOCSPVerifyTest,
9585 testing::ValuesIn(kOCSPVerifyData));
9586
[email protected]3a86a712013-07-30 07:16:209587class HTTPSHardFailTest : public HTTPSOCSPTest {
9588 protected:
rsleevid6de8302016-06-21 01:33:209589 void SetupContext() override {
9590 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149591 false /* check for EV */, false /* online revocation checking */,
9592 true /* require rev. checking for local
9593 anchors */,
9594 false /* token binding enabled */));
[email protected]3a86a712013-07-30 07:16:209595 }
9596};
9597
[email protected]3a86a712013-07-30 07:16:209598TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
9599 if (!SystemSupportsOCSP()) {
9600 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9601 return;
9602 }
9603
9604 if (!SystemSupportsHardFailRevocationChecking()) {
9605 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
9606 << "revocation checking";
9607 return;
9608 }
9609
9610 SpawnedTestServer::SSLOptions ssl_options(
9611 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589612 ssl_options.ocsp_status =
9613 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]3a86a712013-07-30 07:16:209614
9615 CertStatus cert_status;
9616 DoConnection(ssl_options, &cert_status);
9617
9618 EXPECT_EQ(CERT_STATUS_REVOKED,
9619 cert_status & CERT_STATUS_REVOKED);
9620
9621 // Without a positive OCSP response, we shouldn't show the EV status.
9622 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9623}
9624
[email protected]a13234c2012-03-20 21:45:029625class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
9626 protected:
rsleevid6de8302016-06-21 01:33:209627 void SetupContext() override {
9628 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149629 true /* check for EV */, false /* online revocation checking */,
9630 false /* require rev. checking for local
9631 anchors */,
9632 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029633 }
9634};
9635
9636TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
9637 if (!SystemSupportsOCSP()) {
9638 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9639 return;
9640 }
9641
[email protected]ce7d0cbc2013-05-03 18:57:229642 SpawnedTestServer::SSLOptions ssl_options(
9643 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589644 ssl_options.ocsp_status =
9645 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029646 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9647
[email protected]924e9f92012-12-16 22:00:539648 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129649 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029650
mattmaf868e72016-09-23 23:25:209651 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:029652 cert_status & CERT_STATUS_ALL_ERRORS);
9653
9654 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089655 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9656 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029657}
9658
[email protected]be0fff62013-08-29 23:37:489659TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
9660 if (!SystemSupportsOCSP()) {
9661 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9662 return;
9663 }
9664
9665 SpawnedTestServer::SSLOptions ssl_options(
9666 SpawnedTestServer::SSLOptions::CERT_AUTO);
9667 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
9668 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9669
9670 CertStatus cert_status;
9671 DoConnection(ssl_options, &cert_status);
9672
9673 // Currently only works for Windows. When using NSS or OS X, it's not
9674 // possible to determine whether the check failed because of actual
9675 // revocation or because there was an OCSP failure.
9676#if defined(OS_WIN)
9677 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9678#else
9679 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9680#endif
9681
9682 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9683 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9684 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9685}
9686
[email protected]a13234c2012-03-20 21:45:029687TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
9688 if (!SystemSupportsOCSP()) {
9689 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9690 return;
9691 }
9692
[email protected]ce7d0cbc2013-05-03 18:57:229693 SpawnedTestServer::SSLOptions ssl_options(
9694 SpawnedTestServer::SSLOptions::CERT_AUTO);
9695 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:029696 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
9697
9698 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129699 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029700
9701 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9702
9703 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9704 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:089705 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9706 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029707}
9708
9709TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
9710 if (!SystemSupportsOCSP()) {
9711 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9712 return;
9713 }
9714
[email protected]ce7d0cbc2013-05-03 18:57:229715 SpawnedTestServer::SSLOptions ssl_options(
9716 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589717 ssl_options.ocsp_status =
9718 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029719 SSLConfigService::SetCRLSet(
9720 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9721
9722 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129723 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029724
mattmaf868e72016-09-23 23:25:209725 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]a13234c2012-03-20 21:45:029726 cert_status & CERT_STATUS_ALL_ERRORS);
9727
9728 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:089729 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9730 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029731}
9732
[email protected]51523f52013-07-31 21:57:289733TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
9734 if (!SystemSupportsOCSP()) {
9735 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9736 return;
9737 }
9738
9739 SpawnedTestServer::SSLOptions ssl_options(
9740 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589741 ssl_options.ocsp_status =
9742 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]51523f52013-07-31 21:57:289743 SSLConfigService::SetCRLSet(
9744 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9745 false, &kOCSPTestCertSPKI, "")));
9746
9747 CertStatus cert_status;
9748 DoConnection(ssl_options, &cert_status);
9749
9750 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
9751 // revocation check for EV.
9752 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9753 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
9754 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
9755 EXPECT_FALSE(
9756 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9757}
9758
9759TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
9760 if (!SystemSupportsOCSP()) {
9761 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9762 return;
9763 }
9764
[email protected]ce7d0cbc2013-05-03 18:57:229765 SpawnedTestServer::SSLOptions ssl_options(
9766 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589767 ssl_options.ocsp_status =
9768 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029769 SSLConfigService::SetCRLSet(
9770 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
9771
[email protected]51523f52013-07-31 21:57:289772 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:129773 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029774
[email protected]51523f52013-07-31 21:57:289775 // Even with a fresh CRLSet, we should still do online revocation checks when
9776 // the certificate chain isn't covered by the CRLSet, which it isn't in this
9777 // test.
mattmaf868e72016-09-23 23:25:209778 EXPECT_EQ(ExpectedCertStatusForFailedOnlineEVRevocationCheck(),
[email protected]51523f52013-07-31 21:57:289779 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:029780
[email protected]51523f52013-07-31 21:57:289781 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:029782 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:289783 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:029784}
9785
[email protected]b6f2de32012-08-17 04:35:089786TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
9787 // Test that when EV verification is requested, but online revocation
9788 // checking is disabled, and the leaf certificate is not in fact EV, that
9789 // no revocation checking actually happens.
9790 if (!SystemSupportsOCSP()) {
9791 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
9792 return;
9793 }
9794
9795 // Unmark the certificate's OID as EV, which should disable revocation
9796 // checking (as per the user preference)
9797 ev_test_policy_.reset();
9798
[email protected]ce7d0cbc2013-05-03 18:57:229799 SpawnedTestServer::SSLOptions ssl_options(
9800 SpawnedTestServer::SSLOptions::CERT_AUTO);
9801 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:089802 SSLConfigService::SetCRLSet(
9803 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9804
9805 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129806 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:089807
9808 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9809
9810 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9811 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9812}
9813
[email protected]a13234c2012-03-20 21:45:029814class HTTPSCRLSetTest : public HTTPSOCSPTest {
9815 protected:
rsleevid6de8302016-06-21 01:33:209816 void SetupContext() override {
9817 context_.set_ssl_config_service(new TestSSLConfigService(
nharperb7441ef2016-01-25 23:54:149818 false /* check for EV */, false /* online revocation checking */,
9819 false /* require rev. checking for local
9820 anchors */,
9821 false /* token binding enabled */));
[email protected]a13234c2012-03-20 21:45:029822 }
9823};
9824
9825TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:229826 SpawnedTestServer::SSLOptions ssl_options(
9827 SpawnedTestServer::SSLOptions::CERT_AUTO);
dadrian612337a2016-07-20 22:36:589828 ssl_options.ocsp_status =
9829 SpawnedTestServer::SSLOptions::OCSP_INVALID_RESPONSE;
[email protected]a13234c2012-03-20 21:45:029830 SSLConfigService::SetCRLSet(
9831 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
9832
[email protected]924e9f92012-12-16 22:00:539833 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:129834 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:029835
9836 // If we're not trying EV verification then, even if the CRLSet has expired,
9837 // we don't fall back to online revocation checks.
9838 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
9839 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9840 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
9841}
[email protected]51523f52013-07-31 21:57:289842
9843TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:309844#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:289845 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
9846 return;
9847#endif
9848
9849 SpawnedTestServer::SSLOptions ssl_options(
9850 SpawnedTestServer::SSLOptions::CERT_AUTO);
9851 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
9852 ssl_options.cert_serial = 10;
9853 SSLConfigService::SetCRLSet(
9854 scoped_refptr<CRLSet>(CRLSet::ForTesting(
9855 false, &kOCSPTestCertSPKI, "\x0a")));
9856
9857 CertStatus cert_status = 0;
9858 DoConnection(ssl_options, &cert_status);
9859
9860 // If the certificate is recorded as revoked in the CRLSet, that should be
9861 // reflected without online revocation checking.
9862 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
9863 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
9864 EXPECT_FALSE(
9865 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
9866}
[email protected]316c1e5e2012-09-12 15:17:449867#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:279868
mmenke9f2ec60c2015-06-01 20:59:479869#if !defined(DISABLE_FTP_SUPPORT) && !defined(OS_ANDROID)
9870// These tests aren't passing on Android. Either the RemoteTestServer isn't
9871// starting up successfully, or it can't access the test files.
9872// TODO(mmenke): Fix this. See http://crbug.com/495220
[email protected]b89ca032009-08-31 21:41:319873class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:119874 public:
[email protected]d9fca99a2012-02-24 16:16:209875 URLRequestTestFTP()
mmenkecd4c7532016-10-19 18:36:059876 : ftp_test_server_(SpawnedTestServer::TYPE_FTP,
tommycli59a63432015-11-06 00:10:559877 SpawnedTestServer::kLocalhost,
9878 base::FilePath(kTestFilePath)) {
mmenke9f2ec60c2015-06-01 20:59:479879 // Can't use |default_context_|'s HostResolver to set up the
9880 // FTPTransactionFactory because it hasn't been created yet.
9881 default_context_.set_host_resolver(&host_resolver_);
9882 }
9883
9884 // URLRequestTest interface:
9885 void SetUpFactory() override {
9886 // Add FTP support to the default URLRequestContext.
9887 job_factory_impl_->SetProtocolHandler(
mmenkecd4c7532016-10-19 18:36:059888 "ftp", FtpProtocolHandler::Create(&host_resolver_));
mmenke9f2ec60c2015-06-01 20:59:479889 }
9890
9891 std::string GetTestFileContents() {
9892 base::FilePath path;
9893 EXPECT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &path));
9894 path = path.Append(kTestFilePath);
9895 path = path.AppendASCII(kFtpTestFile);
9896 std::string contents;
9897 EXPECT_TRUE(base::ReadFileToString(path, &contents));
9898 return contents;
[email protected]95409e12010-08-17 20:07:119899 }
9900
[email protected]b89ca032009-08-31 21:41:319901 protected:
mmenkecd4c7532016-10-19 18:36:059902 // Note that this is destroyed before the FtpProtocolHandler that references
9903 // it, which is owned by the parent class. Since no requests are made during
9904 // teardown, this works, though it's not great.
mmenke9f2ec60c2015-06-01 20:59:479905 MockHostResolver host_resolver_;
mmenke9f2ec60c2015-06-01 20:59:479906
tommycli59a63432015-11-06 00:10:559907 SpawnedTestServer ftp_test_server_;
[email protected]b89ca032009-08-31 21:41:319908};
9909
[email protected]d2a133182012-08-05 16:44:089910// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:099911TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:089912 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:089913
9914 TestDelegate d;
9915 {
danakj8522a25b2016-04-16 00:17:369916 std::unique_ptr<URLRequest> r(
davidben151423e2015-03-23 18:48:369917 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199918 r->Start();
9919 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:089920
[email protected]255620da2013-08-19 13:14:299921 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:089922
[email protected]f7022f32014-08-21 16:32:199923 EXPECT_FALSE(r->is_pending());
maksim.sisovb53724b52016-09-16 05:30:509924 EXPECT_EQ(ERR_UNSAFE_PORT, d.request_status());
[email protected]d2a133182012-08-05 16:44:089925 }
9926}
9927
mmenke9f2ec60c2015-06-01 20:59:479928TEST_F(URLRequestTestFTP, FTPDirectoryListing) {
tommycli59a63432015-11-06 00:10:559929 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119930
[email protected]a25e90e2009-09-09 17:05:379931 TestDelegate d;
9932 {
danakj8522a25b2016-04-16 00:17:369933 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559934 ftp_test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199935 r->Start();
9936 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379937
[email protected]255620da2013-08-19 13:14:299938 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:379939
[email protected]f7022f32014-08-21 16:32:199940 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:379941 EXPECT_EQ(1, d.response_started_count());
9942 EXPECT_FALSE(d.received_data_before_response());
9943 EXPECT_LT(0, d.bytes_received());
tommycli59a63432015-11-06 00:10:559944 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199945 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559946 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199947 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:379948 }
9949}
9950
mmenke9f2ec60c2015-06-01 20:59:479951TEST_F(URLRequestTestFTP, FTPGetTestAnonymous) {
tommycli59a63432015-11-06 00:10:559952 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119953
[email protected]dd265012009-01-08 20:45:279954 TestDelegate d;
9955 {
danakj8522a25b2016-04-16 00:17:369956 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559957 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199958 r->Start();
9959 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279960
[email protected]255620da2013-08-19 13:14:299961 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279962
[email protected]f7022f32014-08-21 16:32:199963 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279964 EXPECT_EQ(1, d.response_started_count());
9965 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:479966 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559967 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199968 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559969 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199970 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:279971 }
9972}
9973
mmenke9f2ec60c2015-06-01 20:59:479974TEST_F(URLRequestTestFTP, FTPGetTest) {
tommycli59a63432015-11-06 00:10:559975 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:119976
[email protected]dd265012009-01-08 20:45:279977 TestDelegate d;
9978 {
danakj8522a25b2016-04-16 00:17:369979 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:559980 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
9981 "chrome"),
9982 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:199983 r->Start();
9984 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:279985
[email protected]255620da2013-08-19 13:14:299986 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:279987
[email protected]f7022f32014-08-21 16:32:199988 EXPECT_FALSE(r->is_pending());
mmenke9f2ec60c2015-06-01 20:59:479989 EXPECT_EQ(1, d.response_started_count());
9990 EXPECT_FALSE(d.received_data_before_response());
9991 EXPECT_EQ(GetTestFileContents(), d.data_received());
tommycli59a63432015-11-06 00:10:559992 EXPECT_EQ(ftp_test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:199993 r->GetSocketAddress().host());
tommycli59a63432015-11-06 00:10:559994 EXPECT_EQ(ftp_test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:199995 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:259996
9997 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:199998 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:259999 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:2710000 }
10001}
10002
mmenke9f2ec60c2015-06-01 20:59:4710003TEST_F(URLRequestTestFTP, FTPCheckWrongPassword) {
tommycli59a63432015-11-06 00:10:5510004 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110005
[email protected]dd265012009-01-08 20:45:2710006 TestDelegate d;
10007 {
danakj8522a25b2016-04-16 00:17:3610008 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510009 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10010 "wrong_password"),
davidben151423e2015-03-23 18:48:3610011 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910012 r->Start();
10013 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710014
[email protected]255620da2013-08-19 13:14:2910015 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710016
[email protected]f7022f32014-08-21 16:32:1910017 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710018 EXPECT_EQ(1, d.response_started_count());
10019 EXPECT_FALSE(d.received_data_before_response());
10020 EXPECT_EQ(d.bytes_received(), 0);
10021 }
10022}
10023
mmenke9f2ec60c2015-06-01 20:59:4710024TEST_F(URLRequestTestFTP, FTPCheckWrongPasswordRestart) {
tommycli59a63432015-11-06 00:10:5510025 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110026
[email protected]8b8a197d2009-08-26 15:57:5810027 TestDelegate d;
10028 // Set correct login credentials. The delegate will be asked for them when
10029 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810030 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810031 {
danakj8522a25b2016-04-16 00:17:3610032 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510033 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10034 "wrong_password"),
davidben151423e2015-03-23 18:48:3610035 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910036 r->Start();
10037 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810038
[email protected]255620da2013-08-19 13:14:2910039 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810040
[email protected]f7022f32014-08-21 16:32:1910041 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810042 EXPECT_EQ(1, d.response_started_count());
10043 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710044 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810045 }
10046}
10047
mmenke9f2ec60c2015-06-01 20:59:4710048TEST_F(URLRequestTestFTP, FTPCheckWrongUser) {
tommycli59a63432015-11-06 00:10:5510049 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110050
[email protected]dd265012009-01-08 20:45:2710051 TestDelegate d;
10052 {
danakj8522a25b2016-04-16 00:17:3610053 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510054 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10055 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710056 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910057 r->Start();
10058 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710059
[email protected]255620da2013-08-19 13:14:2910060 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:2710061
[email protected]f7022f32014-08-21 16:32:1910062 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:2710063 EXPECT_EQ(1, d.response_started_count());
10064 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710065 EXPECT_EQ(0, d.bytes_received());
[email protected]dd265012009-01-08 20:45:2710066 }
10067}
[email protected]8b8a197d2009-08-26 15:57:5810068
mmenke9f2ec60c2015-06-01 20:59:4710069TEST_F(URLRequestTestFTP, FTPCheckWrongUserRestart) {
tommycli59a63432015-11-06 00:10:5510070 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110071
[email protected]8b8a197d2009-08-26 15:57:5810072 TestDelegate d;
10073 // Set correct login credentials. The delegate will be asked for them when
10074 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810075 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:5810076 {
danakj8522a25b2016-04-16 00:17:3610077 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510078 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "wrong_user",
10079 "chrome"),
mmenke9f2ec60c2015-06-01 20:59:4710080 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:1910081 r->Start();
10082 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810083
[email protected]255620da2013-08-19 13:14:2910084 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:5810085
[email protected]f7022f32014-08-21 16:32:1910086 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:5810087 EXPECT_EQ(1, d.response_started_count());
10088 EXPECT_FALSE(d.received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710089 EXPECT_EQ(GetTestFileContents(), d.data_received());
[email protected]8b8a197d2009-08-26 15:57:5810090 }
10091}
[email protected]60a3df52009-09-22 16:13:2410092
mmenke9f2ec60c2015-06-01 20:59:4710093TEST_F(URLRequestTestFTP, FTPCacheURLCredentials) {
tommycli59a63432015-11-06 00:10:5510094 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110095
danakj8522a25b2016-04-16 00:17:3610096 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410097 {
10098 // Pass correct login identity in the URL.
danakj8522a25b2016-04-16 00:17:3610099 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510100 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10101 "chrome"),
10102 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910103 r->Start();
10104 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410105
[email protected]255620da2013-08-19 13:14:2910106 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410107
[email protected]f7022f32014-08-21 16:32:1910108 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410109 EXPECT_EQ(1, d->response_started_count());
10110 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710111 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410112 }
10113
10114 d.reset(new TestDelegate);
10115 {
10116 // This request should use cached identity from previous request.
danakj8522a25b2016-04-16 00:17:3610117 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510118 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910119 r->Start();
10120 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410121
[email protected]255620da2013-08-19 13:14:2910122 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410123
[email protected]f7022f32014-08-21 16:32:1910124 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410125 EXPECT_EQ(1, d->response_started_count());
10126 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710127 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410128 }
10129}
10130
mmenke9f2ec60c2015-06-01 20:59:4710131TEST_F(URLRequestTestFTP, FTPCacheLoginBoxCredentials) {
tommycli59a63432015-11-06 00:10:5510132 ASSERT_TRUE(ftp_test_server_.Start());
[email protected]95409e12010-08-17 20:07:1110133
danakj8522a25b2016-04-16 00:17:3610134 std::unique_ptr<TestDelegate> d(new TestDelegate);
[email protected]60a3df52009-09-22 16:13:2410135 // Set correct login credentials. The delegate will be asked for them when
10136 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:5810137 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:2410138 {
danakj8522a25b2016-04-16 00:17:3610139 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510140 ftp_test_server_.GetURLWithUserAndPassword(kFtpTestFile, "chrome",
10141 "wrong_password"),
davidben151423e2015-03-23 18:48:3610142 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910143 r->Start();
10144 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410145
[email protected]255620da2013-08-19 13:14:2910146 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410147
[email protected]f7022f32014-08-21 16:32:1910148 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410149 EXPECT_EQ(1, d->response_started_count());
10150 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710151 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410152 }
10153
10154 // Use a new delegate without explicit credentials. The cached ones should be
10155 // used.
10156 d.reset(new TestDelegate);
10157 {
10158 // Don't pass wrong credentials in the URL, they would override valid cached
10159 // ones.
danakj8522a25b2016-04-16 00:17:3610160 std::unique_ptr<URLRequest> r(default_context_.CreateRequest(
tommycli59a63432015-11-06 00:10:5510161 ftp_test_server_.GetURL(kFtpTestFile), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:1910162 r->Start();
10163 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410164
[email protected]255620da2013-08-19 13:14:2910165 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:2410166
[email protected]f7022f32014-08-21 16:32:1910167 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:2410168 EXPECT_EQ(1, d->response_started_count());
10169 EXPECT_FALSE(d->received_data_before_response());
mmenke9f2ec60c2015-06-01 20:59:4710170 EXPECT_EQ(GetTestFileContents(), d->data_received());
[email protected]60a3df52009-09-22 16:13:2410171 }
10172}
ricea3a1c71f2016-06-17 10:05:2610173
10174TEST_F(URLRequestTestFTP, RawBodyBytes) {
10175 ASSERT_TRUE(ftp_test_server_.Start());
10176
10177 TestDelegate d;
10178 std::unique_ptr<URLRequest> req(default_context().CreateRequest(
10179 ftp_test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &d));
10180 req->Start();
10181 base::RunLoop().Run();
10182
10183 EXPECT_EQ(6, req->GetRawBodyBytes());
10184}
10185
[email protected]316c1e5e2012-09-12 15:17:4410186#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:5110187
ttuttlec0c828492015-05-15 01:25:5510188TEST_F(URLRequestTest, NetworkAccessedClearOnDataRequest) {
10189 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610190 std::unique_ptr<URLRequest> req(
ttuttlec0c828492015-05-15 01:25:5510191 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
10192
10193 EXPECT_FALSE(req->response_info().network_accessed);
10194
10195 req->Start();
10196 base::RunLoop().Run();
10197
10198 EXPECT_EQ(1, default_network_delegate_.completed_requests());
10199 EXPECT_FALSE(req->response_info().network_accessed);
10200}
10201
10202TEST_F(URLRequestTest, NetworkAccessedSetOnHostResolutionFailure) {
10203 MockHostResolver host_resolver;
10204 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
10205 TestURLRequestContext context(true);
10206 context.set_network_delegate(&network_delegate);
10207 context.set_host_resolver(&host_resolver);
10208 host_resolver.rules()->AddSimulatedFailure("*");
10209 context.Init();
10210
10211 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610212 std::unique_ptr<URLRequest> req(context.CreateRequest(
ttuttlec0c828492015-05-15 01:25:5510213 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
10214
10215 EXPECT_FALSE(req->response_info().network_accessed);
10216
10217 req->Start();
10218 base::RunLoop().Run();
10219 EXPECT_TRUE(req->response_info().network_accessed);
10220}
10221
mmenkeed0498b2015-12-08 23:20:4210222// Test that URLRequest is canceled correctly.
alexanderkcd904b52015-07-24 18:57:2210223// See http://crbug.com/508900
mmenkeed0498b2015-12-08 23:20:4210224TEST_F(URLRequestTest, URLRequestRedirectJobCancelRequest) {
alexanderkcd904b52015-07-24 18:57:2210225 TestDelegate d;
danakj8522a25b2016-04-16 00:17:3610226 std::unique_ptr<URLRequest> req(default_context_.CreateRequest(
alexanderkcd904b52015-07-24 18:57:2210227 GURL("http://not-a-real-domain/"), DEFAULT_PRIORITY, &d));
10228
danakj8522a25b2016-04-16 00:17:3610229 std::unique_ptr<URLRequestRedirectJob> job(new URLRequestRedirectJob(
alexanderkcd904b52015-07-24 18:57:2210230 req.get(), &default_network_delegate_,
10231 GURL("http://this-should-never-be-navigated-to/"),
mmenkeed0498b2015-12-08 23:20:4210232 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT, "Jumbo shrimp"));
10233 AddTestInterceptor()->set_main_intercept_job(std::move(job));
alexanderkcd904b52015-07-24 18:57:2210234
10235 req->Start();
10236 req->Cancel();
alexanderkcd904b52015-07-24 18:57:2210237 base::RunLoop().RunUntilIdle();
maksim.sisovb53724b52016-09-16 05:30:5010238 EXPECT_EQ(ERR_ABORTED, d.request_status());
alexanderkcd904b52015-07-24 18:57:2210239 EXPECT_EQ(0, d.received_redirect_count());
10240}
10241
[email protected]7461a402011-03-24 23:19:5110242} // namespace net