blob: b114ecc2dfe8509e3a951d1ede8e63417f25ebd5 [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
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
initial.commit586acc5fe2008-07-26 22:42:5212#include <algorithm>
13#include <string>
14
[email protected]aad63572011-05-24 20:14:3915#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3816#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5817#include "base/compiler_specific.h"
thestigd8df0332014-09-04 06:33:2918#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0719#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2820#include "base/format_macros.h"
mmenke19378d22014-09-09 04:12:5921#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4722#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2223#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2924#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5225#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2926#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5027#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5528#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2229#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2230#include "base/strings/string_util.h"
31#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0532#include "base/strings/utf_string_conversions.h"
[email protected]58e32bb2013-01-21 18:23:2533#include "net/base/capturing_net_log.h"
mmenkecbc2b712014-10-09 20:29:0734#include "net/base/chunked_upload_data_stream.h"
35#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5236#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2537#include "net/base/load_timing_info.h"
38#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0639#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5340#include "net/base/net_log.h"
41#include "net/base/net_log_unittest.h"
initial.commit586acc5fe2008-07-26 22:42:5242#include "net/base/net_module.h"
43#include "net/base/net_util.h"
[email protected]2ca01e52013-10-31 22:05:1944#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4045#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2846#include "net/base/upload_bytes_element_reader.h"
47#include "net/base/upload_data_stream.h"
48#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1149#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2450#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1151#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0652#include "net/cookies/cookie_monster.h"
53#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5254#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5355#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4256#include "net/ftp/ftp_network_layer.h"
[email protected]b7572ea2013-11-26 20:16:3857#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5258#include "net/http/http_cache.h"
59#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1960#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2561#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2162#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0063#include "net/http/http_util.h"
[email protected]dffe8242012-03-20 15:14:2764#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2765#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1966#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0967#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5768#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1169#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2170#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3471#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4372#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5273#include "net/url_request/url_request.h"
[email protected]bcb84f8b2009-08-31 16:20:1474#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5075#include "net/url_request/url_request_intercepting_job_factory.h"
76#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4977#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5178#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4779#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4480#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5281#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1582#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5283
[email protected]02494ec2014-05-07 15:05:2984#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5585#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2986#include "net/url_request/file_protocol_handler.h"
87#include "net/url_request/url_request_file_dir_job.h"
88#endif
89
90#if !defined(DISABLE_FTP_SUPPORT)
91#include "net/url_request/ftp_protocol_handler.h"
92#endif
93
[email protected]dffe8242012-03-20 15:14:2794#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4895#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5696#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2797#include "base/win/windows_version.h"
98#endif
99
[email protected]ad65a3e2013-12-25 18:18:01100using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33101using base::Time;
102
[email protected]7461a402011-03-24 23:19:51103namespace net {
104
initial.commit586acc5fe2008-07-26 22:42:52105namespace {
106
[email protected]42cba2fb2013-03-29 19:58:57107const base::string16 kChrome(ASCIIToUTF16("chrome"));
108const base::string16 kSecret(ASCIIToUTF16("secret"));
109const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44110
[email protected]2bba3252013-04-08 19:50:59111// Tests load timing information in the case a fresh connection was used, with
112// no proxy.
[email protected]cba24642014-08-15 20:49:59113void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25114 int connect_timing_flags) {
115 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59116 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25117
118 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
119 EXPECT_FALSE(load_timing_info.request_start.is_null());
120
121 EXPECT_LE(load_timing_info.request_start,
122 load_timing_info.connect_timing.connect_start);
123 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
124 connect_timing_flags);
125 EXPECT_LE(load_timing_info.connect_timing.connect_end,
126 load_timing_info.send_start);
127 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
128 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
129
[email protected]58e32bb2013-01-21 18:23:25130 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
131 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
132}
133
[email protected]2bba3252013-04-08 19:50:59134// Same as above, but with proxy times.
135void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59136 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59137 int connect_timing_flags) {
138 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59139 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59140
141 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
142 EXPECT_FALSE(load_timing_info.request_start.is_null());
143
144 EXPECT_LE(load_timing_info.request_start,
145 load_timing_info.proxy_resolve_start);
146 EXPECT_LE(load_timing_info.proxy_resolve_start,
147 load_timing_info.proxy_resolve_end);
148 EXPECT_LE(load_timing_info.proxy_resolve_end,
149 load_timing_info.connect_timing.connect_start);
150 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
151 connect_timing_flags);
152 EXPECT_LE(load_timing_info.connect_timing.connect_end,
153 load_timing_info.send_start);
154 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
155 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
156}
157
158// Same as above, but with a reused socket and proxy times.
159void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59160 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59161 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59162 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59163
164 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165 EXPECT_FALSE(load_timing_info.request_start.is_null());
166
167 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
168
169 EXPECT_LE(load_timing_info.request_start,
170 load_timing_info.proxy_resolve_start);
171 EXPECT_LE(load_timing_info.proxy_resolve_start,
172 load_timing_info.proxy_resolve_end);
173 EXPECT_LE(load_timing_info.proxy_resolve_end,
174 load_timing_info.send_start);
175 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
176 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
177}
178
[email protected]3b23a222013-05-15 21:33:25179// Tests load timing information in the case of a cache hit, when no cache
180// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17181base::StringPiece TestNetResourceProvider(int key) {
182 return "header";
183}
184
185void FillBuffer(char* buffer, size_t len) {
186 static bool called = false;
187 if (!called) {
188 called = true;
189 int seed = static_cast<int>(Time::Now().ToInternalValue());
190 srand(seed);
191 }
192
193 for (size_t i = 0; i < len; i++) {
194 buffer[i] = static_cast<char>(rand());
195 if (!buffer[i])
196 buffer[i] = 'g';
197 }
198}
199
200#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25201void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59202 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25203 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59204 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25205
206 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
207 EXPECT_FALSE(load_timing_info.request_start.is_null());
208
209 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
210 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
211 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
212 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
213
214 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
215 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
216}
217
218// Tests load timing in the case that there is no HTTP response. This can be
219// used to test in the case of errors or non-HTTP requests.
220void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59221 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25222 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59223 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25224
225 // Only the request times should be non-null.
226 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
227 EXPECT_FALSE(load_timing_info.request_start.is_null());
228
229 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
230
231 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
232 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
233 EXPECT_TRUE(load_timing_info.send_start.is_null());
234 EXPECT_TRUE(load_timing_info.send_end.is_null());
235 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
236}
237
[email protected]71c64f62008-11-15 04:36:51238// Do a case-insensitive search through |haystack| for |needle|.
239bool ContainsString(const std::string& haystack, const char* needle) {
240 std::string::const_iterator it =
241 std::search(haystack.begin(),
242 haystack.end(),
243 needle,
244 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35245 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51246 return it != haystack.end();
247}
248
mmenkecbc2b712014-10-09 20:29:07249scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28250 scoped_ptr<UploadElementReader> reader(
251 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07252 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23253}
254
[email protected]96adadb2010-08-28 01:16:17255// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51256void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17257 // -1 means unknown. 0 means no encryption.
258 EXPECT_GT(ssl_info.security_bits, 0);
259
260 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29261 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17262 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29263 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17264}
265
[email protected]79e1fd62013-06-20 06:50:04266void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
267 const GURL& host_url) {
268 std::string sent_value;
269
270 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
271 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
272
273 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
274 EXPECT_EQ("keep-alive", sent_value);
275}
276
[email protected]ede03212012-09-07 12:52:26277bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27278 size_t size = a.size();
279
280 if (size != b.size())
281 return false;
282
283 for (size_t i = 0; i < size; ++i) {
284 if (!a[i].Equals(b[i]))
285 return false;
286 }
287
288 return true;
289}
[email protected]e3a85452013-11-14 01:46:17290#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27291
[email protected]dc5a5cf2012-09-26 02:49:30292// A network delegate that allows the user to choose a subset of request stages
293// to block in. When blocking, the delegate can do one of the following:
294// * synchronously return a pre-specified error code, or
295// * asynchronously return that value via an automatically called callback,
296// or
297// * block and wait for the user to do a callback.
298// Additionally, the user may also specify a redirect URL -- then each request
299// with the current URL different from the redirect target will be redirected
300// to that target, in the on-before-URL-request stage, independent of whether
301// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12302class BlockingNetworkDelegate : public TestNetworkDelegate {
303 public:
[email protected]dc5a5cf2012-09-26 02:49:30304 // Stages in which the delegate can block.
305 enum Stage {
[email protected]9045b8822012-01-13 20:35:35306 NOT_BLOCKED = 0,
307 ON_BEFORE_URL_REQUEST = 1 << 0,
308 ON_BEFORE_SEND_HEADERS = 1 << 1,
309 ON_HEADERS_RECEIVED = 1 << 2,
310 ON_AUTH_REQUIRED = 1 << 3
311 };
312
[email protected]dc5a5cf2012-09-26 02:49:30313 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59314 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30315 enum BlockMode {
316 SYNCHRONOUS, // No callback, returns specified return values.
317 AUTO_CALLBACK, // |this| posts a task to run the callback using the
318 // specified return codes.
319 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
320 // |auth_retval_| are ignored. In every blocking stage the
321 // message loop is quit.
322 };
323
324 // Creates a delegate which does not block at all.
325 explicit BlockingNetworkDelegate(BlockMode block_mode);
326
327 // For users to trigger a callback returning |response|.
328 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
329 // Only call if |block_mode_| == USER_CALLBACK.
330 void DoCallback(int response);
331 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
332
333 // Setters.
334 void set_retval(int retval) {
335 ASSERT_NE(USER_CALLBACK, block_mode_);
336 ASSERT_NE(ERR_IO_PENDING, retval);
337 ASSERT_NE(OK, retval);
338 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35339 }
340
[email protected]dc5a5cf2012-09-26 02:49:30341 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
342 // |auth_credentials_| will be passed with the response.
343 void set_auth_retval(AuthRequiredResponse auth_retval) {
344 ASSERT_NE(USER_CALLBACK, block_mode_);
345 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
346 auth_retval_ = auth_retval;
347 }
348 void set_auth_credentials(const AuthCredentials& auth_credentials) {
349 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35350 }
351
[email protected]dc5a5cf2012-09-26 02:49:30352 void set_redirect_url(const GURL& url) {
353 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35354 }
355
[email protected]dc5a5cf2012-09-26 02:49:30356 void set_block_on(int block_on) {
357 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35358 }
359
[email protected]dc5a5cf2012-09-26 02:49:30360 // Allows the user to check in which state did we block.
361 Stage stage_blocked_for_callback() const {
362 EXPECT_EQ(USER_CALLBACK, block_mode_);
363 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35364 }
365
366 private:
[email protected]dc5a5cf2012-09-26 02:49:30367 void RunCallback(int response, const CompletionCallback& callback);
368 void RunAuthCallback(AuthRequiredResponse response,
369 const AuthCallback& callback);
370
[email protected]9045b8822012-01-13 20:35:35371 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20372 int OnBeforeURLRequest(URLRequest* request,
373 const CompletionCallback& callback,
374 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35375
dchengb03027d2014-10-21 12:00:20376 int OnBeforeSendHeaders(URLRequest* request,
377 const CompletionCallback& callback,
378 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35379
dchengb03027d2014-10-21 12:00:20380 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35381 URLRequest* request,
382 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32383 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16384 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13385 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35386
dchengb03027d2014-10-21 12:00:20387 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35388 URLRequest* request,
389 const AuthChallengeInfo& auth_info,
390 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13391 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35392
[email protected]dc5a5cf2012-09-26 02:49:30393 // Resets the callbacks and |stage_blocked_for_callback_|.
394 void Reset();
[email protected]9045b8822012-01-13 20:35:35395
[email protected]dc5a5cf2012-09-26 02:49:30396 // Checks whether we should block in |stage|. If yes, returns an error code
397 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
398 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
399
400 // Configuration parameters, can be adjusted by public methods:
401 const BlockMode block_mode_;
402
403 // Values returned on blocking stages when mode is SYNCHRONOUS or
404 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
405 int retval_; // To be returned in non-auth stages.
406 AuthRequiredResponse auth_retval_;
407
[email protected]5f714132014-03-26 10:41:16408 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30409 int block_on_; // Bit mask: in which stages to block.
410
411 // |auth_credentials_| will be copied to |*target_auth_credential_| on
412 // callback.
413 AuthCredentials auth_credentials_;
414 AuthCredentials* target_auth_credentials_;
415
416 // Internal variables, not set by not the user:
417 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
418 // USER_CALLBACK).
419 Stage stage_blocked_for_callback_;
420
421 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35422 CompletionCallback callback_;
423 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30424
425 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
426
427 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35428};
429
[email protected]dc5a5cf2012-09-26 02:49:30430BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
431 : block_mode_(block_mode),
432 retval_(OK),
433 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
434 block_on_(0),
435 target_auth_credentials_(NULL),
436 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32437 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30438}
439
440void BlockingNetworkDelegate::DoCallback(int response) {
441 ASSERT_EQ(USER_CALLBACK, block_mode_);
442 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
443 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
444 CompletionCallback callback = callback_;
445 Reset();
446 RunCallback(response, callback);
447}
448
449void BlockingNetworkDelegate::DoAuthCallback(
450 NetworkDelegate::AuthRequiredResponse response) {
451 ASSERT_EQ(USER_CALLBACK, block_mode_);
452 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
453 AuthCallback auth_callback = auth_callback_;
454 Reset();
455 RunAuthCallback(response, auth_callback);
456}
457
458void BlockingNetworkDelegate::RunCallback(int response,
459 const CompletionCallback& callback) {
460 callback.Run(response);
461}
462
463void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
464 const AuthCallback& callback) {
465 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
466 ASSERT_TRUE(target_auth_credentials_ != NULL);
467 *target_auth_credentials_ = auth_credentials_;
468 }
469 callback.Run(response);
470}
471
472int BlockingNetworkDelegate::OnBeforeURLRequest(
473 URLRequest* request,
474 const CompletionCallback& callback,
475 GURL* new_url) {
476 if (redirect_url_ == request->url())
477 return OK; // We've already seen this request and redirected elsewhere.
478
479 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
480
481 if (!redirect_url_.is_empty())
482 *new_url = redirect_url_;
483
484 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
485}
486
487int BlockingNetworkDelegate::OnBeforeSendHeaders(
488 URLRequest* request,
489 const CompletionCallback& callback,
490 HttpRequestHeaders* headers) {
491 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
492
493 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
494}
495
496int BlockingNetworkDelegate::OnHeadersReceived(
497 URLRequest* request,
498 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32499 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16500 scoped_refptr<HttpResponseHeaders>* override_response_headers,
501 GURL* allowed_unsafe_redirect_url) {
502 TestNetworkDelegate::OnHeadersReceived(request,
503 callback,
504 original_response_headers,
505 override_response_headers,
506 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30507
508 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
509}
510
511NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
512 URLRequest* request,
513 const AuthChallengeInfo& auth_info,
514 const AuthCallback& callback,
515 AuthCredentials* credentials) {
516 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
517 credentials);
518 // Check that the user has provided callback for the previous blocked stage.
519 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
520
521 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
522 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
523 }
524
525 target_auth_credentials_ = credentials;
526
527 switch (block_mode_) {
528 case SYNCHRONOUS:
529 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
530 *target_auth_credentials_ = auth_credentials_;
531 return auth_retval_;
532
533 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34534 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30535 FROM_HERE,
536 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
537 weak_factory_.GetWeakPtr(), auth_retval_, callback));
538 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
539
540 case USER_CALLBACK:
541 auth_callback_ = callback;
542 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34543 base::MessageLoop::current()->PostTask(FROM_HERE,
544 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30545 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
546 }
547 NOTREACHED();
548 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
549}
550
551void BlockingNetworkDelegate::Reset() {
552 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
553 stage_blocked_for_callback_ = NOT_BLOCKED;
554 callback_.Reset();
555 auth_callback_.Reset();
556}
557
558int BlockingNetworkDelegate::MaybeBlockStage(
559 BlockingNetworkDelegate::Stage stage,
560 const CompletionCallback& callback) {
561 // Check that the user has provided callback for the previous blocked stage.
562 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
563
564 if ((block_on_ & stage) == 0) {
565 return OK;
566 }
567
568 switch (block_mode_) {
569 case SYNCHRONOUS:
570 EXPECT_NE(OK, retval_);
571 return retval_;
572
573 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34574 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30575 FROM_HERE,
576 base::Bind(&BlockingNetworkDelegate::RunCallback,
577 weak_factory_.GetWeakPtr(), retval_, callback));
578 return ERR_IO_PENDING;
579
580 case USER_CALLBACK:
581 callback_ = callback;
582 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34583 base::MessageLoop::current()->PostTask(FROM_HERE,
584 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30585 return ERR_IO_PENDING;
586 }
587 NOTREACHED();
588 return 0;
589}
590
[email protected]d5a4dd62012-05-23 01:41:04591class TestURLRequestContextWithProxy : public TestURLRequestContext {
592 public:
593 // Does not own |delegate|.
594 TestURLRequestContextWithProxy(const std::string& proxy,
595 NetworkDelegate* delegate)
596 : TestURLRequestContext(true) {
597 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
598 set_network_delegate(delegate);
599 Init();
600 }
dchengb03027d2014-10-21 12:00:20601 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04602};
603
604} // namespace
605
[email protected]a592c0432012-12-01 18:10:29606// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48607class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00608 public:
[email protected]ef2bf422012-05-11 03:27:09609 URLRequestTest() : default_context_(true) {
610 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25611 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50612 job_factory_impl_ = new URLRequestJobFactoryImpl();
613 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50614 }
bengr1bf8e942014-11-07 01:36:50615
dcheng67be2b1f2014-10-27 21:47:29616 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18617 // URLRequestJobs may post clean-up tasks on destruction.
618 base::RunLoop().RunUntilIdle();
619 }
[email protected]87a09a92011-07-14 15:50:50620
bengr1bf8e942014-11-07 01:36:50621 virtual void SetUp() {
622 SetUpFactory();
623 default_context_.set_job_factory(job_factory_.get());
624 default_context_.Init();
625 PlatformTest::SetUp();
626 }
627
628 virtual void SetUpFactory() {
629 job_factory_impl_->SetProtocolHandler("data", new DataProtocolHandler);
630#if !defined(DISABLE_FILE_SUPPORT)
631 job_factory_impl_->SetProtocolHandler(
632 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
633#endif
634 }
635
636 TestNetworkDelegate* default_network_delegate() {
637 return &default_network_delegate_;
638 }
639
640 const TestURLRequestContext& default_context() const {
641 return default_context_;
642 }
643
644
[email protected]3c5ca8c2011-09-29 01:14:51645 // Adds the TestJobInterceptor to the default context.
646 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23647 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
bengr1bf8e942014-11-07 01:36:50648 job_factory_impl_->SetProtocolHandler("http", NULL);
649 job_factory_impl_->SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23650 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51651 }
652
[email protected]87a09a92011-07-14 15:50:50653 protected:
[email protected]58e32bb2013-01-21 18:23:25654 CapturingNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24655 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
bengr1bf8e942014-11-07 01:36:50656 URLRequestJobFactoryImpl* job_factory_impl_;
657 scoped_ptr<URLRequestJobFactory> job_factory_;
[email protected]ef2bf422012-05-11 03:27:09658 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48659};
660
[email protected]316c1e5e2012-09-12 15:17:44661TEST_F(URLRequestTest, AboutBlankTest) {
662 TestDelegate d;
663 {
[email protected]f7022f32014-08-21 16:32:19664 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
665 GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44666
[email protected]f7022f32014-08-21 16:32:19667 r->Start();
668 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44669
[email protected]255620da2013-08-19 13:14:29670 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44671
[email protected]f7022f32014-08-21 16:32:19672 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44673 EXPECT_FALSE(d.received_data_before_response());
674 EXPECT_EQ(d.bytes_received(), 0);
[email protected]f7022f32014-08-21 16:32:19675 EXPECT_EQ("", r->GetSocketAddress().host());
676 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04677
678 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19679 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44680 }
681}
682
683TEST_F(URLRequestTest, DataURLImageTest) {
684 TestDelegate d;
685 {
686 // Use our nice little Chrome logo.
[email protected]f7022f32014-08-21 16:32:19687 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:19688 GURL(
[email protected]316c1e5e2012-09-12 15:17:44689 "data:image/png;base64,"
690 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
691 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
692 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
693 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
694 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
695 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
696 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
697 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
698 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
699 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
700 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
701 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
702 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
703 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
704 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
705 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
706 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
707 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
[email protected]f7022f32014-08-21 16:32:19708 DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44709
[email protected]f7022f32014-08-21 16:32:19710 r->Start();
711 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44712
[email protected]255620da2013-08-19 13:14:29713 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44714
[email protected]f7022f32014-08-21 16:32:19715 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44716 EXPECT_FALSE(d.received_data_before_response());
717 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19718 EXPECT_EQ("", r->GetSocketAddress().host());
719 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04720
721 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19722 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44723 }
724}
725
[email protected]5ecf7cb282014-05-11 01:49:55726#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44727TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15728 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44729 PathService::Get(base::FILE_EXE, &app_path);
730 GURL app_url = FilePathToFileURL(app_path);
731
732 TestDelegate d;
733 {
[email protected]f7022f32014-08-21 16:32:19734 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
735 app_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44736
[email protected]f7022f32014-08-21 16:32:19737 r->Start();
738 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44739
[email protected]255620da2013-08-19 13:14:29740 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44741
742 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49743 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44744
[email protected]f7022f32014-08-21 16:32:19745 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44746 EXPECT_EQ(1, d.response_started_count());
747 EXPECT_FALSE(d.received_data_before_response());
748 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19749 EXPECT_EQ("", r->GetSocketAddress().host());
750 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04751
752 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19753 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44754 }
755}
756
[email protected]ba40bb762012-12-17 07:11:04757TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15758 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04759 PathService::Get(base::FILE_EXE, &app_path);
760 GURL app_url = FilePathToFileURL(app_path);
761
762 TestDelegate d;
763 {
[email protected]f7022f32014-08-21 16:32:19764 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
765 app_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]ba40bb762012-12-17 07:11:04766
[email protected]f7022f32014-08-21 16:32:19767 r->Start();
768 EXPECT_TRUE(r->is_pending());
769 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04770 }
[email protected]79e1fd62013-06-20 06:50:04771 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04772 // destroyed.
[email protected]255620da2013-08-19 13:14:29773 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04774}
775
[email protected]316c1e5e2012-09-12 15:17:44776TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
777 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17778 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44779 FillBuffer(buffer.get(), buffer_size);
780
[email protected]6cdfd7f2013-02-08 20:40:15781 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52782 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44783 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30784 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44785
786 int64 file_size;
[email protected]56285702013-12-04 18:22:49787 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44788
789 const size_t first_byte_position = 500;
790 const size_t last_byte_position = buffer_size - first_byte_position;
791 const size_t content_length = last_byte_position - first_byte_position + 1;
792 std::string partial_buffer_string(buffer.get() + first_byte_position,
793 buffer.get() + last_byte_position + 1);
794
795 TestDelegate d;
796 {
[email protected]f7022f32014-08-21 16:32:19797 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
798 temp_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44799
800 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38801 headers.SetHeader(
802 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59803 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38804 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19805 r->SetExtraRequestHeaders(headers);
806 r->Start();
807 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44808
[email protected]255620da2013-08-19 13:14:29809 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19810 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44811 EXPECT_EQ(1, d.response_started_count());
812 EXPECT_FALSE(d.received_data_before_response());
813 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
814 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
815 EXPECT_TRUE(partial_buffer_string == d.data_received());
816 }
817
[email protected]dd3aa792013-07-16 19:10:23818 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44819}
820
821TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
822 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17823 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44824 FillBuffer(buffer.get(), buffer_size);
825
[email protected]6cdfd7f2013-02-08 20:40:15826 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52827 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44828 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30829 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44830
831 int64 file_size;
[email protected]56285702013-12-04 18:22:49832 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44833
834 const size_t first_byte_position = 500;
835 const size_t last_byte_position = buffer_size - 1;
836 const size_t content_length = last_byte_position - first_byte_position + 1;
837 std::string partial_buffer_string(buffer.get() + first_byte_position,
838 buffer.get() + last_byte_position + 1);
839
840 TestDelegate d;
841 {
[email protected]f7022f32014-08-21 16:32:19842 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
843 temp_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44844
845 HttpRequestHeaders headers;
846 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59847 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38848 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19849 r->SetExtraRequestHeaders(headers);
850 r->Start();
851 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44852
[email protected]255620da2013-08-19 13:14:29853 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19854 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44855 EXPECT_EQ(1, d.response_started_count());
856 EXPECT_FALSE(d.received_data_before_response());
857 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
858 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
859 EXPECT_TRUE(partial_buffer_string == d.data_received());
860 }
861
[email protected]dd3aa792013-07-16 19:10:23862 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44863}
864
865TEST_F(URLRequestTest, FileTestMultipleRanges) {
866 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17867 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44868 FillBuffer(buffer.get(), buffer_size);
869
[email protected]6cdfd7f2013-02-08 20:40:15870 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52871 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44872 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30873 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44874
875 int64 file_size;
[email protected]56285702013-12-04 18:22:49876 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44877
878 TestDelegate d;
879 {
[email protected]f7022f32014-08-21 16:32:19880 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
881 temp_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:44882
883 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38884 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19885 r->SetExtraRequestHeaders(headers);
886 r->Start();
887 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44888
[email protected]255620da2013-08-19 13:14:29889 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44890 EXPECT_TRUE(d.request_failed());
891 }
892
[email protected]dd3aa792013-07-16 19:10:23893 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44894}
895
[email protected]3ca8b362013-11-11 22:18:07896TEST_F(URLRequestTest, AllowFileURLs) {
897 base::ScopedTempDir temp_dir;
898 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
899 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52900 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07901 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30902 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59903 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07904
905 {
906 TestDelegate d;
907 TestNetworkDelegate network_delegate;
908 network_delegate.set_can_access_files(true);
909 default_context_.set_network_delegate(&network_delegate);
[email protected]f7022f32014-08-21 16:32:19910 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
911 test_file_url, DEFAULT_PRIORITY, &d, NULL));
912 r->Start();
[email protected]3ca8b362013-11-11 22:18:07913 base::RunLoop().Run();
914 EXPECT_FALSE(d.request_failed());
915 EXPECT_EQ(test_data, d.data_received());
916 }
917
918 {
919 TestDelegate d;
920 TestNetworkDelegate network_delegate;
921 network_delegate.set_can_access_files(false);
922 default_context_.set_network_delegate(&network_delegate);
[email protected]f7022f32014-08-21 16:32:19923 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
924 test_file_url, DEFAULT_PRIORITY, &d, NULL));
925 r->Start();
[email protected]3ca8b362013-11-11 22:18:07926 base::RunLoop().Run();
927 EXPECT_TRUE(d.request_failed());
928 EXPECT_EQ("", d.data_received());
929 }
930}
931
[email protected]316c1e5e2012-09-12 15:17:44932
933TEST_F(URLRequestTest, FileDirCancelTest) {
934 // Put in mock resource provider.
935 NetModule::SetResourceProvider(TestNetResourceProvider);
936
937 TestDelegate d;
938 {
[email protected]6cdfd7f2013-02-08 20:40:15939 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44940 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
941 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
942 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
943
[email protected]f7022f32014-08-21 16:32:19944 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
945 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
946 req->Start();
947 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44948
949 d.set_cancel_in_received_data_pending(true);
950
[email protected]255620da2013-08-19 13:14:29951 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44952 }
953
954 // Take out mock resource provider.
955 NetModule::SetResourceProvider(NULL);
956}
957
[email protected]5f9581402013-10-30 13:08:32958TEST_F(URLRequestTest, FileDirOutputSanity) {
959 // Verify the general sanity of the the output of the file:
960 // directory lister by checking for the output of a known existing
961 // file.
962 const char sentinel_name[] = "filedir-sentinel";
963
964 base::FilePath path;
965 PathService::Get(base::DIR_SOURCE_ROOT, &path);
966 path = path.Append(FILE_PATH_LITERAL("net"));
967 path = path.Append(FILE_PATH_LITERAL("data"));
968 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
969
970 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19971 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
972 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
973 req->Start();
[email protected]5f9581402013-10-30 13:08:32974 base::RunLoop().Run();
975
976 // Generate entry for the sentinel file.
977 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58978 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49979 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32980 EXPECT_GT(info.size, 0);
981 std::string sentinel_output = GetDirectoryListingEntry(
982 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
983 std::string(sentinel_name),
984 false /* is_dir */,
985 info.size,
986 info.last_modified);
987
988 ASSERT_LT(0, d.bytes_received());
989 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:19990 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:32991 // Check for the entry generated for the "sentinel" file.
992 const std::string& data = d.data_received();
993 ASSERT_NE(data.find(sentinel_output), std::string::npos);
994}
995
[email protected]316c1e5e2012-09-12 15:17:44996TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
997 // There is an implicit redirect when loading a file path that matches a
998 // directory and does not end with a slash. Ensure that following such
999 // redirects does not crash. See http://crbug.com/18686.
1000
[email protected]6cdfd7f2013-02-08 20:40:151001 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441002 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1003 path = path.Append(FILE_PATH_LITERAL("net"));
1004 path = path.Append(FILE_PATH_LITERAL("data"));
1005 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1006
1007 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191008 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1009 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
1010 req->Start();
[email protected]255620da2013-08-19 13:14:291011 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441012
1013 ASSERT_EQ(1, d.received_redirect_count());
1014 ASSERT_LT(0, d.bytes_received());
1015 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191016 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441017}
1018
1019#if defined(OS_WIN)
1020// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1021TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1022 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191023 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1024 GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1025 req->Start();
[email protected]255620da2013-08-19 13:14:291026 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441027
1028 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191029 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441030}
[email protected]5ecf7cb282014-05-11 01:49:551031#endif // defined(OS_WIN)
1032
1033#endif // !defined(DISABLE_FILE_SUPPORT)
1034
1035TEST_F(URLRequestTest, InvalidUrlTest) {
1036 TestDelegate d;
1037 {
[email protected]f7022f32014-08-21 16:32:191038 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1039 GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5ecf7cb282014-05-11 01:49:551040
[email protected]f7022f32014-08-21 16:32:191041 r->Start();
1042 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551043
1044 base::RunLoop().Run();
1045 EXPECT_TRUE(d.request_failed());
1046 }
1047}
1048
jochen0e3b3a62014-09-16 18:31:231049TEST_F(URLRequestTest, InvalidReferrerTest) {
1050 TestURLRequestContext context;
1051 TestNetworkDelegate network_delegate;
1052 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1053 context.set_network_delegate(&network_delegate);
1054 TestDelegate d;
1055 scoped_ptr<URLRequest> req(context.CreateRequest(
1056 GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1057 req->SetReferrer("https://somewhere.com/");
1058
1059 req->Start();
1060 base::RunLoop().Run();
1061 EXPECT_TRUE(d.request_failed());
1062}
1063
[email protected]5ecf7cb282014-05-11 01:49:551064#if defined(OS_WIN)
1065TEST_F(URLRequestTest, ResolveShortcutTest) {
1066 base::FilePath app_path;
1067 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1068 app_path = app_path.AppendASCII("net");
1069 app_path = app_path.AppendASCII("data");
1070 app_path = app_path.AppendASCII("url_request_unittest");
1071 app_path = app_path.AppendASCII("with-headers.html");
1072
1073 std::wstring lnk_path = app_path.value() + L".lnk";
1074
1075 base::win::ScopedCOMInitializer com_initializer;
1076
1077 // Temporarily create a shortcut for test
1078 {
1079 base::win::ScopedComPtr<IShellLink> shell;
1080 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1081 CLSCTX_INPROC_SERVER)));
1082 base::win::ScopedComPtr<IPersistFile> persist;
1083 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1084 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1085 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1086 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1087 }
1088
1089 TestDelegate d;
1090 {
[email protected]f7022f32014-08-21 16:32:191091 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1092 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1093 NULL));
[email protected]5ecf7cb282014-05-11 01:49:551094
[email protected]f7022f32014-08-21 16:32:191095 r->Start();
1096 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551097
1098 base::RunLoop().Run();
1099
1100 WIN32_FILE_ATTRIBUTE_DATA data;
1101 GetFileAttributesEx(app_path.value().c_str(),
1102 GetFileExInfoStandard, &data);
1103 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1104 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1105 FILE_ATTRIBUTE_NORMAL, NULL);
1106 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1107 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1108 DWORD read_size;
1109 BOOL result;
1110 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1111 &read_size, NULL);
1112 std::string content(buffer.get(), read_size);
1113 CloseHandle(file);
1114
[email protected]f7022f32014-08-21 16:32:191115 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551116 EXPECT_EQ(1, d.received_redirect_count());
1117 EXPECT_EQ(content, d.data_received());
1118 }
1119
1120 // Clean the shortcut
1121 DeleteFile(lnk_path.c_str());
1122}
1123#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441124
1125// Custom URLRequestJobs for use with interceptor tests
1126class RestartTestJob : public URLRequestTestJob {
1127 public:
1128 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1129 : URLRequestTestJob(request, network_delegate, true) {}
1130 protected:
dchengb03027d2014-10-21 12:00:201131 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441132 private:
dchengb03027d2014-10-21 12:00:201133 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441134};
1135
1136class CancelTestJob : public URLRequestTestJob {
1137 public:
1138 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139 : URLRequestTestJob(request, network_delegate, true) {}
1140 protected:
dchengb03027d2014-10-21 12:00:201141 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441142 private:
dchengb03027d2014-10-21 12:00:201143 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441144};
1145
1146class CancelThenRestartTestJob : public URLRequestTestJob {
1147 public:
1148 explicit CancelThenRestartTestJob(URLRequest* request,
1149 NetworkDelegate* network_delegate)
1150 : URLRequestTestJob(request, network_delegate, true) {
1151 }
1152 protected:
dchengb03027d2014-10-21 12:00:201153 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441154 request_->Cancel();
1155 this->NotifyRestartRequired();
1156 }
1157 private:
dchengb03027d2014-10-21 12:00:201158 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441159};
1160
bengr1bf8e942014-11-07 01:36:501161// An Interceptor for use with interceptor tests.
1162class MockURLRequestInterceptor : public URLRequestInterceptor {
1163 public:
1164 // Static getters for canned response header and data strings.
1165 static std::string ok_data() {
1166 return URLRequestTestJob::test_data_1();
1167 }
1168
1169 static std::string ok_headers() {
1170 return URLRequestTestJob::test_headers();
1171 }
1172
1173 static std::string redirect_data() {
1174 return std::string();
1175 }
1176
1177 static std::string redirect_headers() {
1178 return URLRequestTestJob::test_redirect_headers();
1179 }
1180
1181 static std::string error_data() {
1182 return std::string("ohhh nooooo mr. bill!");
1183 }
1184
1185 static std::string error_headers() {
1186 return URLRequestTestJob::test_error_headers();
1187 }
1188
1189 MockURLRequestInterceptor()
1190 : intercept_main_request_(false), restart_main_request_(false),
1191 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1192 simulate_main_network_error_(false),
1193 intercept_redirect_(false), cancel_redirect_request_(false),
1194 intercept_final_response_(false), cancel_final_request_(false),
1195 use_url_request_http_job_(false),
1196 did_intercept_main_(false), did_restart_main_(false),
1197 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1198 did_simulate_error_main_(false),
1199 did_intercept_redirect_(false), did_cancel_redirect_(false),
1200 did_intercept_final_(false), did_cancel_final_(false) {
1201 }
1202
1203 ~MockURLRequestInterceptor() override {
1204 }
1205
1206 // URLRequestInterceptor implementation:
1207 URLRequestJob* MaybeInterceptRequest(
1208 URLRequest* request,
1209 NetworkDelegate* network_delegate) const override {
1210 if (restart_main_request_) {
1211 restart_main_request_ = false;
1212 did_restart_main_ = true;
1213 return new RestartTestJob(request, network_delegate);
1214 }
1215 if (cancel_main_request_) {
1216 cancel_main_request_ = false;
1217 did_cancel_main_ = true;
1218 return new CancelTestJob(request, network_delegate);
1219 }
1220 if (cancel_then_restart_main_request_) {
1221 cancel_then_restart_main_request_ = false;
1222 did_cancel_then_restart_main_ = true;
1223 return new CancelThenRestartTestJob(request, network_delegate);
1224 }
1225 if (simulate_main_network_error_) {
1226 simulate_main_network_error_ = false;
1227 did_simulate_error_main_ = true;
1228 if (use_url_request_http_job_) {
1229 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1230 }
1231 // This job will result in error since the requested URL is not one of the
1232 // URLs supported by these tests.
1233 return new URLRequestTestJob(request, network_delegate, true);
1234 }
1235 if (!intercept_main_request_)
1236 return nullptr;
1237 intercept_main_request_ = false;
1238 did_intercept_main_ = true;
1239 URLRequestTestJob* job = new URLRequestTestJob(request,
1240 network_delegate,
1241 main_headers_,
1242 main_data_,
1243 true);
1244 job->set_load_timing_info(main_request_load_timing_info_);
1245 return job;
1246 }
1247
1248 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1249 NetworkDelegate* network_delegate,
1250 const GURL& location) const override {
1251 if (cancel_redirect_request_) {
1252 cancel_redirect_request_ = false;
1253 did_cancel_redirect_ = true;
1254 return new CancelTestJob(request, network_delegate);
1255 }
1256 if (!intercept_redirect_)
1257 return nullptr;
1258 intercept_redirect_ = false;
1259 did_intercept_redirect_ = true;
1260 if (use_url_request_http_job_) {
1261 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1262 }
1263 return new URLRequestTestJob(request,
1264 network_delegate,
1265 redirect_headers_,
1266 redirect_data_,
1267 true);
1268 }
1269
1270 URLRequestJob* MaybeInterceptResponse(
1271 URLRequest* request,
1272 NetworkDelegate* network_delegate) const override {
1273 if (cancel_final_request_) {
1274 cancel_final_request_ = false;
1275 did_cancel_final_ = true;
1276 return new CancelTestJob(request, network_delegate);
1277 }
1278 if (!intercept_final_response_)
1279 return nullptr;
1280 intercept_final_response_ = false;
1281 did_intercept_final_ = true;
1282 if (use_url_request_http_job_) {
1283 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1284 }
1285 return new URLRequestTestJob(request,
1286 network_delegate,
1287 final_headers_,
1288 final_data_,
1289 true);
1290 }
1291
1292 void set_intercept_main_request(bool intercept_main_request) {
1293 intercept_main_request_ = intercept_main_request;
1294 }
1295
1296 void set_main_headers(const std::string& main_headers) {
1297 main_headers_ = main_headers;
1298 }
1299
1300 void set_main_data(const std::string& main_data) {
1301 main_data_ = main_data;
1302 }
1303
1304 void set_main_request_load_timing_info(
1305 const LoadTimingInfo& main_request_load_timing_info) {
1306 main_request_load_timing_info_ = main_request_load_timing_info;
1307 }
1308
1309 void set_restart_main_request(bool restart_main_request) {
1310 restart_main_request_ = restart_main_request;
1311 }
1312
1313 void set_cancel_main_request(bool cancel_main_request) {
1314 cancel_main_request_ = cancel_main_request;
1315 }
1316
1317 void set_cancel_then_restart_main_request(
1318 bool cancel_then_restart_main_request) {
1319 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1320 }
1321
1322 void set_simulate_main_network_error(bool simulate_main_network_error) {
1323 simulate_main_network_error_ = simulate_main_network_error;
1324 }
1325
1326 void set_intercept_redirect(bool intercept_redirect) {
1327 intercept_redirect_ = intercept_redirect;
1328 }
1329
1330 void set_redirect_headers(const std::string& redirect_headers) {
1331 redirect_headers_ = redirect_headers;
1332 }
1333
1334 void set_redirect_data(const std::string& redirect_data) {
1335 redirect_data_ = redirect_data;
1336 }
1337
1338 void set_cancel_redirect_request(bool cancel_redirect_request) {
1339 cancel_redirect_request_ = cancel_redirect_request;
1340 }
1341
1342 void set_intercept_final_response(bool intercept_final_response) {
1343 intercept_final_response_ = intercept_final_response;
1344 }
1345
1346 void set_final_headers(const std::string& final_headers) {
1347 final_headers_ = final_headers;
1348 }
1349
1350 void set_final_data(const std::string& final_data) {
1351 final_data_ = final_data;
1352 }
1353
1354 void set_cancel_final_request(bool cancel_final_request) {
1355 cancel_final_request_ = cancel_final_request;
1356 }
1357
1358 void set_use_url_request_http_job(bool use_url_request_http_job) {
1359 use_url_request_http_job_ = use_url_request_http_job;
1360 }
1361
1362 bool did_intercept_main() const {
1363 return did_intercept_main_;
1364 }
1365
1366 bool did_restart_main() const {
1367 return did_restart_main_;
1368 }
1369
1370 bool did_cancel_main() const {
1371 return did_cancel_main_;
1372 }
1373
1374 bool did_cancel_then_restart_main() const {
1375 return did_cancel_then_restart_main_;
1376 }
1377
1378 bool did_simulate_error_main() const {
1379 return did_simulate_error_main_;
1380 }
1381
1382 bool did_intercept_redirect() const {
1383 return did_intercept_redirect_;
1384 }
1385
1386 bool did_cancel_redirect() const {
1387 return did_cancel_redirect_;
1388 }
1389
1390 bool did_intercept_final() const {
1391 return did_intercept_final_;
1392 }
1393
1394 bool did_cancel_final() const {
1395 return did_cancel_final_;
1396 }
1397
1398 private:
1399 // Indicate whether to intercept the main request, and if so specify the
1400 // response to return and the LoadTimingInfo to use.
1401 mutable bool intercept_main_request_;
1402 mutable std::string main_headers_;
1403 mutable std::string main_data_;
1404 mutable LoadTimingInfo main_request_load_timing_info_;
1405
1406 // These indicate actions that can be taken within MaybeInterceptRequest.
1407 mutable bool restart_main_request_;
1408 mutable bool cancel_main_request_;
1409 mutable bool cancel_then_restart_main_request_;
1410 mutable bool simulate_main_network_error_;
1411
1412 // Indicate whether to intercept redirects, and if so specify the response to
1413 // return.
1414 mutable bool intercept_redirect_;
1415 mutable std::string redirect_headers_;
1416 mutable std::string redirect_data_;
1417
1418 // Cancel the request within MaybeInterceptRedirect.
1419 mutable bool cancel_redirect_request_;
1420
1421 // Indicate whether to intercept the final response, and if so specify the
1422 // response to return.
1423 mutable bool intercept_final_response_;
1424 mutable std::string final_headers_;
1425 mutable std::string final_data_;
1426
1427 // Cancel the final request within MaybeInterceptResponse.
1428 mutable bool cancel_final_request_;
1429
1430 // Instruct the interceptor to use a real URLRequestHTTPJob.
1431 mutable bool use_url_request_http_job_;
1432
1433 // These indicate if the interceptor did something or not.
1434 mutable bool did_intercept_main_;
1435 mutable bool did_restart_main_;
1436 mutable bool did_cancel_main_;
1437 mutable bool did_cancel_then_restart_main_;
1438 mutable bool did_simulate_error_main_;
1439 mutable bool did_intercept_redirect_;
1440 mutable bool did_cancel_redirect_;
1441 mutable bool did_intercept_final_;
1442 mutable bool did_cancel_final_;
1443};
1444
1445// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1446class URLRequestInterceptorTest : public URLRequestTest {
1447 public:
1448 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1449 }
1450
1451 ~URLRequestInterceptorTest() override {
1452 // URLRequestJobs may post clean-up tasks on destruction.
1453 base::RunLoop().RunUntilIdle();
1454 }
1455
1456 void SetUpFactory() override {
1457 interceptor_ = new MockURLRequestInterceptor();
1458 job_factory_.reset(new URLRequestInterceptingJobFactory(
1459 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1460 }
1461
1462 MockURLRequestInterceptor* interceptor() const {
1463 return interceptor_;
1464 }
1465
1466 private:
1467 MockURLRequestInterceptor* interceptor_;
1468};
1469
1470TEST_F(URLRequestInterceptorTest, Intercept) {
1471 // Intercept the main request and respond with a simple response.
1472 interceptor()->set_intercept_main_request(true);
1473 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1474 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591475 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501476 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1477 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1478 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1479 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1480 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1481 req->SetUserData(nullptr, user_data0);
1482 req->SetUserData(&user_data1, user_data1);
1483 req->SetUserData(&user_data2, user_data2);
1484 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191485 req->Start();
[email protected]255620da2013-08-19 13:14:291486 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591487
bengr1bf8e942014-11-07 01:36:501488 // Make sure we can retrieve our specific user data.
1489 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1490 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1491 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591492
bengr1bf8e942014-11-07 01:36:501493 // Check that we got one good response.
1494 EXPECT_TRUE(req->status().is_success());
1495 EXPECT_EQ(200, req->response_headers()->response_code());
1496 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1497 EXPECT_EQ(1, d.response_started_count());
1498 EXPECT_EQ(0, d.received_redirect_count());
1499}
[email protected]2bba3252013-04-08 19:50:591500
bengr1bf8e942014-11-07 01:36:501501TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1502 // Intercept the main request and respond with a redirect.
1503 interceptor()->set_intercept_main_request(true);
1504 interceptor()->set_main_headers(
1505 MockURLRequestInterceptor::redirect_headers());
1506 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1507
1508 // Intercept that redirect and respond with a final OK response.
1509 interceptor()->set_intercept_redirect(true);
1510 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1511 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1512
1513 TestDelegate d;
1514 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1515 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1516 req->set_method("GET");
1517 req->Start();
1518 base::RunLoop().Run();
1519
1520 // Check that the interceptor got called as expected.
1521 EXPECT_TRUE(interceptor()->did_intercept_main());
1522 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1523
1524 // Check that we got one good response.
1525 EXPECT_TRUE(req->status().is_success());
1526 if (req->status().is_success())
1527 EXPECT_EQ(200, req->response_headers()->response_code());
1528
1529 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1530 EXPECT_EQ(1, d.response_started_count());
1531 EXPECT_EQ(0, d.received_redirect_count());
1532}
1533
1534TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1535 // Intercept the main request to generate a server error response.
1536 interceptor()->set_intercept_main_request(true);
1537 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1538 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1539
1540 // Intercept that error and respond with an OK response.
1541 interceptor()->set_intercept_final_response(true);
1542 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1543 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1544
1545 TestDelegate d;
1546 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1547 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1548 req->set_method("GET");
1549 req->Start();
1550 base::RunLoop().Run();
1551
1552 // Check that the interceptor got called as expected.
1553 EXPECT_TRUE(interceptor()->did_intercept_main());
1554 EXPECT_TRUE(interceptor()->did_intercept_final());
1555
1556 // Check that we got one good response.
1557 EXPECT_TRUE(req->status().is_success());
1558 EXPECT_EQ(200, req->response_headers()->response_code());
1559 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1560 EXPECT_EQ(1, d.response_started_count());
1561 EXPECT_EQ(0, d.received_redirect_count());
1562}
1563
1564TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1565 // Intercept the main request to simulate a network error.
1566 interceptor()->set_simulate_main_network_error(true);
1567
1568 // Intercept that error and respond with an OK response.
1569 interceptor()->set_intercept_final_response(true);
1570 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1571 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1572
1573 TestDelegate d;
1574 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1575 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1576 req->set_method("GET");
1577 req->Start();
1578 base::RunLoop().Run();
1579
1580 // Check that the interceptor got called as expected.
1581 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1582 EXPECT_TRUE(interceptor()->did_intercept_final());
1583
1584 // Check that we received one good response.
1585 EXPECT_TRUE(req->status().is_success());
1586 EXPECT_EQ(200, req->response_headers()->response_code());
1587 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1588 EXPECT_EQ(1, d.response_started_count());
1589 EXPECT_EQ(0, d.received_redirect_count());
1590}
1591
1592TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1593 // Restart the main request.
1594 interceptor()->set_restart_main_request(true);
1595
1596 // then intercept the new main request and respond with an OK response
1597 interceptor()->set_intercept_main_request(true);
1598 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1599 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1600
1601 TestDelegate d;
1602 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1603 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1604 req->set_method("GET");
1605 req->Start();
1606 base::RunLoop().Run();
1607
1608 // Check that the interceptor got called as expected.
1609 EXPECT_TRUE(interceptor()->did_restart_main());
1610 EXPECT_TRUE(interceptor()->did_intercept_main());
1611
1612 // Check that we received one good response.
1613 EXPECT_TRUE(req->status().is_success());
1614 if (req->status().is_success())
1615 EXPECT_EQ(200, req->response_headers()->response_code());
1616
1617 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1618 EXPECT_EQ(1, d.response_started_count());
1619 EXPECT_EQ(0, d.received_redirect_count());
1620}
1621
1622TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1623 // Intercept the main request and cancel from within the restarted job.
1624 interceptor()->set_cancel_main_request(true);
1625
1626 // Set up to intercept the final response and override it with an OK response.
1627 interceptor()->set_intercept_final_response(true);
1628 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1629 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1630
1631 TestDelegate d;
1632 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1633 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1634 req->set_method("GET");
1635 req->Start();
1636 base::RunLoop().Run();
1637
1638 // Check that the interceptor got called as expected.
1639 EXPECT_TRUE(interceptor()->did_cancel_main());
1640 EXPECT_FALSE(interceptor()->did_intercept_final());
1641
1642 // Check that we see a canceled request.
1643 EXPECT_FALSE(req->status().is_success());
1644 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1645}
1646
1647TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1648 // Intercept the main request and respond with a redirect.
1649 interceptor()->set_intercept_main_request(true);
1650 interceptor()->set_main_headers(
1651 MockURLRequestInterceptor::redirect_headers());
1652 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1653
1654 // Intercept the redirect and cancel from within that job.
1655 interceptor()->set_cancel_redirect_request(true);
1656
1657 // Set up to intercept the final response and override it with an OK response.
1658 interceptor()->set_intercept_final_response(true);
1659 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1660 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1661
1662 TestDelegate d;
1663 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1664 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1665 req->set_method("GET");
1666 req->Start();
1667 base::RunLoop().Run();
1668
1669 // Check that the interceptor got called as expected.
1670 EXPECT_TRUE(interceptor()->did_intercept_main());
1671 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1672 EXPECT_FALSE(interceptor()->did_intercept_final());
1673
1674 // Check that we see a canceled request.
1675 EXPECT_FALSE(req->status().is_success());
1676 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1677}
1678
1679TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1680 // Intercept the main request to simulate a network error.
1681 interceptor()->set_simulate_main_network_error(true);
1682
1683 // Set up to intercept final the response and cancel from within that job.
1684 interceptor()->set_cancel_final_request(true);
1685
1686 TestDelegate d;
1687 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1688 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1689 req->set_method("GET");
1690 req->Start();
1691 base::RunLoop().Run();
1692
1693 // Check that the interceptor got called as expected.
1694 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1695 EXPECT_TRUE(interceptor()->did_cancel_final());
1696
1697 // Check that we see a canceled request.
1698 EXPECT_FALSE(req->status().is_success());
1699 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1700}
1701
1702TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1703 // Intercept the main request and cancel then restart from within that job.
1704 interceptor()->set_cancel_then_restart_main_request(true);
1705
1706 // Set up to intercept the final response and override it with an OK response.
1707 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501708 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1709 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501710
1711 TestDelegate d;
1712 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1713 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1714 req->set_method("GET");
1715 req->Start();
1716 base::RunLoop().Run();
1717
1718 // Check that the interceptor got called as expected.
1719 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1720 EXPECT_FALSE(interceptor()->did_intercept_final());
1721
1722 // Check that we see a canceled request.
1723 EXPECT_FALSE(req->status().is_success());
1724 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591725}
1726
1727// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1728// reused. |connect_time_flags| is used to indicate if there should be dns
1729// or SSL times, and |used_proxy| is used for proxy times.
1730LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1731 int connect_time_flags,
1732 bool used_proxy) {
1733 LoadTimingInfo load_timing;
1734 load_timing.socket_log_id = 1;
1735
1736 if (used_proxy) {
1737 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1738 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1739 }
1740
1741 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1742 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1743 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1744 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1745 }
1746 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1747 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1748 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1749 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1750 }
1751 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1752
1753 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1754 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1755 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1756 return load_timing;
1757}
1758
1759// Same as above, but in the case of a reused socket.
1760LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1761 bool used_proxy) {
1762 LoadTimingInfo load_timing;
1763 load_timing.socket_log_id = 1;
1764 load_timing.socket_reused = true;
1765
1766 if (used_proxy) {
1767 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1768 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1769 }
1770
1771 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1772 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1773 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1774 return load_timing;
1775}
1776
bengr1bf8e942014-11-07 01:36:501777LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1778 const LoadTimingInfo& job_load_timing,
1779 const URLRequestContext& context,
1780 MockURLRequestInterceptor* interceptor) {
1781 interceptor->set_intercept_main_request(true);
1782 interceptor->set_main_request_load_timing_info(job_load_timing);
1783 TestDelegate d;
1784 scoped_ptr<URLRequest> req(context.CreateRequest(
1785 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1786 req->Start();
1787 base::RunLoop().Run();
1788
1789 LoadTimingInfo resulting_load_timing;
1790 req->GetLoadTimingInfo(&resulting_load_timing);
1791
1792 // None of these should be modified by the URLRequest.
1793 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1794 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1795 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1796 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1797 EXPECT_EQ(job_load_timing.receive_headers_end,
1798 resulting_load_timing.receive_headers_end);
1799
1800 return resulting_load_timing;
1801}
1802
[email protected]2bba3252013-04-08 19:50:591803// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501804TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591805 base::TimeTicks now = base::TimeTicks::Now();
1806 LoadTimingInfo job_load_timing =
1807 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1808
[email protected]2ca01e52013-10-31 22:05:191809 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501810 RunURLRequestInterceptorLoadTimingTest(
1811 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591812
1813 // Nothing should have been changed by the URLRequest.
1814 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1815 load_timing_result.proxy_resolve_start);
1816 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1817 load_timing_result.proxy_resolve_end);
1818 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1819 load_timing_result.connect_timing.dns_start);
1820 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1821 load_timing_result.connect_timing.dns_end);
1822 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1823 load_timing_result.connect_timing.connect_start);
1824 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1825 load_timing_result.connect_timing.connect_end);
1826 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1827 load_timing_result.connect_timing.ssl_start);
1828 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1829 load_timing_result.connect_timing.ssl_end);
1830
1831 // Redundant sanity check.
1832 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1833}
1834
1835// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501836TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591837 base::TimeTicks now = base::TimeTicks::Now();
1838 LoadTimingInfo job_load_timing =
1839 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1840
[email protected]2ca01e52013-10-31 22:05:191841 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501842 RunURLRequestInterceptorLoadTimingTest(
1843 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591844
1845 // Nothing should have been changed by the URLRequest.
1846 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1847 load_timing_result.proxy_resolve_start);
1848 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1849 load_timing_result.proxy_resolve_end);
1850 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1851 load_timing_result.connect_timing.dns_start);
1852 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1853 load_timing_result.connect_timing.dns_end);
1854 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1855 load_timing_result.connect_timing.connect_start);
1856 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1857 load_timing_result.connect_timing.connect_end);
1858 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1859 load_timing_result.connect_timing.ssl_start);
1860 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1861 load_timing_result.connect_timing.ssl_end);
1862
1863 // Redundant sanity check.
1864 TestLoadTimingNotReusedWithProxy(load_timing_result,
1865 CONNECT_TIMING_HAS_SSL_TIMES);
1866}
1867
1868// Make sure that URLRequest correctly adjusts proxy times when they're before
1869// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101870// the case of reusing a SPDY session. The connected socket is not considered
1871// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591872//
1873// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501874TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591875 base::TimeTicks now = base::TimeTicks::Now();
1876 LoadTimingInfo job_load_timing =
1877 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1878 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1879 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1880 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1881 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1882 job_load_timing.connect_timing.connect_start =
1883 now - base::TimeDelta::FromDays(2);
1884 job_load_timing.connect_timing.connect_end =
1885 now - base::TimeDelta::FromDays(1);
1886
[email protected]2ca01e52013-10-31 22:05:191887 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501888 RunURLRequestInterceptorLoadTimingTest(
1889 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591890
1891 // Proxy times, connect times, and DNS times should all be replaced with
1892 // request_start.
1893 EXPECT_EQ(load_timing_result.request_start,
1894 load_timing_result.proxy_resolve_start);
1895 EXPECT_EQ(load_timing_result.request_start,
1896 load_timing_result.proxy_resolve_end);
1897 EXPECT_EQ(load_timing_result.request_start,
1898 load_timing_result.connect_timing.dns_start);
1899 EXPECT_EQ(load_timing_result.request_start,
1900 load_timing_result.connect_timing.dns_end);
1901 EXPECT_EQ(load_timing_result.request_start,
1902 load_timing_result.connect_timing.connect_start);
1903 EXPECT_EQ(load_timing_result.request_start,
1904 load_timing_result.connect_timing.connect_end);
1905
1906 // Other times should have been left null.
1907 TestLoadTimingNotReusedWithProxy(load_timing_result,
1908 CONNECT_TIMING_HAS_DNS_TIMES);
1909}
1910
1911// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501912TEST_F(URLRequestInterceptorTest,
1913 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591914 base::TimeTicks now = base::TimeTicks::Now();
1915 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1916 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1917 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1918
[email protected]2ca01e52013-10-31 22:05:191919 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501920 RunURLRequestInterceptorLoadTimingTest(
1921 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591922
1923 // Proxy times and connect times should all be replaced with request_start.
1924 EXPECT_EQ(load_timing_result.request_start,
1925 load_timing_result.proxy_resolve_start);
1926 EXPECT_EQ(load_timing_result.request_start,
1927 load_timing_result.proxy_resolve_end);
1928
1929 // Other times should have been left null.
1930 TestLoadTimingReusedWithProxy(load_timing_result);
1931}
1932
1933// Make sure that URLRequest correctly adjusts connect times when they're before
1934// |request_start|, due to reusing a connected socket. The connected socket is
1935// not considered reused in this test (May be a preconnect).
1936//
1937// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501938TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591939 base::TimeTicks now = base::TimeTicks::Now();
1940 LoadTimingInfo job_load_timing =
1941 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1942 job_load_timing.connect_timing.connect_start =
1943 now - base::TimeDelta::FromDays(1);
1944 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1945 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1946 job_load_timing.connect_timing.connect_end =
1947 now - base::TimeDelta::FromDays(4);
1948
[email protected]2ca01e52013-10-31 22:05:191949 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501950 RunURLRequestInterceptorLoadTimingTest(
1951 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591952
1953 // Connect times, and SSL times should be replaced with request_start.
1954 EXPECT_EQ(load_timing_result.request_start,
1955 load_timing_result.connect_timing.connect_start);
1956 EXPECT_EQ(load_timing_result.request_start,
1957 load_timing_result.connect_timing.ssl_start);
1958 EXPECT_EQ(load_timing_result.request_start,
1959 load_timing_result.connect_timing.ssl_end);
1960 EXPECT_EQ(load_timing_result.request_start,
1961 load_timing_result.connect_timing.connect_end);
1962
1963 // Other times should have been left null.
1964 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1965}
1966
1967// Make sure that URLRequest correctly adjusts connect times when they're before
1968// |request_start|, due to reusing a connected socket in the case that there
1969// are also proxy times. The connected socket is not considered reused in this
1970// test (May be a preconnect).
1971//
1972// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501973TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591974 base::TimeTicks now = base::TimeTicks::Now();
1975 LoadTimingInfo job_load_timing =
1976 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1977 job_load_timing.connect_timing.connect_start =
1978 now - base::TimeDelta::FromDays(1);
1979 job_load_timing.connect_timing.connect_end =
1980 now - base::TimeDelta::FromDays(2);
1981
[email protected]2ca01e52013-10-31 22:05:191982 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501983 RunURLRequestInterceptorLoadTimingTest(
1984 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591985
1986 // Connect times should be replaced with proxy_resolve_end.
1987 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1988 load_timing_result.connect_timing.connect_start);
1989 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1990 load_timing_result.connect_timing.connect_end);
1991
1992 // Other times should have been left null.
1993 TestLoadTimingNotReusedWithProxy(load_timing_result,
1994 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1995}
1996
[email protected]316c1e5e2012-09-12 15:17:441997// Check that two different URL requests have different identifiers.
1998TEST_F(URLRequestTest, Identifiers) {
1999 TestDelegate d;
2000 TestURLRequestContext context;
mmenke19378d22014-09-09 04:12:592001 scoped_ptr<URLRequest> req(context.CreateRequest(
2002 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2003 scoped_ptr<URLRequest> other_req(context.CreateRequest(
2004 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:442005
mmenke19378d22014-09-09 04:12:592006 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442007}
2008
2009// Check that a failure to connect to the proxy is reported to the network
2010// delegate.
2011TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2012 MockHostResolver host_resolver;
2013 host_resolver.rules()->AddSimulatedFailure("*");
2014
[email protected]ceefd7fd2012-11-29 00:36:242015 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442016 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2017
2018 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192019 scoped_ptr<URLRequest> req(context.CreateRequest(
2020 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2021 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442022
[email protected]f7022f32014-08-21 16:32:192023 req->Start();
[email protected]255620da2013-08-19 13:14:292024 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442025
2026 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192027 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152028 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192029 EXPECT_TRUE(req->proxy_server().IsEmpty());
2030 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2031 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442032
2033 EXPECT_EQ(1, network_delegate.error_count());
2034 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2035 EXPECT_EQ(1, network_delegate.completed_requests());
2036}
2037
[email protected]cba24642014-08-15 20:49:592038// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442039// content is empty.
2040TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2041 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192042 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2043 GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
2044 req->Start();
[email protected]255620da2013-08-19 13:14:292045 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442046 EXPECT_EQ("", d.data_received());
2047 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2048}
2049
[email protected]5033ab82013-03-22 20:17:462050// Make sure that SetPriority actually sets the URLRequest's priority
2051// correctly, both before and after start.
2052TEST_F(URLRequestTest, SetPriorityBasic) {
2053 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192054 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2055 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2056 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462057
[email protected]f7022f32014-08-21 16:32:192058 req->SetPriority(LOW);
2059 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462060
[email protected]f7022f32014-08-21 16:32:192061 req->Start();
2062 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462063
[email protected]f7022f32014-08-21 16:32:192064 req->SetPriority(MEDIUM);
2065 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462066}
2067
2068// Make sure that URLRequest calls SetPriority on a job before calling
2069// Start on it.
2070TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2071 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192072 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2073 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2074 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462075
2076 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192077 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502078 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462079 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2080
[email protected]f7022f32014-08-21 16:32:192081 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462082
[email protected]f7022f32014-08-21 16:32:192083 req->Start();
[email protected]5033ab82013-03-22 20:17:462084 EXPECT_EQ(LOW, job->priority());
2085}
2086
2087// Make sure that URLRequest passes on its priority updates to its
2088// job.
2089TEST_F(URLRequestTest, SetJobPriority) {
2090 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192091 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2092 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5033ab82013-03-22 20:17:462093
2094 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192095 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502096 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462097
[email protected]f7022f32014-08-21 16:32:192098 req->SetPriority(LOW);
2099 req->Start();
[email protected]5033ab82013-03-22 20:17:462100 EXPECT_EQ(LOW, job->priority());
2101
[email protected]f7022f32014-08-21 16:32:192102 req->SetPriority(MEDIUM);
2103 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462104 EXPECT_EQ(MEDIUM, job->priority());
2105}
2106
[email protected]bb1c4662013-11-14 00:00:072107// Setting the IGNORE_LIMITS load flag should be okay if the priority
2108// is MAXIMUM_PRIORITY.
2109TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2110 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192111 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2112 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
2113 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072114
2115 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192116 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072117 AddTestInterceptor()->set_main_intercept_job(job.get());
2118
[email protected]f7022f32014-08-21 16:32:192119 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2120 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072121
[email protected]f7022f32014-08-21 16:32:192122 req->SetPriority(MAXIMUM_PRIORITY);
2123 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072124
[email protected]f7022f32014-08-21 16:32:192125 req->Start();
2126 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072127 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2128}
2129
[email protected]ce7d0cbc2013-05-03 18:57:222130// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442131#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:222132// A subclass of SpawnedTestServer that uses a statically-configured hostname.
2133// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:442134// http://crbug.com/114369
[email protected]cd6f2522014-01-16 18:27:352135// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
[email protected]ce7d0cbc2013-05-03 18:57:222136class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442137 public:
[email protected]6cdfd7f2013-02-08 20:40:152138 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222139 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2140 ScopedCustomUrlRequestTestHttpHost::value(),
2141 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442142 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222143 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2144 ScopedCustomUrlRequestTestHttpHost::value(),
2145 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442146};
2147
[email protected]f2f31b32013-01-16 23:24:092148TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442149 LocalHttpTestServer test_server;
2150 ASSERT_TRUE(test_server.Start());
2151
2152 TestURLRequestContext context;
2153 scoped_refptr<DelayedCookieMonster> delayed_cm =
2154 new DelayedCookieMonster();
2155 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502156 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442157
2158 // Set up a cookie.
2159 {
2160 TestNetworkDelegate network_delegate;
2161 context.set_network_delegate(&network_delegate);
2162 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192163 scoped_ptr<URLRequest> req(context.CreateRequest(
2164 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2165 &d, NULL));
2166 req->Start();
[email protected]255620da2013-08-19 13:14:292167 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442168 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2169 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2170 EXPECT_EQ(1, network_delegate.set_cookie_count());
2171 }
2172
2173 // Verify that the cookie is set.
2174 {
2175 TestNetworkDelegate network_delegate;
2176 context.set_network_delegate(&network_delegate);
2177 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192178 scoped_ptr<URLRequest> req(context.CreateRequest(
2179 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2180 req->Start();
[email protected]255620da2013-08-19 13:14:292181 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442182
2183 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2184 != std::string::npos);
2185 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2186 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2187 }
2188}
2189
[email protected]f2f31b32013-01-16 23:24:092190TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442191 LocalHttpTestServer test_server;
2192 ASSERT_TRUE(test_server.Start());
2193
2194 // Set up a cookie.
2195 {
2196 TestNetworkDelegate network_delegate;
2197 default_context_.set_network_delegate(&network_delegate);
2198 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192199 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2200 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2201 &d, NULL));
2202 req->Start();
[email protected]255620da2013-08-19 13:14:292203 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442204 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2205 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2206 }
2207
2208 // Verify that the cookie is set.
2209 {
2210 TestNetworkDelegate network_delegate;
2211 default_context_.set_network_delegate(&network_delegate);
2212 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2215 req->Start();
[email protected]255620da2013-08-19 13:14:292216 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442217
2218 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2219 != std::string::npos);
2220 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2221 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2222 }
2223
2224 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2225 {
2226 TestNetworkDelegate network_delegate;
2227 default_context_.set_network_delegate(&network_delegate);
2228 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192229 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2230 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2231 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2232 req->Start();
[email protected]255620da2013-08-19 13:14:292233 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442234
2235 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2236 == std::string::npos);
2237
2238 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2239 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2240 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2241 }
2242}
2243
2244TEST_F(URLRequestTest, DoNotSaveCookies) {
2245 LocalHttpTestServer test_server;
2246 ASSERT_TRUE(test_server.Start());
2247
2248 // Set up a cookie.
2249 {
2250 TestNetworkDelegate network_delegate;
2251 default_context_.set_network_delegate(&network_delegate);
2252 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192253 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2254 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2255 &d, NULL));
2256 req->Start();
[email protected]255620da2013-08-19 13:14:292257 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442258
2259 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2260 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2261 EXPECT_EQ(1, network_delegate.set_cookie_count());
2262 }
2263
2264 // Try to set-up another cookie and update the previous cookie.
2265 {
2266 TestNetworkDelegate network_delegate;
2267 default_context_.set_network_delegate(&network_delegate);
2268 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192269 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442270 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192271 DEFAULT_PRIORITY, &d, NULL));
2272 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2273 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442274
[email protected]255620da2013-08-19 13:14:292275 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442276
2277 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2280 EXPECT_EQ(0, network_delegate.set_cookie_count());
2281 }
2282
2283 // Verify the cookies weren't saved or updated.
2284 {
2285 TestNetworkDelegate network_delegate;
2286 default_context_.set_network_delegate(&network_delegate);
2287 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192288 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2289 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2290 req->Start();
[email protected]255620da2013-08-19 13:14:292291 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442292
2293 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2294 == std::string::npos);
2295 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2296 != std::string::npos);
2297
2298 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2299 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2300 EXPECT_EQ(0, network_delegate.set_cookie_count());
2301 }
2302}
2303
2304TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2305 LocalHttpTestServer test_server;
2306 ASSERT_TRUE(test_server.Start());
2307
2308 // Set up a cookie.
2309 {
2310 TestNetworkDelegate network_delegate;
2311 default_context_.set_network_delegate(&network_delegate);
2312 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192313 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2314 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2315 &d, NULL));
2316 req->Start();
[email protected]255620da2013-08-19 13:14:292317 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442318
2319 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2320 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2321 }
2322
2323 // Verify that the cookie is set.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192328 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2329 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2330 req->Start();
[email protected]255620da2013-08-19 13:14:292331 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442332
2333 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2334 != std::string::npos);
2335
2336 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 isn't sent.
2341 {
2342 TestNetworkDelegate network_delegate;
2343 default_context_.set_network_delegate(&network_delegate);
2344 TestDelegate d;
2345 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192346 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2347 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2348 req->Start();
[email protected]255620da2013-08-19 13:14:292349 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442350
2351 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2352 == std::string::npos);
2353
[email protected]22e045f2013-09-20 03:54:032354 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442355 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2356 }
2357}
2358
2359TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2360 LocalHttpTestServer test_server;
2361 ASSERT_TRUE(test_server.Start());
2362
2363 // Set up a cookie.
2364 {
2365 TestNetworkDelegate network_delegate;
2366 default_context_.set_network_delegate(&network_delegate);
2367 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192368 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2369 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2370 &d, NULL));
2371 req->Start();
[email protected]255620da2013-08-19 13:14:292372 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442373
2374 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2375 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2376 }
2377
2378 // Try to set-up another cookie and update the previous cookie.
2379 {
2380 TestNetworkDelegate network_delegate;
2381 default_context_.set_network_delegate(&network_delegate);
2382 TestDelegate d;
2383 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192384 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442385 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192386 DEFAULT_PRIORITY, &d, NULL));
2387 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442388
[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(2, network_delegate.blocked_set_cookie_count());
2393 }
2394
2395 // Verify the cookies weren't saved or updated.
2396 {
2397 TestNetworkDelegate network_delegate;
2398 default_context_.set_network_delegate(&network_delegate);
2399 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192400 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2401 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2402 req->Start();
[email protected]255620da2013-08-19 13:14:292403 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442404
2405 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2406 == std::string::npos);
2407 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2408 != std::string::npos);
2409
2410 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2411 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2412 }
2413}
2414
2415TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2416 LocalHttpTestServer test_server;
2417 ASSERT_TRUE(test_server.Start());
2418
2419 // Set up an empty cookie.
2420 {
2421 TestNetworkDelegate network_delegate;
2422 default_context_.set_network_delegate(&network_delegate);
2423 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192424 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2425 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2426 req->Start();
[email protected]255620da2013-08-19 13:14:292427 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442428
2429 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2430 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2431 EXPECT_EQ(0, network_delegate.set_cookie_count());
2432 }
2433}
2434
2435TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2436 LocalHttpTestServer test_server;
2437 ASSERT_TRUE(test_server.Start());
2438
2439 // Set up a cookie.
2440 {
2441 TestNetworkDelegate network_delegate;
2442 default_context_.set_network_delegate(&network_delegate);
2443 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192444 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2445 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2446 &d, NULL));
2447 req->Start();
[email protected]255620da2013-08-19 13:14:292448 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442449
2450 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2451 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2452 }
2453
2454 // Verify that the cookie is set.
2455 {
2456 TestNetworkDelegate network_delegate;
2457 default_context_.set_network_delegate(&network_delegate);
2458 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2460 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2461 req->Start();
[email protected]255620da2013-08-19 13:14:292462 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442463
2464 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2465 != std::string::npos);
2466
2467 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2468 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2469 }
2470
2471 // Verify that the cookie isn't sent.
2472 {
2473 TestNetworkDelegate network_delegate;
2474 default_context_.set_network_delegate(&network_delegate);
2475 TestDelegate d;
2476 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192477 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2478 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2479 req->Start();
[email protected]255620da2013-08-19 13:14:292480 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442481
2482 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2483 == std::string::npos);
2484
[email protected]22e045f2013-09-20 03:54:032485 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442486 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2487 }
2488}
2489
2490TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2491 LocalHttpTestServer test_server;
2492 ASSERT_TRUE(test_server.Start());
2493
2494 // Set up a cookie.
2495 {
2496 TestNetworkDelegate network_delegate;
2497 default_context_.set_network_delegate(&network_delegate);
2498 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192499 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2500 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2501 &d, NULL));
2502 req->Start();
[email protected]255620da2013-08-19 13:14:292503 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442504
2505 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2506 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2507 }
2508
2509 // Try to set-up another cookie and update the previous cookie.
2510 {
2511 TestNetworkDelegate network_delegate;
2512 default_context_.set_network_delegate(&network_delegate);
2513 TestDelegate d;
2514 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192515 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442516 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192517 DEFAULT_PRIORITY, &d, NULL));
2518 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442519
[email protected]255620da2013-08-19 13:14:292520 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442521
2522 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2523 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2524 }
2525
2526 // Verify the cookies weren't saved or updated.
2527 {
2528 TestNetworkDelegate network_delegate;
2529 default_context_.set_network_delegate(&network_delegate);
2530 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192531 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2532 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2533 req->Start();
[email protected]255620da2013-08-19 13:14:292534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442535
2536 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2537 == std::string::npos);
2538 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2539 != std::string::npos);
2540
2541 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2542 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2543 }
2544}
2545
[email protected]5095cd72012-11-01 10:29:162546// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2547// value for the |fixed_date| argument given to the constructor.
2548class FixedDateNetworkDelegate : public TestNetworkDelegate {
2549 public:
2550 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2551 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202552 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162553
[email protected]cba24642014-08-15 20:49:592554 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202555 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592556 URLRequest* request,
2557 const CompletionCallback& callback,
2558 const HttpResponseHeaders* original_response_headers,
2559 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132560 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162561
2562 private:
2563 std::string fixed_date_;
2564
2565 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2566};
2567
2568int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592569 URLRequest* request,
2570 const CompletionCallback& callback,
2571 const HttpResponseHeaders* original_response_headers,
2572 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162573 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592574 HttpResponseHeaders* new_response_headers =
2575 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162576
2577 new_response_headers->RemoveHeader("Date");
2578 new_response_headers->AddHeader("Date: " + fixed_date_);
2579
2580 *override_response_headers = new_response_headers;
2581 return TestNetworkDelegate::OnHeadersReceived(request,
2582 callback,
2583 original_response_headers,
[email protected]5f714132014-03-26 10:41:162584 override_response_headers,
2585 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162586}
2587
2588// Test that cookie expiration times are adjusted for server/client clock
2589// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2590// headers by defaulting to GMT. (crbug.com/135131)
2591TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2592 LocalHttpTestServer test_server;
2593 ASSERT_TRUE(test_server.Start());
2594
2595 // Set up an expired cookie.
2596 {
2597 TestNetworkDelegate network_delegate;
2598 default_context_.set_network_delegate(&network_delegate);
2599 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192600 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192601 test_server.GetURL(
2602 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
[email protected]f7022f32014-08-21 16:32:192603 DEFAULT_PRIORITY, &d, NULL));
2604 req->Start();
[email protected]255620da2013-08-19 13:14:292605 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162606 }
2607 // Verify that the cookie is not set.
2608 {
2609 TestNetworkDelegate network_delegate;
2610 default_context_.set_network_delegate(&network_delegate);
2611 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192612 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2613 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2614 req->Start();
[email protected]255620da2013-08-19 13:14:292615 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162616
2617 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2618 }
2619 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2620 {
2621 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2622 default_context_.set_network_delegate(&network_delegate);
2623 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192624 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192625 test_server.GetURL(
2626 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
[email protected]f7022f32014-08-21 16:32:192627 DEFAULT_PRIORITY, &d, NULL));
2628 req->Start();
[email protected]255620da2013-08-19 13:14:292629 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162630 }
2631 // Verify that the cookie is set.
2632 {
2633 TestNetworkDelegate network_delegate;
2634 default_context_.set_network_delegate(&network_delegate);
2635 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192636 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2637 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2638 req->Start();
[email protected]255620da2013-08-19 13:14:292639 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162640
2641 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2642 }
2643}
2644
2645
[email protected]316c1e5e2012-09-12 15:17:442646// Check that it is impossible to change the referrer in the extra headers of
2647// an URLRequest.
2648TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2649 LocalHttpTestServer test_server;
2650 ASSERT_TRUE(test_server.Start());
2651
2652 // If extra headers contain referer and the request contains a referer,
2653 // only the latter shall be respected.
2654 {
2655 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192656 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2657 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2658 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442659
2660 HttpRequestHeaders headers;
2661 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192662 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442663
[email protected]f7022f32014-08-21 16:32:192664 req->Start();
[email protected]255620da2013-08-19 13:14:292665 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442666
2667 EXPECT_EQ("http://foo.com/", d.data_received());
2668 }
2669
2670 // If extra headers contain a referer but the request does not, no referer
2671 // shall be sent in the header.
2672 {
2673 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192674 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2675 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:442676
2677 HttpRequestHeaders headers;
2678 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192679 req->SetExtraRequestHeaders(headers);
2680 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442681
[email protected]f7022f32014-08-21 16:32:192682 req->Start();
[email protected]255620da2013-08-19 13:14:292683 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442684
2685 EXPECT_EQ("None", d.data_received());
2686 }
2687}
2688
[email protected]b89290212009-08-14 22:37:352689class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112690 public:
2691 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152692 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112693 "net/data/url_request_unittest"))) {
2694 }
2695
[email protected]b89290212009-08-14 22:37:352696 protected:
[email protected]21184962011-10-26 00:50:302697 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2698 // |request_method| is the method to use for the initial request.
2699 // |redirect_method| is the method that is expected to be used for the second
2700 // request, after redirection.
2701 // If |include_data| is true, data is uploaded with the request. The
2702 // response body is expected to match it exactly, if and only if
2703 // |request_method| == |redirect_method|.
2704 void HTTPRedirectMethodTest(const GURL& redirect_url,
2705 const std::string& request_method,
2706 const std::string& redirect_method,
2707 bool include_data) {
2708 static const char kData[] = "hello world";
2709 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192710 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2711 redirect_url, DEFAULT_PRIORITY, &d, NULL));
2712 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302713 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072714 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302715 HttpRequestHeaders headers;
2716 headers.SetHeader(HttpRequestHeaders::kContentLength,
2717 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:192718 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302719 }
[email protected]f7022f32014-08-21 16:32:192720 req->Start();
[email protected]255620da2013-08-19 13:14:292721 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192722 EXPECT_EQ(redirect_method, req->method());
2723 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2724 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302725 if (include_data) {
2726 if (request_method == redirect_method) {
2727 EXPECT_EQ(kData, d.data_received());
2728 } else {
2729 EXPECT_NE(kData, d.data_received());
2730 }
2731 }
2732 if (HasFailure())
2733 LOG(WARNING) << "Request method was: " << request_method;
2734 }
2735
[email protected]762d2db2010-01-11 19:03:012736 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012737 const int kMsgSize = 20000; // multiple of 10
2738 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482739 char* uploadBytes = new char[kMsgSize+1];
2740 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012741 char marker = 'a';
2742 for (int idx = 0; idx < kMsgSize/10; idx++) {
2743 memcpy(ptr, "----------", 10);
2744 ptr += 10;
2745 if (idx % 100 == 0) {
2746 ptr--;
2747 *ptr++ = marker;
2748 if (++marker > 'z')
2749 marker = 'a';
2750 }
2751 }
2752 uploadBytes[kMsgSize] = '\0';
2753
[email protected]762d2db2010-01-11 19:03:012754 for (int i = 0; i < kIterations; ++i) {
2755 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192756 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2757 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
2758 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:012759
mmenkecbc2b712014-10-09 20:29:072760 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:012761
[email protected]f7022f32014-08-21 16:32:192762 r->Start();
2763 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:012764
[email protected]255620da2013-08-19 13:14:292765 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012766
[email protected]329b68b2012-11-14 17:54:272767 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:192768 << "request failed: " << r->status().status()
2769 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:012770
2771 EXPECT_FALSE(d.received_data_before_response());
2772 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012773 }
2774 delete[] uploadBytes;
2775 }
2776
[email protected]ef2bf422012-05-11 03:27:092777 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222778 r->AppendChunkToUpload("a", 1, false);
2779 r->AppendChunkToUpload("bcd", 3, false);
2780 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2781 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2782 r->AppendChunkToUpload("0", 1, false);
2783 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112784 }
2785
[email protected]ef2bf422012-05-11 03:27:092786 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112787 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272788 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112789 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2790
[email protected]329b68b2012-11-14 17:54:272791 ASSERT_EQ(1, d->response_started_count())
2792 << "request failed: " << r->status().status()
2793 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112794
2795 EXPECT_FALSE(d->received_data_before_response());
2796
[email protected]329b68b2012-11-14 17:54:272797 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2798 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112799 }
2800
[email protected]ede03212012-09-07 12:52:262801 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342802 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192803 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2804 test_server_.GetURL("set-many-cookies?" +
2805 base::IntToString(num_cookies)),
2806 DEFAULT_PRIORITY, &d, NULL));
[email protected]263163f2012-06-14 22:40:342807
[email protected]f7022f32014-08-21 16:32:192808 r->Start();
2809 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:342810
[email protected]255620da2013-08-19 13:14:292811 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342812
[email protected]f7022f32014-08-21 16:32:192813 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:342814
[email protected]ede03212012-09-07 12:52:262815 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:192816 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342817 // The test server appears to be unable to handle subsequent requests
2818 // after this error is triggered. Force it to restart.
2819 EXPECT_TRUE(test_server_.Stop());
2820 EXPECT_TRUE(test_server_.Start());
2821 }
2822
2823 return is_success;
2824 }
2825
bengr1bf8e942014-11-07 01:36:502826 LocalHttpTestServer* test_server() {
2827 return &test_server_;
2828 }
2829
2830 protected:
[email protected]1700c6a2012-02-22 18:07:072831 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352832};
2833
[email protected]95409e12010-08-17 20:07:112834// In this unit test, we're using the HTTPTestServer as a proxy server and
2835// issuing a CONNECT request with the magic host name "www.redirect.com".
2836// The HTTPTestServer will return a 302 response, which we should not
2837// follow.
[email protected]f2f31b32013-01-16 23:24:092838TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112839 ASSERT_TRUE(test_server_.Start());
2840
[email protected]ceefd7fd2012-11-29 00:36:242841 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042842 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192843 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502844
[email protected]d1ec59082009-02-11 02:48:152845 TestDelegate d;
2846 {
[email protected]f7022f32014-08-21 16:32:192847 scoped_ptr<URLRequest> r(context.CreateRequest(
2848 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2849 r->Start();
2850 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:152851
[email protected]255620da2013-08-19 13:14:292852 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152853
[email protected]f7022f32014-08-21 16:32:192854 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152855 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192856 EXPECT_TRUE(r->proxy_server().IsEmpty());
2857 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:082858 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152859 // We should not have followed the redirect.
2860 EXPECT_EQ(0, d.received_redirect_count());
2861 }
2862}
2863
[email protected]8202d0c2011-02-23 08:31:142864// This is the same as the previous test, but checks that the network delegate
2865// registers the error.
[email protected]c044616e2013-02-20 02:01:262866TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142867 ASSERT_TRUE(test_server_.Start());
2868
[email protected]ceefd7fd2012-11-29 00:36:242869 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042870 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192871 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502872
[email protected]8202d0c2011-02-23 08:31:142873 TestDelegate d;
2874 {
[email protected]f7022f32014-08-21 16:32:192875 scoped_ptr<URLRequest> r(context.CreateRequest(
2876 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2877 r->Start();
2878 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:142879
[email protected]255620da2013-08-19 13:14:292880 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142881
[email protected]f7022f32014-08-21 16:32:192882 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152883 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192884 EXPECT_TRUE(r->proxy_server().IsEmpty());
2885 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:142886 EXPECT_EQ(1, d.response_started_count());
2887 // We should not have followed the redirect.
2888 EXPECT_EQ(0, d.received_redirect_count());
2889
2890 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052891 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142892 }
2893}
2894
[email protected]dc5a5cf2012-09-26 02:49:302895// Tests that we can block and asynchronously return OK in various stages.
2896TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2897 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2898 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2899 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2900 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2901 };
2902 static const size_t blocking_stages_length = arraysize(blocking_stages);
2903
2904 ASSERT_TRUE(test_server_.Start());
2905
2906 TestDelegate d;
2907 BlockingNetworkDelegate network_delegate(
2908 BlockingNetworkDelegate::USER_CALLBACK);
2909 network_delegate.set_block_on(
2910 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2911 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2912 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2913
2914 TestURLRequestContext context(true);
2915 context.set_network_delegate(&network_delegate);
2916 context.Init();
2917
2918 {
[email protected]f7022f32014-08-21 16:32:192919 scoped_ptr<URLRequest> r(context.CreateRequest(
2920 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
[email protected]dc5a5cf2012-09-26 02:49:302921
[email protected]f7022f32014-08-21 16:32:192922 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:302923 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292924 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302925 EXPECT_EQ(blocking_stages[i],
2926 network_delegate.stage_blocked_for_callback());
2927 network_delegate.DoCallback(OK);
2928 }
[email protected]255620da2013-08-19 13:14:292929 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192930 EXPECT_EQ(200, r->GetResponseCode());
2931 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:302932 EXPECT_EQ(1, network_delegate.created_requests());
2933 EXPECT_EQ(0, network_delegate.destroyed_requests());
2934 }
2935 EXPECT_EQ(1, network_delegate.destroyed_requests());
2936}
2937
[email protected]4c76d7c2011-04-15 19:14:122938// Tests that the network delegate can block and cancel a request.
2939TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2940 ASSERT_TRUE(test_server_.Start());
2941
2942 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302943 BlockingNetworkDelegate network_delegate(
2944 BlockingNetworkDelegate::AUTO_CALLBACK);
2945 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2946 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122947
[email protected]d5a4dd62012-05-23 01:41:042948 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192949 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502950
[email protected]4c76d7c2011-04-15 19:14:122951 {
[email protected]f7022f32014-08-21 16:32:192952 scoped_ptr<URLRequest> r(context.CreateRequest(
2953 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]4c76d7c2011-04-15 19:14:122954
[email protected]f7022f32014-08-21 16:32:192955 r->Start();
[email protected]255620da2013-08-19 13:14:292956 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122957
[email protected]f7022f32014-08-21 16:32:192958 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152959 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:192960 EXPECT_TRUE(r->proxy_server().IsEmpty());
2961 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:122962 EXPECT_EQ(1, network_delegate.created_requests());
2963 EXPECT_EQ(0, network_delegate.destroyed_requests());
2964 }
2965 EXPECT_EQ(1, network_delegate.destroyed_requests());
2966}
2967
[email protected]b4438d32012-09-27 06:15:302968// Helper function for NetworkDelegateCancelRequestAsynchronously and
2969// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2970// delegate operating in |block_mode| and a request for |url|. It blocks the
2971// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2972void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2973 BlockingNetworkDelegate::Stage stage,
2974 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362975 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302976 BlockingNetworkDelegate network_delegate(block_mode);
2977 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2978 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362979
[email protected]b4438d32012-09-27 06:15:302980 TestURLRequestContext context(true);
2981 context.set_network_delegate(&network_delegate);
2982 context.Init();
[email protected]3cd384c602011-08-31 16:12:362983
2984 {
[email protected]f7022f32014-08-21 16:32:192985 scoped_ptr<URLRequest> r(context.CreateRequest(
2986 url, DEFAULT_PRIORITY, &d, NULL));
[email protected]3cd384c602011-08-31 16:12:362987
[email protected]f7022f32014-08-21 16:32:192988 r->Start();
[email protected]255620da2013-08-19 13:14:292989 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362990
[email protected]f7022f32014-08-21 16:32:192991 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152992 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:192993 EXPECT_TRUE(r->proxy_server().IsEmpty());
2994 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:362995 EXPECT_EQ(1, network_delegate.created_requests());
2996 EXPECT_EQ(0, network_delegate.destroyed_requests());
2997 }
2998 EXPECT_EQ(1, network_delegate.destroyed_requests());
2999}
3000
[email protected]b4438d32012-09-27 06:15:303001// The following 3 tests check that the network delegate can cancel a request
3002// synchronously in various stages of the request.
3003TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3004 ASSERT_TRUE(test_server_.Start());
3005 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3006 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453007 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303008}
3009
3010TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3011 ASSERT_TRUE(test_server_.Start());
3012 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3013 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453014 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303015}
3016
3017TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3018 ASSERT_TRUE(test_server_.Start());
3019 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3020 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453021 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303022}
3023
3024// The following 3 tests check that the network delegate can cancel a request
3025// asynchronously in various stages of the request.
3026TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3027 ASSERT_TRUE(test_server_.Start());
3028 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3029 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453030 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303031}
3032
3033TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3034 ASSERT_TRUE(test_server_.Start());
3035 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3036 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453037 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303038}
3039
3040TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3041 ASSERT_TRUE(test_server_.Start());
3042 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3043 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453044 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303045}
3046
[email protected]4c76d7c2011-04-15 19:14:123047// Tests that the network delegate can block and redirect a request to a new
3048// URL.
3049TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3050 ASSERT_TRUE(test_server_.Start());
3051
3052 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303053 BlockingNetworkDelegate network_delegate(
3054 BlockingNetworkDelegate::AUTO_CALLBACK);
3055 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123056 GURL redirect_url(test_server_.GetURL("simple.html"));
3057 network_delegate.set_redirect_url(redirect_url);
3058
[email protected]d5a4dd62012-05-23 01:41:043059 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193060 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503061
[email protected]4c76d7c2011-04-15 19:14:123062 {
[email protected]8f1ac082011-04-19 21:14:133063 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193064 scoped_ptr<URLRequest> r(context.CreateRequest(
3065 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]4c76d7c2011-04-15 19:14:123066
[email protected]6be6fa92014-08-06 23:44:563067 // Quit after hitting the redirect, so can check the headers.
3068 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193069 r->Start();
[email protected]255620da2013-08-19 13:14:293070 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123071
[email protected]6be6fa92014-08-06 23:44:563072 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193073 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3074 EXPECT_EQ(307, r->GetResponseCode());
3075 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563076 std::string location;
[email protected]f7022f32014-08-21 16:32:193077 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3078 &location));
[email protected]6be6fa92014-08-06 23:44:563079 EXPECT_EQ(redirect_url, GURL(location));
3080
3081 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193082 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563083 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193084 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3085 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273086 EXPECT_EQ(
3087 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3088 EXPECT_TRUE(
3089 network_delegate.last_observed_proxy().Equals(
3090 test_server_.host_port_pair()));
3091
[email protected]f7022f32014-08-21 16:32:193092 EXPECT_EQ(0, r->status().error());
3093 EXPECT_EQ(redirect_url, r->url());
3094 EXPECT_EQ(original_url, r->original_url());
3095 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123096 EXPECT_EQ(1, network_delegate.created_requests());
3097 EXPECT_EQ(0, network_delegate.destroyed_requests());
3098 }
3099 EXPECT_EQ(1, network_delegate.destroyed_requests());
3100}
3101
[email protected]b813ed72012-04-05 08:21:363102// Tests that the network delegate can block and redirect a request to a new
3103// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3104TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3105 ASSERT_TRUE(test_server_.Start());
3106
3107 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303108 BlockingNetworkDelegate network_delegate(
3109 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363110 GURL redirect_url(test_server_.GetURL("simple.html"));
3111 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363112
[email protected]d5a4dd62012-05-23 01:41:043113 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193114 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363115
3116 {
3117 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193118 scoped_ptr<URLRequest> r(context.CreateRequest(
3119 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]b813ed72012-04-05 08:21:363120
[email protected]6be6fa92014-08-06 23:44:563121 // Quit after hitting the redirect, so can check the headers.
3122 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193123 r->Start();
[email protected]255620da2013-08-19 13:14:293124 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363125
[email protected]6be6fa92014-08-06 23:44:563126 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193127 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3128 EXPECT_EQ(307, r->GetResponseCode());
3129 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563130 std::string location;
[email protected]f7022f32014-08-21 16:32:193131 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3132 &location));
[email protected]6be6fa92014-08-06 23:44:563133 EXPECT_EQ(redirect_url, GURL(location));
3134
3135 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193136 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563137 base::RunLoop().Run();
3138
[email protected]f7022f32014-08-21 16:32:193139 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3140 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273141 EXPECT_EQ(
3142 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3143 EXPECT_TRUE(
3144 network_delegate.last_observed_proxy().Equals(
3145 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193146 EXPECT_EQ(0, r->status().error());
3147 EXPECT_EQ(redirect_url, r->url());
3148 EXPECT_EQ(original_url, r->original_url());
3149 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363150 EXPECT_EQ(1, network_delegate.created_requests());
3151 EXPECT_EQ(0, network_delegate.destroyed_requests());
3152 }
3153 EXPECT_EQ(1, network_delegate.destroyed_requests());
3154}
3155
[email protected]3c5ca8c2011-09-29 01:14:513156// Tests that redirects caused by the network delegate preserve POST data.
3157TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3158 ASSERT_TRUE(test_server_.Start());
3159
3160 const char kData[] = "hello world";
3161
3162 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303163 BlockingNetworkDelegate network_delegate(
3164 BlockingNetworkDelegate::AUTO_CALLBACK);
3165 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513166 GURL redirect_url(test_server_.GetURL("echo"));
3167 network_delegate.set_redirect_url(redirect_url);
3168
[email protected]ef2bf422012-05-11 03:27:093169 TestURLRequestContext context(true);
3170 context.set_network_delegate(&network_delegate);
3171 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513172
3173 {
3174 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193175 scoped_ptr<URLRequest> r(context.CreateRequest(
3176 original_url, DEFAULT_PRIORITY, &d, NULL));
3177 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073178 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513179 HttpRequestHeaders headers;
3180 headers.SetHeader(HttpRequestHeaders::kContentLength,
3181 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193182 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563183
3184 // Quit after hitting the redirect, so can check the headers.
3185 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193186 r->Start();
[email protected]255620da2013-08-19 13:14:293187 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513188
[email protected]6be6fa92014-08-06 23:44:563189 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193190 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3191 EXPECT_EQ(307, r->GetResponseCode());
3192 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563193 std::string location;
[email protected]f7022f32014-08-21 16:32:193194 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3195 &location));
[email protected]6be6fa92014-08-06 23:44:563196 EXPECT_EQ(redirect_url, GURL(location));
3197
3198 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193199 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563200 base::RunLoop().Run();
3201
[email protected]f7022f32014-08-21 16:32:193202 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3203 EXPECT_EQ(0, r->status().error());
3204 EXPECT_EQ(redirect_url, r->url());
3205 EXPECT_EQ(original_url, r->original_url());
3206 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513207 EXPECT_EQ(1, network_delegate.created_requests());
3208 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193209 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513210 EXPECT_EQ(kData, d.data_received());
3211 }
3212 EXPECT_EQ(1, network_delegate.destroyed_requests());
3213}
3214
[email protected]5f714132014-03-26 10:41:163215// Tests that the network delegate can block and redirect a request to a new
3216// URL during OnHeadersReceived.
3217TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3218 ASSERT_TRUE(test_server_.Start());
3219
3220 TestDelegate d;
3221 BlockingNetworkDelegate network_delegate(
3222 BlockingNetworkDelegate::AUTO_CALLBACK);
3223 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3224 GURL redirect_url(test_server_.GetURL("simple.html"));
3225 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3226
3227 TestURLRequestContextWithProxy context(
3228 test_server_.host_port_pair().ToString(), &network_delegate);
3229
3230 {
3231 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193232 scoped_ptr<URLRequest> r(context.CreateRequest(
3233 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:163234
[email protected]f7022f32014-08-21 16:32:193235 r->Start();
[email protected]5f714132014-03-26 10:41:163236 base::RunLoop().Run();
3237
[email protected]f7022f32014-08-21 16:32:193238 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3239 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273240 EXPECT_EQ(
3241 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3242 EXPECT_TRUE(
3243 network_delegate.last_observed_proxy().Equals(
3244 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193245
3246 EXPECT_EQ(OK, r->status().error());
3247 EXPECT_EQ(redirect_url, r->url());
3248 EXPECT_EQ(original_url, r->original_url());
3249 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163250 EXPECT_EQ(2, network_delegate.created_requests());
3251 EXPECT_EQ(0, network_delegate.destroyed_requests());
3252 }
3253 EXPECT_EQ(1, network_delegate.destroyed_requests());
3254}
3255
[email protected]c2911d72011-10-03 22:16:363256// Tests that the network delegate can synchronously complete OnAuthRequired
3257// by taking no action. This indicates that the NetworkDelegate does not want to
3258// handle the challenge, and is passing the buck along to the
3259// URLRequest::Delegate.
3260TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3261 ASSERT_TRUE(test_server_.Start());
3262
3263 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303264 BlockingNetworkDelegate network_delegate(
3265 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363266
[email protected]ef2bf422012-05-11 03:27:093267 TestURLRequestContext context(true);
3268 context.set_network_delegate(&network_delegate);
3269 context.Init();
[email protected]c2911d72011-10-03 22:16:363270
[email protected]f3cf9802011-10-28 18:44:583271 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363272
3273 {
3274 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193275 scoped_ptr<URLRequest> r(context.CreateRequest(
3276 url, DEFAULT_PRIORITY, &d, NULL));
3277 r->Start();
[email protected]79e1fd62013-06-20 06:50:043278
[email protected]255620da2013-08-19 13:14:293279 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043280
[email protected]f7022f32014-08-21 16:32:193281 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3282 EXPECT_EQ(0, r->status().error());
3283 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043284 EXPECT_TRUE(d.auth_required_called());
3285 EXPECT_EQ(1, network_delegate.created_requests());
3286 EXPECT_EQ(0, network_delegate.destroyed_requests());
3287 }
3288 EXPECT_EQ(1, network_delegate.destroyed_requests());
3289}
3290
3291TEST_F(URLRequestTestHTTP,
3292 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3293 ASSERT_TRUE(test_server_.Start());
3294
3295 TestDelegate d;
3296 BlockingNetworkDelegate network_delegate(
3297 BlockingNetworkDelegate::SYNCHRONOUS);
3298
3299 TestURLRequestContext context(true);
3300 context.set_network_delegate(&network_delegate);
3301 context.Init();
3302
3303 d.set_credentials(AuthCredentials(kUser, kSecret));
3304
3305 {
3306 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193307 scoped_ptr<URLRequest> r(context.CreateRequest(
3308 url, DEFAULT_PRIORITY, &d, NULL));
3309 r->Start();
[email protected]79e1fd62013-06-20 06:50:043310
3311 {
3312 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193313 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043314 EXPECT_FALSE(headers.HasHeader("Authorization"));
3315 }
3316
[email protected]255620da2013-08-19 13:14:293317 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363318
[email protected]f7022f32014-08-21 16:32:193319 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3320 EXPECT_EQ(0, r->status().error());
3321 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363322 EXPECT_TRUE(d.auth_required_called());
3323 EXPECT_EQ(1, network_delegate.created_requests());
3324 EXPECT_EQ(0, network_delegate.destroyed_requests());
3325 }
3326 EXPECT_EQ(1, network_delegate.destroyed_requests());
3327}
3328
3329// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403330// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363331TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3332 ASSERT_TRUE(test_server_.Start());
3333
3334 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303335 BlockingNetworkDelegate network_delegate(
3336 BlockingNetworkDelegate::SYNCHRONOUS);
3337 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363338 network_delegate.set_auth_retval(
3339 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3340
[email protected]f3cf9802011-10-28 18:44:583341 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363342
[email protected]ef2bf422012-05-11 03:27:093343 TestURLRequestContext context(true);
3344 context.set_network_delegate(&network_delegate);
3345 context.Init();
[email protected]c2911d72011-10-03 22:16:363346
3347 {
3348 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193349 scoped_ptr<URLRequest> r(context.CreateRequest(
3350 url, DEFAULT_PRIORITY, &d, NULL));
3351 r->Start();
[email protected]255620da2013-08-19 13:14:293352 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363353
[email protected]f7022f32014-08-21 16:32:193354 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3355 EXPECT_EQ(0, r->status().error());
3356 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363357 EXPECT_FALSE(d.auth_required_called());
3358 EXPECT_EQ(1, network_delegate.created_requests());
3359 EXPECT_EQ(0, network_delegate.destroyed_requests());
3360 }
3361 EXPECT_EQ(1, network_delegate.destroyed_requests());
3362}
3363
[email protected]79e1fd62013-06-20 06:50:043364// Same as above, but also tests that GetFullRequestHeaders returns the proper
3365// headers (for the first or second request) when called at the proper times.
3366TEST_F(URLRequestTestHTTP,
3367 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3368 ASSERT_TRUE(test_server_.Start());
3369
3370 TestDelegate d;
3371 BlockingNetworkDelegate network_delegate(
3372 BlockingNetworkDelegate::SYNCHRONOUS);
3373 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3374 network_delegate.set_auth_retval(
3375 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3376
3377 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3378
3379 TestURLRequestContext context(true);
3380 context.set_network_delegate(&network_delegate);
3381 context.Init();
3382
3383 {
3384 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193385 scoped_ptr<URLRequest> r(context.CreateRequest(
3386 url, DEFAULT_PRIORITY, &d, NULL));
3387 r->Start();
[email protected]255620da2013-08-19 13:14:293388 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043389
[email protected]f7022f32014-08-21 16:32:193390 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3391 EXPECT_EQ(0, r->status().error());
3392 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043393 EXPECT_FALSE(d.auth_required_called());
3394 EXPECT_EQ(1, network_delegate.created_requests());
3395 EXPECT_EQ(0, network_delegate.destroyed_requests());
3396
3397 {
3398 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193399 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043400 EXPECT_TRUE(headers.HasHeader("Authorization"));
3401 }
3402 }
3403 EXPECT_EQ(1, network_delegate.destroyed_requests());
3404}
3405
[email protected]c2911d72011-10-03 22:16:363406// Tests that the network delegate can synchronously complete OnAuthRequired
3407// by cancelling authentication.
3408TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3409 ASSERT_TRUE(test_server_.Start());
3410
3411 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303412 BlockingNetworkDelegate network_delegate(
3413 BlockingNetworkDelegate::SYNCHRONOUS);
3414 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363415 network_delegate.set_auth_retval(
3416 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3417
[email protected]ef2bf422012-05-11 03:27:093418 TestURLRequestContext context(true);
3419 context.set_network_delegate(&network_delegate);
3420 context.Init();
[email protected]c2911d72011-10-03 22:16:363421
3422 {
3423 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193424 scoped_ptr<URLRequest> r(context.CreateRequest(
3425 url, DEFAULT_PRIORITY, &d, NULL));
3426 r->Start();
[email protected]255620da2013-08-19 13:14:293427 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363428
[email protected]f7022f32014-08-21 16:32:193429 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3430 EXPECT_EQ(OK, r->status().error());
3431 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363432 EXPECT_FALSE(d.auth_required_called());
3433 EXPECT_EQ(1, network_delegate.created_requests());
3434 EXPECT_EQ(0, network_delegate.destroyed_requests());
3435 }
3436 EXPECT_EQ(1, network_delegate.destroyed_requests());
3437}
3438
3439// Tests that the network delegate can asynchronously complete OnAuthRequired
3440// by taking no action. This indicates that the NetworkDelegate does not want
3441// to handle the challenge, and is passing the buck along to the
3442// URLRequest::Delegate.
3443TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3444 ASSERT_TRUE(test_server_.Start());
3445
3446 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303447 BlockingNetworkDelegate network_delegate(
3448 BlockingNetworkDelegate::AUTO_CALLBACK);
3449 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363450
[email protected]ef2bf422012-05-11 03:27:093451 TestURLRequestContext context(true);
3452 context.set_network_delegate(&network_delegate);
3453 context.Init();
[email protected]c2911d72011-10-03 22:16:363454
[email protected]f3cf9802011-10-28 18:44:583455 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363456
3457 {
3458 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193459 scoped_ptr<URLRequest> r(context.CreateRequest(
3460 url, DEFAULT_PRIORITY, &d, NULL));
3461 r->Start();
[email protected]255620da2013-08-19 13:14:293462 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363463
[email protected]f7022f32014-08-21 16:32:193464 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3465 EXPECT_EQ(0, r->status().error());
3466 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363467 EXPECT_TRUE(d.auth_required_called());
3468 EXPECT_EQ(1, network_delegate.created_requests());
3469 EXPECT_EQ(0, network_delegate.destroyed_requests());
3470 }
3471 EXPECT_EQ(1, network_delegate.destroyed_requests());
3472}
3473
3474// Tests that the network delegate can asynchronously complete OnAuthRequired
3475// by setting credentials.
3476TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3477 ASSERT_TRUE(test_server_.Start());
3478
3479 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303480 BlockingNetworkDelegate network_delegate(
3481 BlockingNetworkDelegate::AUTO_CALLBACK);
3482 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363483 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363484 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3485
[email protected]f3cf9802011-10-28 18:44:583486 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363487 network_delegate.set_auth_credentials(auth_credentials);
3488
[email protected]ef2bf422012-05-11 03:27:093489 TestURLRequestContext context(true);
3490 context.set_network_delegate(&network_delegate);
3491 context.Init();
[email protected]c2911d72011-10-03 22:16:363492
3493 {
3494 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193495 scoped_ptr<URLRequest> r(context.CreateRequest(
3496 url, DEFAULT_PRIORITY, &d, NULL));
3497 r->Start();
[email protected]255620da2013-08-19 13:14:293498 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363499
[email protected]f7022f32014-08-21 16:32:193500 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3501 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363502
[email protected]f7022f32014-08-21 16:32:193503 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363504 EXPECT_FALSE(d.auth_required_called());
3505 EXPECT_EQ(1, network_delegate.created_requests());
3506 EXPECT_EQ(0, network_delegate.destroyed_requests());
3507 }
3508 EXPECT_EQ(1, network_delegate.destroyed_requests());
3509}
3510
3511// Tests that the network delegate can asynchronously complete OnAuthRequired
3512// by cancelling authentication.
3513TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3514 ASSERT_TRUE(test_server_.Start());
3515
3516 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303517 BlockingNetworkDelegate network_delegate(
3518 BlockingNetworkDelegate::AUTO_CALLBACK);
3519 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363520 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363521 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3522
[email protected]ef2bf422012-05-11 03:27:093523 TestURLRequestContext context(true);
3524 context.set_network_delegate(&network_delegate);
3525 context.Init();
[email protected]c2911d72011-10-03 22:16:363526
3527 {
3528 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193529 scoped_ptr<URLRequest> r(context.CreateRequest(
3530 url, DEFAULT_PRIORITY, &d, NULL));
3531 r->Start();
[email protected]255620da2013-08-19 13:14:293532 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363533
[email protected]f7022f32014-08-21 16:32:193534 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3535 EXPECT_EQ(OK, r->status().error());
3536 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363537 EXPECT_FALSE(d.auth_required_called());
3538 EXPECT_EQ(1, network_delegate.created_requests());
3539 EXPECT_EQ(0, network_delegate.destroyed_requests());
3540 }
3541 EXPECT_EQ(1, network_delegate.destroyed_requests());
3542}
3543
[email protected]9045b8822012-01-13 20:35:353544// Tests that we can handle when a network request was canceled while we were
3545// waiting for the network delegate.
3546// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3547TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3548 ASSERT_TRUE(test_server_.Start());
3549
3550 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303551 BlockingNetworkDelegate network_delegate(
3552 BlockingNetworkDelegate::USER_CALLBACK);
3553 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353554
[email protected]ef2bf422012-05-11 03:27:093555 TestURLRequestContext context(true);
3556 context.set_network_delegate(&network_delegate);
3557 context.Init();
[email protected]9045b8822012-01-13 20:35:353558
3559 {
[email protected]f7022f32014-08-21 16:32:193560 scoped_ptr<URLRequest> r(context.CreateRequest(
3561 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:353562
[email protected]f7022f32014-08-21 16:32:193563 r->Start();
[email protected]255620da2013-08-19 13:14:293564 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303565 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3566 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353567 EXPECT_EQ(0, network_delegate.completed_requests());
3568 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193569 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353570 // Ensure that network delegate is notified.
3571 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193572 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3573 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353574 EXPECT_EQ(1, network_delegate.created_requests());
3575 EXPECT_EQ(0, network_delegate.destroyed_requests());
3576 }
3577 EXPECT_EQ(1, network_delegate.destroyed_requests());
3578}
3579
3580// Tests that we can handle when a network request was canceled while we were
3581// waiting for the network delegate.
3582// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3583TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3584 ASSERT_TRUE(test_server_.Start());
3585
3586 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303587 BlockingNetworkDelegate network_delegate(
3588 BlockingNetworkDelegate::USER_CALLBACK);
3589 network_delegate.set_block_on(
3590 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353591
[email protected]ef2bf422012-05-11 03:27:093592 TestURLRequestContext context(true);
3593 context.set_network_delegate(&network_delegate);
3594 context.Init();
[email protected]9045b8822012-01-13 20:35:353595
3596 {
[email protected]f7022f32014-08-21 16:32:193597 scoped_ptr<URLRequest> r(context.CreateRequest(
3598 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:353599
[email protected]f7022f32014-08-21 16:32:193600 r->Start();
[email protected]255620da2013-08-19 13:14:293601 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303602 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3603 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353604 EXPECT_EQ(0, network_delegate.completed_requests());
3605 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193606 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353607 // Ensure that network delegate is notified.
3608 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193609 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3610 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353611 EXPECT_EQ(1, network_delegate.created_requests());
3612 EXPECT_EQ(0, network_delegate.destroyed_requests());
3613 }
3614 EXPECT_EQ(1, network_delegate.destroyed_requests());
3615}
3616
3617// Tests that we can handle when a network request was canceled while we were
3618// waiting for the network delegate.
3619// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3620TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3621 ASSERT_TRUE(test_server_.Start());
3622
3623 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303624 BlockingNetworkDelegate network_delegate(
3625 BlockingNetworkDelegate::USER_CALLBACK);
3626 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353627
[email protected]ef2bf422012-05-11 03:27:093628 TestURLRequestContext context(true);
3629 context.set_network_delegate(&network_delegate);
3630 context.Init();
[email protected]9045b8822012-01-13 20:35:353631
3632 {
[email protected]f7022f32014-08-21 16:32:193633 scoped_ptr<URLRequest> r(context.CreateRequest(
3634 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:353635
[email protected]f7022f32014-08-21 16:32:193636 r->Start();
[email protected]255620da2013-08-19 13:14:293637 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303638 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3639 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353640 EXPECT_EQ(0, network_delegate.completed_requests());
3641 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193642 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353643 // Ensure that network delegate is notified.
3644 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193645 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3646 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353647 EXPECT_EQ(1, network_delegate.created_requests());
3648 EXPECT_EQ(0, network_delegate.destroyed_requests());
3649 }
3650 EXPECT_EQ(1, network_delegate.destroyed_requests());
3651}
3652
3653// Tests that we can handle when a network request was canceled while we were
3654// waiting for the network delegate.
3655// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023656TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353657 ASSERT_TRUE(test_server_.Start());
3658
3659 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303660 BlockingNetworkDelegate network_delegate(
3661 BlockingNetworkDelegate::USER_CALLBACK);
3662 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353663
[email protected]ef2bf422012-05-11 03:27:093664 TestURLRequestContext context(true);
3665 context.set_network_delegate(&network_delegate);
3666 context.Init();
[email protected]9045b8822012-01-13 20:35:353667
3668 {
[email protected]f7022f32014-08-21 16:32:193669 scoped_ptr<URLRequest> r(context.CreateRequest(
3670 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:353671
[email protected]f7022f32014-08-21 16:32:193672 r->Start();
[email protected]255620da2013-08-19 13:14:293673 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303674 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3675 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353676 EXPECT_EQ(0, network_delegate.completed_requests());
3677 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193678 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353679 // Ensure that network delegate is notified.
3680 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193681 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3682 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353683 EXPECT_EQ(1, network_delegate.created_requests());
3684 EXPECT_EQ(0, network_delegate.destroyed_requests());
3685 }
3686 EXPECT_EQ(1, network_delegate.destroyed_requests());
3687}
3688
[email protected]95409e12010-08-17 20:07:113689// In this unit test, we're using the HTTPTestServer as a proxy server and
3690// issuing a CONNECT request with the magic host name "www.server-auth.com".
3691// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353692TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113693 ASSERT_TRUE(test_server_.Start());
3694
[email protected]ceefd7fd2012-11-29 00:36:243695 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043696 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193697 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503698
[email protected]dc651782009-02-14 01:45:083699 TestDelegate d;
3700 {
[email protected]f7022f32014-08-21 16:32:193701 scoped_ptr<URLRequest> r(context.CreateRequest(
3702 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
[email protected]dc651782009-02-14 01:45:083703
[email protected]f7022f32014-08-21 16:32:193704 r->Start();
3705 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083706
[email protected]255620da2013-08-19 13:14:293707 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083708
[email protected]f7022f32014-08-21 16:32:193709 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153710 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193711 EXPECT_TRUE(r->proxy_server().IsEmpty());
3712 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083713 }
3714}
3715
[email protected]b89290212009-08-14 22:37:353716TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113717 ASSERT_TRUE(test_server_.Start());
3718
initial.commit586acc5fe2008-07-26 22:42:523719 TestDelegate d;
3720 {
[email protected]f7022f32014-08-21 16:32:193721 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3722 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
initial.commit586acc5fe2008-07-26 22:42:523723
[email protected]f7022f32014-08-21 16:32:193724 r->Start();
3725 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523726
[email protected]255620da2013-08-19 13:14:293727 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523728
3729 EXPECT_EQ(1, d.response_started_count());
3730 EXPECT_FALSE(d.received_data_before_response());
3731 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193732 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193733 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193734 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193735 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163736
[email protected]9e743cd2010-03-16 07:03:533737 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523738 }
initial.commit586acc5fe2008-07-26 22:42:523739}
3740
[email protected]263163f2012-06-14 22:40:343741// This test has the server send a large number of cookies to the client.
3742// To ensure that no number of cookies causes a crash, a galloping binary
3743// search is used to estimate that maximum number of cookies that are accepted
3744// by the browser. Beyond the maximum number, the request will fail with
3745// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303746#if defined(OS_WIN)
3747// http://crbug.com/177916
3748#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3749#else
3750#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3751#endif // defined(OS_WIN)
3752TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343753 ASSERT_TRUE(test_server_.Start());
3754
3755 int lower_bound = 0;
3756 int upper_bound = 1;
3757
3758 // Double the number of cookies until the response header limits are
3759 // exceeded.
3760 while (DoManyCookiesRequest(upper_bound)) {
3761 lower_bound = upper_bound;
3762 upper_bound *= 2;
3763 ASSERT_LT(upper_bound, 1000000);
3764 }
3765
pkasting6b68a162014-12-01 22:10:293766 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:343767 if (tolerance < 2)
3768 tolerance = 2;
3769
3770 // Perform a binary search to find the highest possible number of cookies,
3771 // within the desired tolerance.
3772 while (upper_bound - lower_bound >= tolerance) {
3773 int num_cookies = (lower_bound + upper_bound) / 2;
3774
3775 if (DoManyCookiesRequest(num_cookies))
3776 lower_bound = num_cookies;
3777 else
3778 upper_bound = num_cookies;
3779 }
3780 // Success: the test did not crash.
3781}
3782
[email protected]b89290212009-08-14 22:37:353783TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113784 ASSERT_TRUE(test_server_.Start());
3785
initial.commit586acc5fe2008-07-26 22:42:523786 TestDelegate d;
3787 {
[email protected]f7022f32014-08-21 16:32:193788 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3789 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
initial.commit586acc5fe2008-07-26 22:42:523790
[email protected]f7022f32014-08-21 16:32:193791 r->Start();
3792 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523793
[email protected]255620da2013-08-19 13:14:293794 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523795
3796 EXPECT_EQ(1, d.response_started_count());
3797 EXPECT_FALSE(d.received_data_before_response());
3798 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193799 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193800 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193801 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193802 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523803 }
[email protected]5d7b373e2009-09-02 07:19:033804}
3805
[email protected]79e1fd62013-06-20 06:50:043806TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3807 ASSERT_TRUE(test_server_.Start());
3808
3809 TestDelegate d;
3810 {
3811 GURL test_url(test_server_.GetURL(std::string()));
[email protected]f7022f32014-08-21 16:32:193812 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3813 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:043814
3815 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193816 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043817
[email protected]f7022f32014-08-21 16:32:193818 r->Start();
3819 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:043820
[email protected]255620da2013-08-19 13:14:293821 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043822
3823 EXPECT_EQ(1, d.response_started_count());
3824 EXPECT_FALSE(d.received_data_before_response());
3825 EXPECT_NE(0, d.bytes_received());
3826 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193827 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:043828 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193829 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:043830
3831 EXPECT_TRUE(d.have_full_request_headers());
3832 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3833 }
3834}
3835
[email protected]58e32bb2013-01-21 18:23:253836TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3837 ASSERT_TRUE(test_server_.Start());
3838
3839 TestDelegate d;
3840 {
[email protected]f7022f32014-08-21 16:32:193841 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3842 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]58e32bb2013-01-21 18:23:253843
[email protected]f7022f32014-08-21 16:32:193844 r->Start();
3845 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:253846
[email protected]255620da2013-08-19 13:14:293847 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253848
3849 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:193850 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253851 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3852
3853 EXPECT_EQ(1, d.response_started_count());
3854 EXPECT_FALSE(d.received_data_before_response());
3855 EXPECT_NE(0, d.bytes_received());
3856 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193857 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:253858 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193859 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:253860 }
3861}
3862
[email protected]aad63572011-05-24 20:14:393863TEST_F(URLRequestTestHTTP, GetZippedTest) {
3864 ASSERT_TRUE(test_server_.Start());
3865
3866 // Parameter that specifies the Content-Length field in the response:
3867 // C - Compressed length.
3868 // U - Uncompressed length.
3869 // L - Large length (larger than both C & U).
3870 // M - Medium length (between C & U).
3871 // S - Small length (smaller than both C & U).
3872 const char test_parameters[] = "CULMS";
3873 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3874 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443875 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393876 // S has too little data, but we seem to accept it.
3877 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373878 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393879
3880 for (int i = 0; i < num_tests ; i++) {
3881 TestDelegate d;
3882 {
3883 std::string test_file =
3884 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3885 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393886
[email protected]ceefd7fd2012-11-29 00:36:243887 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093888 TestURLRequestContext context(true);
3889 context.set_network_delegate(&network_delegate);
3890 context.Init();
[email protected]87a09a92011-07-14 15:50:503891
[email protected]f7022f32014-08-21 16:32:193892 scoped_ptr<URLRequest> r(context.CreateRequest(
3893 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
3894 r->Start();
3895 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:393896
[email protected]255620da2013-08-19 13:14:293897 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393898
3899 EXPECT_EQ(1, d.response_started_count());
3900 EXPECT_FALSE(d.received_data_before_response());
3901 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:193902 << " status = " << r->status().status()
3903 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:393904 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:193905 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:393906 << " Parameter = \"" << test_file << "\"";
3907 } else {
[email protected]f7022f32014-08-21 16:32:193908 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3909 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:393910 << " Parameter = \"" << test_file << "\"";
3911 }
3912 }
3913 }
3914}
3915
[email protected]58e32bb2013-01-21 18:23:253916TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3917 ASSERT_TRUE(test_server_.Start());
3918
[email protected]007b3f82013-04-09 08:46:453919 GURL destination_url = test_server_.GetURL(std::string());
3920 GURL original_url =
3921 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253922 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193923 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3924 original_url, DEFAULT_PRIORITY, &d, NULL));
3925 req->Start();
[email protected]255620da2013-08-19 13:14:293926 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253927
3928 EXPECT_EQ(1, d.response_started_count());
3929 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:193930 EXPECT_EQ(destination_url, req->url());
3931 EXPECT_EQ(original_url, req->original_url());
3932 ASSERT_EQ(2U, req->url_chain().size());
3933 EXPECT_EQ(original_url, req->url_chain()[0]);
3934 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:253935
3936 LoadTimingInfo load_timing_info_before_redirect;
3937 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3938 &load_timing_info_before_redirect));
3939 TestLoadTimingNotReused(load_timing_info_before_redirect,
3940 CONNECT_TIMING_HAS_DNS_TIMES);
3941
3942 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:193943 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253944 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3945
3946 // Check that a new socket was used on redirect, since the server does not
3947 // supposed keep-alive sockets, and that the times before the redirect are
3948 // before the ones recorded for the second request.
3949 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3950 load_timing_info.socket_log_id);
3951 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3952 load_timing_info.connect_timing.connect_start);
3953}
3954
[email protected]8f1ac082011-04-19 21:14:133955TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3956 ASSERT_TRUE(test_server_.Start());
3957
[email protected]007b3f82013-04-09 08:46:453958 GURL destination_url = test_server_.GetURL(std::string());
3959 GURL middle_redirect_url =
3960 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133961 GURL original_url = test_server_.GetURL(
3962 "server-redirect?" + middle_redirect_url.spec());
3963 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193964 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3965 original_url, DEFAULT_PRIORITY, &d, NULL));
3966 req->Start();
[email protected]255620da2013-08-19 13:14:293967 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133968
3969 EXPECT_EQ(1, d.response_started_count());
3970 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:193971 EXPECT_EQ(destination_url, req->url());
3972 EXPECT_EQ(original_url, req->original_url());
3973 ASSERT_EQ(3U, req->url_chain().size());
3974 EXPECT_EQ(original_url, req->url_chain()[0]);
3975 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
3976 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:133977}
3978
[email protected]abe1c4a2013-10-25 19:28:513979// First and second pieces of information logged by delegates to URLRequests.
3980const char kFirstDelegateInfo[] = "Wonderful delegate";
3981const char kSecondDelegateInfo[] = "Exciting delegate";
3982
3983// Logs delegate information to a URLRequest. The first string is logged
3984// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3985// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3986// another asynchronous call is used to clear the delegate information
3987// before calling a callback. The object then deletes itself.
3988class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3989 public:
3990 typedef base::Callback<void()> Callback;
3991
3992 // Each time delegate information is added to the URLRequest, the resulting
3993 // load state is checked. The expected load state after each request is
3994 // passed in as an argument.
3995 static void Run(URLRequest* url_request,
3996 LoadState expected_first_load_state,
3997 LoadState expected_second_load_state,
3998 LoadState expected_third_load_state,
3999 const Callback& callback) {
4000 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4001 url_request,
4002 expected_first_load_state,
4003 expected_second_load_state,
4004 expected_third_load_state,
4005 callback);
4006 logger->Start();
4007 }
4008
4009 // Checks that the log entries, starting with log_position, contain the
4010 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4011 // recorded. Returns the index of entry after the expected number of
4012 // events this logged, or entries.size() if there aren't enough entries.
4013 static size_t CheckDelegateInfo(
4014 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4015 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4016 if (log_position + 3 >= entries.size()) {
4017 ADD_FAILURE() << "Not enough log entries";
4018 return entries.size();
4019 }
4020 std::string delegate_info;
4021 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4022 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4023 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4024 &delegate_info));
4025 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4026
4027 ++log_position;
4028 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4029 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4030
4031 ++log_position;
4032 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4033 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4034 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4035 &delegate_info));
4036 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4037
4038 ++log_position;
4039 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4040 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4041
4042 return log_position + 1;
4043 }
4044
[email protected]1826a402014-01-08 15:40:484045 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4046 // Returns the position of the end message.
4047 static size_t ExpectBeforeNetworkEvents(
4048 const CapturingNetLog::CapturedEntryList& entries,
4049 size_t log_position) {
4050 log_position =
4051 ExpectLogContainsSomewhereAfter(entries,
4052 log_position,
4053 NetLog::TYPE_URL_REQUEST_DELEGATE,
4054 NetLog::PHASE_BEGIN);
4055 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4056 entries[log_position + 1].type);
4057 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4058 return log_position + 1;
4059 }
4060
[email protected]abe1c4a2013-10-25 19:28:514061 private:
4062 friend class base::RefCounted<AsyncDelegateLogger>;
4063
4064 AsyncDelegateLogger(URLRequest* url_request,
4065 LoadState expected_first_load_state,
4066 LoadState expected_second_load_state,
4067 LoadState expected_third_load_state,
4068 const Callback& callback)
4069 : url_request_(url_request),
4070 expected_first_load_state_(expected_first_load_state),
4071 expected_second_load_state_(expected_second_load_state),
4072 expected_third_load_state_(expected_third_load_state),
4073 callback_(callback) {
4074 }
4075
4076 ~AsyncDelegateLogger() {}
4077
4078 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534079 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514080 LoadStateWithParam load_state = url_request_->GetLoadState();
4081 EXPECT_EQ(expected_first_load_state_, load_state.state);
4082 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4083 base::MessageLoop::current()->PostTask(
4084 FROM_HERE,
4085 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4086 }
4087
4088 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534089 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514090 LoadStateWithParam load_state = url_request_->GetLoadState();
4091 EXPECT_EQ(expected_second_load_state_, load_state.state);
4092 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4093 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4094 } else {
4095 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4096 }
4097 base::MessageLoop::current()->PostTask(
4098 FROM_HERE,
4099 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4100 }
4101
4102 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534103 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514104 LoadStateWithParam load_state = url_request_->GetLoadState();
4105 EXPECT_EQ(expected_third_load_state_, load_state.state);
4106 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084107 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514108 callback_.Run();
4109 }
4110
4111 URLRequest* url_request_;
4112 const int expected_first_load_state_;
4113 const int expected_second_load_state_;
4114 const int expected_third_load_state_;
4115 const Callback callback_;
4116
4117 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4118};
4119
4120// NetworkDelegate that logs delegate information before a request is started,
4121// before headers are sent, when headers are read, and when auth information
4122// is requested. Uses AsyncDelegateLogger.
4123class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4124 public:
4125 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204126 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514127
4128 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204129 int OnBeforeURLRequest(URLRequest* request,
4130 const CompletionCallback& callback,
4131 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514132 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4133 return RunCallbackAsynchronously(request, callback);
4134 }
4135
dchengb03027d2014-10-21 12:00:204136 int OnBeforeSendHeaders(URLRequest* request,
4137 const CompletionCallback& callback,
4138 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514139 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4140 return RunCallbackAsynchronously(request, callback);
4141 }
4142
dchengb03027d2014-10-21 12:00:204143 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514144 URLRequest* request,
4145 const CompletionCallback& callback,
4146 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164147 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134148 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164149 TestNetworkDelegate::OnHeadersReceived(request,
4150 callback,
[email protected]abe1c4a2013-10-25 19:28:514151 original_response_headers,
[email protected]5f714132014-03-26 10:41:164152 override_response_headers,
4153 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514154 return RunCallbackAsynchronously(request, callback);
4155 }
4156
dchengb03027d2014-10-21 12:00:204157 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514158 URLRequest* request,
4159 const AuthChallengeInfo& auth_info,
4160 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134161 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514162 AsyncDelegateLogger::Run(
4163 request,
4164 LOAD_STATE_WAITING_FOR_DELEGATE,
4165 LOAD_STATE_WAITING_FOR_DELEGATE,
4166 LOAD_STATE_WAITING_FOR_DELEGATE,
4167 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4168 callback, credentials));
4169 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4170 }
4171
4172 private:
4173 static int RunCallbackAsynchronously(
4174 URLRequest* request,
4175 const CompletionCallback& callback) {
4176 AsyncDelegateLogger::Run(
4177 request,
4178 LOAD_STATE_WAITING_FOR_DELEGATE,
4179 LOAD_STATE_WAITING_FOR_DELEGATE,
4180 LOAD_STATE_WAITING_FOR_DELEGATE,
4181 base::Bind(callback, OK));
4182 return ERR_IO_PENDING;
4183 }
4184
4185 static void SetAuthAndResume(const AuthCallback& callback,
4186 AuthCredentials* credentials) {
4187 *credentials = AuthCredentials(kUser, kSecret);
4188 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4189 }
4190
4191 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4192};
4193
4194// URLRequest::Delegate that logs delegate information when the headers
4195// are received, when each read completes, and during redirects. Uses
4196// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4197//
4198// Inherits from TestDelegate to reuse the TestDelegate code to handle
4199// advancing to the next step in most cases, as well as cancellation.
4200class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4201 public:
4202 enum CancelStage {
4203 NO_CANCEL = 0,
4204 CANCEL_ON_RECEIVED_REDIRECT,
4205 CANCEL_ON_RESPONSE_STARTED,
4206 CANCEL_ON_READ_COMPLETED
4207 };
4208
4209 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4210 : cancel_stage_(cancel_stage) {
4211 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4212 set_cancel_in_received_redirect(true);
4213 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4214 set_cancel_in_response_started(true);
4215 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4216 set_cancel_in_received_data(true);
4217 }
dchengb03027d2014-10-21 12:00:204218 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514219
4220 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204221 void OnReceivedRedirect(URLRequest* request,
4222 const RedirectInfo& redirect_info,
4223 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514224 *defer_redirect = true;
4225 AsyncDelegateLogger::Run(
4226 request,
4227 LOAD_STATE_WAITING_FOR_DELEGATE,
4228 LOAD_STATE_WAITING_FOR_DELEGATE,
4229 LOAD_STATE_WAITING_FOR_DELEGATE,
4230 base::Bind(
4231 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594232 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514233 }
4234
dchengb03027d2014-10-21 12:00:204235 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514236 AsyncDelegateLogger::Run(
4237 request,
4238 LOAD_STATE_WAITING_FOR_DELEGATE,
4239 LOAD_STATE_WAITING_FOR_DELEGATE,
4240 LOAD_STATE_WAITING_FOR_DELEGATE,
4241 base::Bind(
4242 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4243 base::Unretained(this), request));
4244 }
4245
dchengb03027d2014-10-21 12:00:204246 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514247 AsyncDelegateLogger::Run(
4248 request,
4249 LOAD_STATE_IDLE,
4250 LOAD_STATE_IDLE,
4251 LOAD_STATE_IDLE,
4252 base::Bind(
4253 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4254 base::Unretained(this), request, bytes_read));
4255 }
4256
4257 private:
4258 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594259 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514260 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594261 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514262 // FollowDeferredRedirect should not be called after cancellation.
4263 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4264 return;
4265 if (!defer_redirect)
4266 request->FollowDeferredRedirect();
4267 }
4268
4269 void OnResponseStartedLoggingComplete(URLRequest* request) {
4270 // The parent class continues the request.
4271 TestDelegate::OnResponseStarted(request);
4272 }
4273
4274 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4275 // The parent class continues the request.
4276 TestDelegate::OnReadCompleted(request, bytes_read);
4277 }
4278
4279 const CancelStage cancel_stage_;
4280
4281 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4282};
4283
4284// Tests handling of delegate info before a request starts.
4285TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4286 ASSERT_TRUE(test_server_.Start());
4287
4288 TestDelegate request_delegate;
4289 TestURLRequestContext context(true);
4290 context.set_network_delegate(NULL);
4291 context.set_net_log(&net_log_);
4292 context.Init();
4293
4294 {
[email protected]f7022f32014-08-21 16:32:194295 scoped_ptr<URLRequest> r(context.CreateRequest(
4296 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4297 NULL));
4298 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514299 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084300 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514301
4302 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194303 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514304 LOAD_STATE_WAITING_FOR_DELEGATE,
4305 LOAD_STATE_WAITING_FOR_DELEGATE,
4306 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194307 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514308
4309 base::RunLoop().Run();
4310
[email protected]f7022f32014-08-21 16:32:194311 EXPECT_EQ(200, r->GetResponseCode());
4312 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514313 }
4314
4315 CapturingNetLog::CapturedEntryList entries;
4316 net_log_.GetEntries(&entries);
4317 size_t log_position = ExpectLogContainsSomewhereAfter(
4318 entries,
4319 0,
4320 NetLog::TYPE_DELEGATE_INFO,
4321 NetLog::PHASE_BEGIN);
4322
4323 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4324
4325 // Nothing else should add any delegate info to the request.
4326 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4327 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4328}
4329
4330// Tests handling of delegate info from a network delegate.
4331TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4332 ASSERT_TRUE(test_server_.Start());
4333
4334 TestDelegate request_delegate;
4335 AsyncLoggingNetworkDelegate network_delegate;
4336 TestURLRequestContext context(true);
4337 context.set_network_delegate(&network_delegate);
4338 context.set_net_log(&net_log_);
4339 context.Init();
4340
4341 {
[email protected]f7022f32014-08-21 16:32:194342 scoped_ptr<URLRequest> r(context.CreateRequest(
4343 test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4344 NULL));
4345 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514346 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084347 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514348
[email protected]f7022f32014-08-21 16:32:194349 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514350 base::RunLoop().Run();
4351
[email protected]f7022f32014-08-21 16:32:194352 EXPECT_EQ(200, r->GetResponseCode());
4353 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514354 EXPECT_EQ(1, network_delegate.created_requests());
4355 EXPECT_EQ(0, network_delegate.destroyed_requests());
4356 }
4357 EXPECT_EQ(1, network_delegate.destroyed_requests());
4358
4359 size_t log_position = 0;
4360 CapturingNetLog::CapturedEntryList entries;
4361 net_log_.GetEntries(&entries);
4362 for (size_t i = 0; i < 3; ++i) {
4363 log_position = ExpectLogContainsSomewhereAfter(
4364 entries,
4365 log_position + 1,
4366 NetLog::TYPE_URL_REQUEST_DELEGATE,
4367 NetLog::PHASE_BEGIN);
4368
4369 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4370 log_position + 1);
4371
4372 ASSERT_LT(log_position, entries.size());
4373 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4374 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484375
4376 if (i == 1) {
4377 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4378 entries, log_position + 1);
4379 }
[email protected]abe1c4a2013-10-25 19:28:514380 }
4381
4382 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4383 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4384}
4385
4386// Tests handling of delegate info from a network delegate in the case of an
4387// HTTP redirect.
4388TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4389 ASSERT_TRUE(test_server_.Start());
4390
4391 TestDelegate request_delegate;
4392 AsyncLoggingNetworkDelegate network_delegate;
4393 TestURLRequestContext context(true);
4394 context.set_network_delegate(&network_delegate);
4395 context.set_net_log(&net_log_);
4396 context.Init();
4397
4398 {
[email protected]f7022f32014-08-21 16:32:194399 scoped_ptr<URLRequest> r(context.CreateRequest(
4400 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4401 &request_delegate, NULL));
4402 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514403 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084404 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514405
[email protected]f7022f32014-08-21 16:32:194406 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514407 base::RunLoop().Run();
4408
[email protected]f7022f32014-08-21 16:32:194409 EXPECT_EQ(200, r->GetResponseCode());
4410 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514411 EXPECT_EQ(2, network_delegate.created_requests());
4412 EXPECT_EQ(0, network_delegate.destroyed_requests());
4413 }
4414 EXPECT_EQ(1, network_delegate.destroyed_requests());
4415
4416 size_t log_position = 0;
4417 CapturingNetLog::CapturedEntryList entries;
4418 net_log_.GetEntries(&entries);
4419 // The NetworkDelegate logged information in OnBeforeURLRequest,
4420 // OnBeforeSendHeaders, and OnHeadersReceived.
4421 for (size_t i = 0; i < 3; ++i) {
4422 log_position = ExpectLogContainsSomewhereAfter(
4423 entries,
4424 log_position + 1,
4425 NetLog::TYPE_URL_REQUEST_DELEGATE,
4426 NetLog::PHASE_BEGIN);
4427
4428 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4429 log_position + 1);
4430
4431 ASSERT_LT(log_position, entries.size());
4432 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4433 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484434
4435 if (i == 1) {
4436 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4437 entries, log_position + 1);
4438 }
[email protected]abe1c4a2013-10-25 19:28:514439 }
4440
4441 // The URLRequest::Delegate then gets informed about the redirect.
4442 log_position = ExpectLogContainsSomewhereAfter(
4443 entries,
4444 log_position + 1,
4445 NetLog::TYPE_URL_REQUEST_DELEGATE,
4446 NetLog::PHASE_BEGIN);
4447
4448 // The NetworkDelegate logged information in the same three events as before.
4449 for (size_t i = 0; i < 3; ++i) {
4450 log_position = ExpectLogContainsSomewhereAfter(
4451 entries,
4452 log_position + 1,
4453 NetLog::TYPE_URL_REQUEST_DELEGATE,
4454 NetLog::PHASE_BEGIN);
4455
4456 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4457 log_position + 1);
4458
4459 ASSERT_LT(log_position, entries.size());
4460 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4461 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4462 }
4463
4464 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4465 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4466}
4467
4468// Tests handling of delegate info from a network delegate in the case of HTTP
4469// AUTH.
4470TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4471 ASSERT_TRUE(test_server_.Start());
4472
4473 TestDelegate request_delegate;
4474 AsyncLoggingNetworkDelegate network_delegate;
4475 TestURLRequestContext context(true);
4476 context.set_network_delegate(&network_delegate);
4477 context.set_net_log(&net_log_);
4478 context.Init();
4479
4480 {
[email protected]f7022f32014-08-21 16:32:194481 scoped_ptr<URLRequest> r(context.CreateRequest(
4482 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4483 NULL));
4484 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514485 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084486 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514487
[email protected]f7022f32014-08-21 16:32:194488 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514489 base::RunLoop().Run();
4490
[email protected]f7022f32014-08-21 16:32:194491 EXPECT_EQ(200, r->GetResponseCode());
4492 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514493 EXPECT_EQ(1, network_delegate.created_requests());
4494 EXPECT_EQ(0, network_delegate.destroyed_requests());
4495 }
4496 EXPECT_EQ(1, network_delegate.destroyed_requests());
4497
4498 size_t log_position = 0;
4499 CapturingNetLog::CapturedEntryList entries;
4500 net_log_.GetEntries(&entries);
4501 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4502 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4503 // OnBeforeURLRequest and OnBeforeSendHeaders.
4504 for (size_t i = 0; i < 6; ++i) {
4505 log_position = ExpectLogContainsSomewhereAfter(
4506 entries,
4507 log_position + 1,
4508 NetLog::TYPE_URL_REQUEST_DELEGATE,
4509 NetLog::PHASE_BEGIN);
4510
4511 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4512 log_position + 1);
4513
4514 ASSERT_LT(log_position, entries.size());
4515 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4516 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484517
4518 if (i == 1) {
4519 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4520 entries, log_position + 1);
4521 }
[email protected]abe1c4a2013-10-25 19:28:514522 }
4523
4524 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4525 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4526}
4527
4528// Tests handling of delegate info from a URLRequest::Delegate.
4529TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4530 ASSERT_TRUE(test_server_.Start());
4531
4532 AsyncLoggingUrlRequestDelegate request_delegate(
4533 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4534 TestURLRequestContext context(true);
4535 context.set_network_delegate(NULL);
4536 context.set_net_log(&net_log_);
4537 context.Init();
4538
4539 {
4540 // A chunked response with delays between chunks is used to make sure that
4541 // attempts by the URLRequest delegate to log information while reading the
4542 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484543 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514544 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194545 scoped_ptr<URLRequest> r(context.CreateRequest(
4546 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
4547 &request_delegate, NULL));
4548 LoadStateWithParam load_state = r->GetLoadState();
4549 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514550 base::RunLoop().Run();
4551
[email protected]f7022f32014-08-21 16:32:194552 EXPECT_EQ(200, r->GetResponseCode());
4553 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514554 }
4555
4556 CapturingNetLog::CapturedEntryList entries;
4557 net_log_.GetEntries(&entries);
4558
[email protected]1826a402014-01-08 15:40:484559 size_t log_position = 0;
4560
4561 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4562 entries, log_position);
4563
[email protected]abe1c4a2013-10-25 19:28:514564 // The delegate info should only have been logged on header complete. Other
4565 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484566 log_position =
4567 ExpectLogContainsSomewhereAfter(entries,
4568 log_position + 1,
4569 NetLog::TYPE_URL_REQUEST_DELEGATE,
4570 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514571
4572 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4573 log_position + 1);
4574
4575 ASSERT_LT(log_position, entries.size());
4576 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4577 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4578
4579 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4580 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4581 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4582 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4583}
4584
4585// Tests handling of delegate info from a URLRequest::Delegate in the case of
4586// an HTTP redirect.
4587TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4588 ASSERT_TRUE(test_server_.Start());
4589
4590 AsyncLoggingUrlRequestDelegate request_delegate(
4591 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4592 TestURLRequestContext context(true);
4593 context.set_network_delegate(NULL);
4594 context.set_net_log(&net_log_);
4595 context.Init();
4596
4597 {
[email protected]f7022f32014-08-21 16:32:194598 scoped_ptr<URLRequest> r(context.CreateRequest(
4599 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4600 &request_delegate, NULL));
4601 LoadStateWithParam load_state = r->GetLoadState();
4602 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514603 base::RunLoop().Run();
4604
[email protected]f7022f32014-08-21 16:32:194605 EXPECT_EQ(200, r->GetResponseCode());
4606 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514607 }
4608
4609 CapturingNetLog::CapturedEntryList entries;
4610 net_log_.GetEntries(&entries);
4611
4612 // Delegate info should only have been logged in OnReceivedRedirect and
4613 // OnResponseStarted.
4614 size_t log_position = 0;
4615 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484616 if (i == 0) {
4617 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4618 entries, log_position) + 1;
4619 }
4620
[email protected]abe1c4a2013-10-25 19:28:514621 log_position = ExpectLogContainsSomewhereAfter(
4622 entries,
4623 log_position,
4624 NetLog::TYPE_URL_REQUEST_DELEGATE,
4625 NetLog::PHASE_BEGIN);
4626
4627 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4628 log_position + 1);
4629
4630 ASSERT_LT(log_position, entries.size());
4631 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4632 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4633 }
4634
4635 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4636 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4637 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4638 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4639}
4640
4641// Tests handling of delegate info from a URLRequest::Delegate in the case of
4642// an HTTP redirect, with cancellation at various points.
4643TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4644 ASSERT_TRUE(test_server_.Start());
4645
4646 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4647 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4648 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4649 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4650 };
4651
4652 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4653 ++test_case) {
4654 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4655 TestURLRequestContext context(true);
4656 CapturingNetLog net_log;
4657 context.set_network_delegate(NULL);
4658 context.set_net_log(&net_log);
4659 context.Init();
4660
4661 {
[email protected]f7022f32014-08-21 16:32:194662 scoped_ptr<URLRequest> r(context.CreateRequest(
4663 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4664 &request_delegate, NULL));
4665 LoadStateWithParam load_state = r->GetLoadState();
4666 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514667 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194668 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514669 }
4670
4671 CapturingNetLog::CapturedEntryList entries;
4672 net_log.GetEntries(&entries);
4673
4674 // Delegate info is always logged in both OnReceivedRedirect and
4675 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4676 // OnResponseStarted delegate call is after cancellation, but logging is
4677 // still currently supported in that call.
4678 size_t log_position = 0;
4679 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484680 if (i == 0) {
4681 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4682 entries, log_position) + 1;
4683 }
4684
[email protected]abe1c4a2013-10-25 19:28:514685 log_position = ExpectLogContainsSomewhereAfter(
4686 entries,
4687 log_position,
4688 NetLog::TYPE_URL_REQUEST_DELEGATE,
4689 NetLog::PHASE_BEGIN);
4690
4691 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4692 log_position + 1);
4693
4694 ASSERT_LT(log_position, entries.size());
4695 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4696 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4697 }
4698
4699 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4700 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4701 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4702 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4703 }
4704}
4705
[email protected]847c0fa92012-11-06 16:37:424706namespace {
4707
4708const char kExtraHeader[] = "Allow-Snafu";
4709const char kExtraValue[] = "fubar";
4710
4711class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204712 void OnReceivedRedirect(URLRequest* request,
4713 const RedirectInfo& redirect_info,
4714 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594715 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424716 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4717 }
4718};
4719
4720} // namespace
4721
4722TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4723 ASSERT_TRUE(test_server_.Start());
4724
4725 GURL destination_url = test_server_.GetURL(
4726 "echoheader?" + std::string(kExtraHeader));
4727 GURL original_url = test_server_.GetURL(
4728 "server-redirect?" + destination_url.spec());
4729 RedirectWithAdditionalHeadersDelegate d;
[email protected]f7022f32014-08-21 16:32:194730 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4731 original_url, DEFAULT_PRIORITY, &d, NULL));
4732 req->Start();
[email protected]255620da2013-08-19 13:14:294733 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424734
4735 std::string value;
[email protected]f7022f32014-08-21 16:32:194736 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424737 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4738 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194739 EXPECT_FALSE(req->is_pending());
4740 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424741 EXPECT_EQ(kExtraValue, d.data_received());
4742}
4743
[email protected]251a1b92012-11-13 11:01:094744namespace {
4745
4746const char kExtraHeaderToRemove[] = "To-Be-Removed";
4747
4748class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204749 void OnReceivedRedirect(URLRequest* request,
4750 const RedirectInfo& redirect_info,
4751 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594752 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094753 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4754 }
4755};
4756
4757} // namespace
4758
4759TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4760 ASSERT_TRUE(test_server_.Start());
4761
4762 GURL destination_url = test_server_.GetURL(
4763 "echoheader?" + std::string(kExtraHeaderToRemove));
4764 GURL original_url = test_server_.GetURL(
4765 "server-redirect?" + destination_url.spec());
4766 RedirectWithHeaderRemovalDelegate d;
[email protected]f7022f32014-08-21 16:32:194767 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4768 original_url, DEFAULT_PRIORITY, &d, NULL));
4769 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4770 req->Start();
[email protected]255620da2013-08-19 13:14:294771 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094772
4773 std::string value;
[email protected]f7022f32014-08-21 16:32:194774 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094775 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194776 EXPECT_FALSE(req->is_pending());
4777 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094778 EXPECT_EQ("None", d.data_received());
4779}
4780
[email protected]316c1e5e2012-09-12 15:17:444781TEST_F(URLRequestTestHTTP, CancelTest) {
4782 TestDelegate d;
4783 {
[email protected]f7022f32014-08-21 16:32:194784 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4785 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:444786
[email protected]f7022f32014-08-21 16:32:194787 r->Start();
4788 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444789
[email protected]f7022f32014-08-21 16:32:194790 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444791
[email protected]255620da2013-08-19 13:14:294792 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444793
4794 // We expect to receive OnResponseStarted even though the request has been
4795 // cancelled.
4796 EXPECT_EQ(1, d.response_started_count());
4797 EXPECT_EQ(0, d.bytes_received());
4798 EXPECT_FALSE(d.received_data_before_response());
4799 }
4800}
4801
4802TEST_F(URLRequestTestHTTP, CancelTest2) {
4803 ASSERT_TRUE(test_server_.Start());
4804
4805 TestDelegate d;
4806 {
[email protected]f7022f32014-08-21 16:32:194807 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4808 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:444809
4810 d.set_cancel_in_response_started(true);
4811
[email protected]f7022f32014-08-21 16:32:194812 r->Start();
4813 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444814
[email protected]255620da2013-08-19 13:14:294815 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444816
4817 EXPECT_EQ(1, d.response_started_count());
4818 EXPECT_EQ(0, d.bytes_received());
4819 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194820 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444821 }
4822}
4823
4824TEST_F(URLRequestTestHTTP, CancelTest3) {
4825 ASSERT_TRUE(test_server_.Start());
4826
4827 TestDelegate d;
4828 {
[email protected]f7022f32014-08-21 16:32:194829 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4830 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:444831
4832 d.set_cancel_in_received_data(true);
4833
[email protected]f7022f32014-08-21 16:32:194834 r->Start();
4835 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444836
[email protected]255620da2013-08-19 13:14:294837 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444838
4839 EXPECT_EQ(1, d.response_started_count());
4840 // There is no guarantee about how much data was received
4841 // before the cancel was issued. It could have been 0 bytes,
4842 // or it could have been all the bytes.
4843 // EXPECT_EQ(0, d.bytes_received());
4844 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194845 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444846 }
4847}
4848
4849TEST_F(URLRequestTestHTTP, CancelTest4) {
4850 ASSERT_TRUE(test_server_.Start());
4851
4852 TestDelegate d;
4853 {
[email protected]f7022f32014-08-21 16:32:194854 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4855 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:444856
[email protected]f7022f32014-08-21 16:32:194857 r->Start();
4858 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444859
4860 // The request will be implicitly canceled when it is destroyed. The
4861 // test delegate must not post a quit message when this happens because
4862 // this test doesn't actually have a message loop. The quit message would
4863 // get put on this thread's message queue and the next test would exit
4864 // early, causing problems.
4865 d.set_quit_on_complete(false);
4866 }
4867 // expect things to just cleanup properly.
4868
4869 // we won't actually get a received reponse here because we've never run the
4870 // message loop
4871 EXPECT_FALSE(d.received_data_before_response());
4872 EXPECT_EQ(0, d.bytes_received());
4873}
4874
4875TEST_F(URLRequestTestHTTP, CancelTest5) {
4876 ASSERT_TRUE(test_server_.Start());
4877
4878 // populate cache
4879 {
4880 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194881 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4882 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4883 r->Start();
[email protected]255620da2013-08-19 13:14:294884 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194885 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444886 }
4887
4888 // cancel read from cache (see bug 990242)
4889 {
4890 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194891 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4892 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
4893 r->Start();
4894 r->Cancel();
[email protected]255620da2013-08-19 13:14:294895 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444896
[email protected]f7022f32014-08-21 16:32:194897 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444898 EXPECT_EQ(1, d.response_started_count());
4899 EXPECT_EQ(0, d.bytes_received());
4900 EXPECT_FALSE(d.received_data_before_response());
4901 }
4902}
4903
4904TEST_F(URLRequestTestHTTP, PostTest) {
4905 ASSERT_TRUE(test_server_.Start());
4906 HTTPUploadDataOperationTest("POST");
4907}
4908
4909TEST_F(URLRequestTestHTTP, PutTest) {
4910 ASSERT_TRUE(test_server_.Start());
4911 HTTPUploadDataOperationTest("PUT");
4912}
4913
4914TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4915 ASSERT_TRUE(test_server_.Start());
4916
4917 TestDelegate d;
4918 {
[email protected]f7022f32014-08-21 16:32:194919 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4920 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4921 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:444922
[email protected]f7022f32014-08-21 16:32:194923 r->Start();
4924 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444925
[email protected]255620da2013-08-19 13:14:294926 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444927
[email protected]329b68b2012-11-14 17:54:274928 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:194929 << "request failed: " << r->status().status()
4930 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:444931
4932 EXPECT_FALSE(d.received_data_before_response());
4933 EXPECT_TRUE(d.data_received().empty());
4934 }
4935}
4936
4937TEST_F(URLRequestTestHTTP, PostFileTest) {
4938 ASSERT_TRUE(test_server_.Start());
4939
4940 TestDelegate d;
4941 {
[email protected]f7022f32014-08-21 16:32:194942 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4943 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4944 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:444945
[email protected]6cdfd7f2013-02-08 20:40:154946 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:444947 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:024948 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:444949
[email protected]f288ef02012-12-15 20:28:284950 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:444951
[email protected]6cdfd7f2013-02-08 20:40:154952 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444953 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4954 path = path.Append(FILE_PATH_LITERAL("net"));
4955 path = path.Append(FILE_PATH_LITERAL("data"));
4956 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4957 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:364958 element_readers.push_back(
4959 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4960 path,
4961 0,
4962 kuint64max,
4963 base::Time()));
mmenkecbc2b712014-10-09 20:29:074964 r->set_upload(make_scoped_ptr<UploadDataStream>(
4965 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:444966
[email protected]f7022f32014-08-21 16:32:194967 r->Start();
4968 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444969
[email protected]255620da2013-08-19 13:14:294970 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444971
pkasting6b68a162014-12-01 22:10:294972 int64 size64 = 0;
4973 ASSERT_EQ(true, base::GetFileSize(path, &size64));
4974 ASSERT_LE(size64, std::numeric_limits<int>::max());
4975 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:174976 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:444977
[email protected]7600d0b2013-12-08 21:43:304978 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:444979
[email protected]329b68b2012-11-14 17:54:274980 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:194981 << "request failed: " << r->status().status()
4982 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:444983
4984 EXPECT_FALSE(d.received_data_before_response());
4985
[email protected]329b68b2012-11-14 17:54:274986 EXPECT_EQ(size, d.bytes_received());
4987 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:444988 }
4989}
4990
[email protected]999dd8c2013-11-12 06:45:544991TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4992 ASSERT_TRUE(test_server_.Start());
4993
4994 TestDelegate d;
4995 {
[email protected]f7022f32014-08-21 16:32:194996 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4997 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
4998 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:544999
5000 ScopedVector<UploadElementReader> element_readers;
5001
5002 element_readers.push_back(new UploadFileElementReader(
5003 base::MessageLoopProxy::current().get(),
5004 base::FilePath(FILE_PATH_LITERAL(
5005 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5006 0,
5007 kuint64max,
5008 base::Time()));
mmenkecbc2b712014-10-09 20:29:075009 r->set_upload(make_scoped_ptr<UploadDataStream>(
5010 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545011
[email protected]f7022f32014-08-21 16:32:195012 r->Start();
5013 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545014
5015 base::RunLoop().Run();
5016
[email protected]999dd8c2013-11-12 06:45:545017 EXPECT_TRUE(d.request_failed());
5018 EXPECT_FALSE(d.received_data_before_response());
5019 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195020 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5021 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545022 }
5023}
5024
[email protected]316c1e5e2012-09-12 15:17:445025TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5026 ASSERT_TRUE(test_server_.Start());
5027
5028 TestDelegate d;
5029 {
[email protected]f7022f32014-08-21 16:32:195030 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5031 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5032 r->EnableChunkedUpload();
5033 r->set_method("POST");
5034 AddChunksToUpload(r.get());
5035 r->Start();
5036 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445037
[email protected]255620da2013-08-19 13:14:295038 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445039
[email protected]f7022f32014-08-21 16:32:195040 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445041 }
5042}
5043
[email protected]329b68b2012-11-14 17:54:275044TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5045 ASSERT_TRUE(test_server_.Start());
5046
5047 TestDelegate d;
5048 {
[email protected]f7022f32014-08-21 16:32:195049 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5050 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5051 r->EnableChunkedUpload();
5052 r->set_method("POST");
5053 r->Start();
5054 EXPECT_TRUE(r->is_pending());
5055 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295056 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275057
[email protected]f7022f32014-08-21 16:32:195058 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275059 }
5060}
5061
[email protected]316c1e5e2012-09-12 15:17:445062TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5063 ASSERT_TRUE(test_server_.Start());
5064
5065 TestDelegate d;
5066 {
[email protected]f7022f32014-08-21 16:32:195067 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5068 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5069 r->EnableChunkedUpload();
5070 r->set_method("POST");
5071 r->Start();
5072 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445073
[email protected]255620da2013-08-19 13:14:295074 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195075 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295076 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445077
[email protected]f7022f32014-08-21 16:32:195078 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445079 }
5080}
5081
5082TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5083 ASSERT_TRUE(test_server_.Start());
5084
5085 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195086 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5087 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
5088 NULL));
5089 req->Start();
[email protected]255620da2013-08-19 13:14:295090 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445091
[email protected]f7022f32014-08-21 16:32:195092 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445093
5094 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195095 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445096
5097 std::string header;
5098 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5099 EXPECT_EQ("private", header);
5100
5101 header.clear();
5102 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5103 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5104
5105 // The response has two "X-Multiple-Entries" headers.
5106 // This verfies our output has them concatenated together.
5107 header.clear();
5108 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5109 EXPECT_EQ("a, b", header);
5110}
5111
[email protected]242d8562012-10-30 21:20:465112TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:225113 SpawnedTestServer::SSLOptions ssl_options;
5114 SpawnedTestServer https_test_server(
5115 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465116 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155117 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465118 ASSERT_TRUE(https_test_server.Start());
5119
5120 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195121 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5122 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
5123 NULL));
5124 request->Start();
[email protected]255620da2013-08-19 13:14:295125 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465126
5127 TransportSecurityState* security_state =
5128 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465129 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265130 EXPECT_TRUE(security_state->GetDynamicDomainState(
5131 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465132 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265133 domain_state.sts.upgrade_mode);
5134 EXPECT_TRUE(domain_state.sts.include_subdomains);
5135 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275136#if defined(OS_ANDROID)
5137 // Android's CertVerifyProc does not (yet) handle pins.
5138#else
5139 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5140#endif
5141}
5142
5143// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5144// reject HPKP headers, and a test setting only HPKP headers will fail (no
5145// DomainState present because header rejected).
5146#if defined(OS_ANDROID)
5147#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5148#else
5149#define MAYBE_ProcessPKP ProcessPKP
5150#endif
5151
5152// Tests that enabling HPKP on a domain does not affect the HSTS
5153// validity/expiration.
5154TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5155 SpawnedTestServer::SSLOptions ssl_options;
5156 SpawnedTestServer https_test_server(
5157 SpawnedTestServer::TYPE_HTTPS,
5158 ssl_options,
5159 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5160 ASSERT_TRUE(https_test_server.Start());
5161
5162 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195163 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5164 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5165 NULL));
5166 request->Start();
[email protected]255620da2013-08-19 13:14:295167 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275168
5169 TransportSecurityState* security_state =
5170 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275171 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265172 EXPECT_TRUE(security_state->GetDynamicDomainState(
5173 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275174 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265175 domain_state.sts.upgrade_mode);
5176 EXPECT_FALSE(domain_state.sts.include_subdomains);
5177 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275178 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265179 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465180}
5181
5182TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:225183 SpawnedTestServer::SSLOptions ssl_options;
5184 SpawnedTestServer https_test_server(
5185 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465186 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155187 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465188 ASSERT_TRUE(https_test_server.Start());
5189
5190 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195191 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465192 https_test_server.GetURL("files/hsts-multiple-headers.html"),
[email protected]f7022f32014-08-21 16:32:195193 DEFAULT_PRIORITY, &d, NULL));
5194 request->Start();
[email protected]255620da2013-08-19 13:14:295195 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465196
5197 // We should have set parameters from the first header, not the second.
5198 TransportSecurityState* security_state =
5199 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465200 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265201 EXPECT_TRUE(security_state->GetDynamicDomainState(
5202 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465203 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265204 domain_state.sts.upgrade_mode);
5205 EXPECT_FALSE(domain_state.sts.include_subdomains);
5206 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465207}
5208
[email protected]9f972ec2013-04-10 20:24:365209TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:225210 SpawnedTestServer::SSLOptions ssl_options;
5211 SpawnedTestServer https_test_server(
5212 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365213 ssl_options,
5214 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5215 ASSERT_TRUE(https_test_server.Start());
5216
5217 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195218 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365219 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
[email protected]f7022f32014-08-21 16:32:195220 DEFAULT_PRIORITY, &d, NULL));
5221 request->Start();
[email protected]255620da2013-08-19 13:14:295222 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365223
5224 // We should have set parameters from the first header, not the second.
5225 TransportSecurityState* security_state =
5226 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365227 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265228 EXPECT_TRUE(security_state->GetDynamicDomainState(
5229 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365230 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265231 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365232#if defined(OS_ANDROID)
5233 // Android's CertVerifyProc does not (yet) handle pins.
5234#else
5235 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5236#endif
[email protected]9e6968d2014-05-07 21:46:265237 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365238
[email protected]a165f092013-06-12 16:10:055239 // Even though there is an HSTS header asserting includeSubdomains, it is
5240 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265241 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055242 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265243 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365244}
5245
[email protected]37fd55fb2013-06-29 13:13:275246// Tests that when multiple HPKP headers are present, asserting different
5247// policies, that only the first such policy is processed.
5248TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5249 SpawnedTestServer::SSLOptions ssl_options;
5250 SpawnedTestServer https_test_server(
5251 SpawnedTestServer::TYPE_HTTPS,
5252 ssl_options,
5253 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5254 ASSERT_TRUE(https_test_server.Start());
5255
5256 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195257 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275258 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
[email protected]f7022f32014-08-21 16:32:195259 DEFAULT_PRIORITY, &d, NULL));
5260 request->Start();
[email protected]255620da2013-08-19 13:14:295261 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275262
5263 TransportSecurityState* security_state =
5264 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275265 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265266 EXPECT_TRUE(security_state->GetDynamicDomainState(
5267 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275268 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265269 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275270#if defined(OS_ANDROID)
5271 // Android's CertVerifyProc does not (yet) handle pins.
5272#else
5273 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5274#endif
[email protected]9e6968d2014-05-07 21:46:265275 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275276
[email protected]9e6968d2014-05-07 21:46:265277 EXPECT_TRUE(domain_state.sts.include_subdomains);
5278 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275279}
5280
[email protected]316c1e5e2012-09-12 15:17:445281TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5282 ASSERT_TRUE(test_server_.Start());
5283
5284 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195285 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5286 test_server_.GetURL("files/content-type-normalization.html"),
5287 DEFAULT_PRIORITY, &d, NULL));
5288 req->Start();
[email protected]255620da2013-08-19 13:14:295289 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445290
5291 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195292 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445293 EXPECT_EQ("text/html", mime_type);
5294
5295 std::string charset;
[email protected]f7022f32014-08-21 16:32:195296 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445297 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195298 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445299}
5300
[email protected]02494ec2014-05-07 15:05:295301TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345302 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345303 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345304 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025305 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345306
5307 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505308 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345309}
5310
[email protected]02494ec2014-05-07 15:05:295311#if !defined(DISABLE_FILE_SUPPORT)
5312TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5313 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5314 GURL file_url("file:///foo.txt");
5315 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5316 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5317
5318 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505319 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295320}
5321
[email protected]588614c22013-08-16 00:09:025322TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445323 ASSERT_TRUE(test_server_.Start());
5324
5325 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195326 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5327 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY, &d,
5328 NULL));
5329 req->Start();
[email protected]255620da2013-08-19 13:14:295330 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445331
[email protected]f7022f32014-08-21 16:32:195332 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5333 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445334}
[email protected]02494ec2014-05-07 15:05:295335#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445336
[email protected]588614c22013-08-16 00:09:025337TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5338 ASSERT_TRUE(test_server_.Start());
5339
5340 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195341 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5342 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY, &d,
5343 NULL));
5344 req->Start();
[email protected]588614c22013-08-16 00:09:025345 base::MessageLoop::current()->Run();
5346
[email protected]f7022f32014-08-21 16:32:195347 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5348 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025349}
5350
[email protected]316c1e5e2012-09-12 15:17:445351TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5352 ASSERT_TRUE(test_server_.Start());
5353
5354 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195355 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5356 test_server_.GetURL("files/redirect-to-invalid-url.html"),
5357 DEFAULT_PRIORITY, &d, NULL));
5358 req->Start();
[email protected]255620da2013-08-19 13:14:295359 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445360
[email protected]f7022f32014-08-21 16:32:195361 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5362 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445363}
5364
[email protected]e50efea2014-03-24 18:41:005365// Make sure redirects are cached, despite not reading their bodies.
5366TEST_F(URLRequestTestHTTP, CacheRedirect) {
5367 ASSERT_TRUE(test_server_.Start());
5368 GURL redirect_url =
5369 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5370
5371 {
5372 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195373 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5374 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5375 req->Start();
[email protected]e50efea2014-03-24 18:41:005376 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195377 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005378 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195379 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005380 }
5381
5382 {
5383 TestDelegate d;
5384 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:195385 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5386 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5387 req->Start();
[email protected]e50efea2014-03-24 18:41:005388 base::RunLoop().Run();
5389
5390 EXPECT_EQ(1, d.received_redirect_count());
5391 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195392 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005393
[email protected]f7022f32014-08-21 16:32:195394 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005395 base::RunLoop().Run();
5396 EXPECT_EQ(1, d.received_redirect_count());
5397 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195398 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5399 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005400 }
5401}
5402
5403// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5404// when the headers are read, since the body won't have been read.
5405TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5406 ASSERT_TRUE(test_server_.Start());
5407 // URL that is normally cached.
5408 GURL initial_url = test_server_.GetURL("cachetime");
5409
5410 {
5411 // Set up the TestNetworkDelegate tp force a redirect.
5412 GURL redirect_to_url = test_server_.GetURL("echo");
5413 default_network_delegate_.set_redirect_on_headers_received_url(
5414 redirect_to_url);
5415
5416 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195417 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5418 initial_url, DEFAULT_PRIORITY, &d, NULL));
5419 req->Start();
[email protected]e50efea2014-03-24 18:41:005420 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195421 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005422 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195423 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005424 }
5425
5426 {
5427 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195428 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5429 initial_url, DEFAULT_PRIORITY, &d, NULL));
5430 req->Start();
[email protected]e50efea2014-03-24 18:41:005431 base::RunLoop().Run();
5432
[email protected]f7022f32014-08-21 16:32:195433 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5434 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005435 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195436 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005437 }
5438}
5439
[email protected]5f714132014-03-26 10:41:165440// Tests that redirection to an unsafe URL is allowed when it has been marked as
5441// safe.
5442TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5443 ASSERT_TRUE(test_server_.Start());
5444
5445 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5446 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5447 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5448
5449 TestDelegate d;
5450 {
[email protected]f7022f32014-08-21 16:32:195451 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5452 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165453
[email protected]f7022f32014-08-21 16:32:195454 r->Start();
[email protected]5f714132014-03-26 10:41:165455 base::RunLoop().Run();
5456
[email protected]f7022f32014-08-21 16:32:195457 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165458
[email protected]f7022f32014-08-21 16:32:195459 EXPECT_EQ(2U, r->url_chain().size());
5460 EXPECT_EQ(OK, r->status().error());
5461 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165462 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5463 }
5464}
5465
5466// Tests that a redirect to a different unsafe URL is blocked, even after adding
5467// some other URL to the whitelist.
5468TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5469 ASSERT_TRUE(test_server_.Start());
5470
5471 GURL unsafe_url("data:text/html,something");
5472 GURL different_unsafe_url("data:text/html,something-else");
5473 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5474 default_network_delegate_.set_allowed_unsafe_redirect_url(
5475 different_unsafe_url);
5476
5477 TestDelegate d;
5478 {
[email protected]f7022f32014-08-21 16:32:195479 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5480 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165481
[email protected]f7022f32014-08-21 16:32:195482 r->Start();
[email protected]5f714132014-03-26 10:41:165483 base::RunLoop().Run();
5484
[email protected]f7022f32014-08-21 16:32:195485 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5486 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165487 }
5488}
5489
[email protected]5f714132014-03-26 10:41:165490// Redirects from an URL with fragment to an unsafe URL with fragment should
5491// be allowed, and the reference fragment of the target URL should be preserved.
5492TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5493 ASSERT_TRUE(test_server_.Start());
5494
5495 GURL original_url(test_server_.GetURL("original#fragment1"));
5496 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5497 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5498
5499 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5500 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5501
5502 TestDelegate d;
5503 {
[email protected]f7022f32014-08-21 16:32:195504 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5505 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165506
[email protected]f7022f32014-08-21 16:32:195507 r->Start();
[email protected]5f714132014-03-26 10:41:165508 base::RunLoop().Run();
5509
[email protected]f7022f32014-08-21 16:32:195510 EXPECT_EQ(2U, r->url_chain().size());
5511 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5512 EXPECT_EQ(OK, r->status().error());
5513 EXPECT_EQ(original_url, r->original_url());
5514 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165515 }
5516}
5517
5518// When a delegate has specified a safe redirect URL, but it does not match the
5519// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145520TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165521 ASSERT_TRUE(test_server_.Start());
5522
5523 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5524 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5525 GURL redirect_url(test_server_.GetURL("target"));
5526 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5527
5528 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5529 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5530
5531 TestDelegate d;
5532 {
[email protected]f7022f32014-08-21 16:32:195533 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5534 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165535
[email protected]f7022f32014-08-21 16:32:195536 r->Start();
[email protected]5f714132014-03-26 10:41:165537 base::RunLoop().Run();
5538
[email protected]f7022f32014-08-21 16:32:195539 EXPECT_EQ(2U, r->url_chain().size());
5540 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5541 EXPECT_EQ(OK, r->status().error());
5542 EXPECT_EQ(original_url, r->original_url());
5543 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165544 }
5545}
5546
[email protected]f878230e2014-04-03 15:36:145547// When a delegate has specified a safe redirect URL, assume that the redirect
5548// URL should not be changed. In particular, the reference fragment should not
5549// be modified.
5550TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5551 ASSERT_TRUE(test_server_.Start());
5552
5553 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5554 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5555
5556 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5557 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5558
5559 TestDelegate d;
5560 {
[email protected]f7022f32014-08-21 16:32:195561 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5562 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:145563
[email protected]f7022f32014-08-21 16:32:195564 r->Start();
[email protected]f878230e2014-04-03 15:36:145565 base::RunLoop().Run();
5566
[email protected]f7022f32014-08-21 16:32:195567 EXPECT_EQ(2U, r->url_chain().size());
5568 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5569 EXPECT_EQ(OK, r->status().error());
5570 EXPECT_EQ(original_url, r->original_url());
5571 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145572 }
5573}
5574
5575// When a URLRequestRedirectJob is created, the redirection must be followed and
5576// the reference fragment of the target URL must not be modified.
5577TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5578 ASSERT_TRUE(test_server_.Start());
5579
5580 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5581 GURL redirect_url(test_server_.GetURL("echo"));
5582
5583 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195584 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5585 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:145586
5587 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195588 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145589 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5590 AddTestInterceptor()->set_main_intercept_job(job);
5591
[email protected]f7022f32014-08-21 16:32:195592 r->Start();
[email protected]f878230e2014-04-03 15:36:145593 base::RunLoop().Run();
5594
[email protected]f7022f32014-08-21 16:32:195595 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5596 EXPECT_EQ(OK, r->status().error());
5597 EXPECT_EQ(original_url, r->original_url());
5598 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145599}
5600
[email protected]316c1e5e2012-09-12 15:17:445601TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5602 ASSERT_TRUE(test_server_.Start());
5603
5604 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195605 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5606 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5607 req->SetReferrer("http://user:[email protected]/");
5608 req->Start();
[email protected]255620da2013-08-19 13:14:295609 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445610
5611 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5612}
5613
[email protected]99ecf6e2013-04-10 22:46:135614TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5615 ASSERT_TRUE(test_server_.Start());
5616
5617 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195618 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5619 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5620 req->SetReferrer("http://foo.com/test#fragment");
5621 req->Start();
[email protected]255620da2013-08-19 13:14:295622 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135623
5624 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5625}
5626
5627TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5628 ASSERT_TRUE(test_server_.Start());
5629
5630 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195631 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5632 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
5633 req->SetReferrer("http://foo.com/test#fragment");
5634 req->SetReferrer("");
5635 req->Start();
[email protected]255620da2013-08-19 13:14:295636 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135637
5638 EXPECT_EQ(std::string("None"), d.data_received());
5639}
5640
[email protected]1826a402014-01-08 15:40:485641// Defer network start and then resume, checking that the request was a success
5642// and bytes were received.
5643TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5644 ASSERT_TRUE(test_server_.Start());
5645
5646 TestDelegate d;
5647 {
5648 d.set_quit_on_network_start(true);
5649 GURL test_url(test_server_.GetURL("echo"));
[email protected]f7022f32014-08-21 16:32:195650 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5651 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]1826a402014-01-08 15:40:485652
[email protected]f7022f32014-08-21 16:32:195653 req->Start();
[email protected]1826a402014-01-08 15:40:485654 base::RunLoop().Run();
5655
5656 EXPECT_EQ(1, d.received_before_network_start_count());
5657 EXPECT_EQ(0, d.response_started_count());
5658
[email protected]f7022f32014-08-21 16:32:195659 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485660 base::RunLoop().Run();
5661
5662 EXPECT_EQ(1, d.response_started_count());
5663 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195664 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485665 }
5666}
5667
5668// Check that OnBeforeNetworkStart is only called once even if there is a
5669// redirect.
5670TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5671 ASSERT_TRUE(test_server_.Start());
5672
5673 TestDelegate d;
5674 {
5675 d.set_quit_on_redirect(true);
5676 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195677 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5678 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d,
5679 NULL));
[email protected]1826a402014-01-08 15:40:485680
[email protected]f7022f32014-08-21 16:32:195681 req->Start();
[email protected]1826a402014-01-08 15:40:485682 base::RunLoop().Run();
5683
5684 EXPECT_EQ(1, d.received_before_network_start_count());
5685 EXPECT_EQ(0, d.response_started_count());
5686 EXPECT_EQ(0, d.received_redirect_count());
5687
[email protected]f7022f32014-08-21 16:32:195688 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485689 base::RunLoop().Run();
5690
5691 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195692 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485693 base::RunLoop().Run();
5694
5695 // Check that the redirect's new network transaction does not get propagated
5696 // to a second OnBeforeNetworkStart() notification.
5697 EXPECT_EQ(1, d.received_before_network_start_count());
5698
5699 EXPECT_EQ(1, d.response_started_count());
5700 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195701 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485702 }
5703}
5704
5705// Cancel the request after learning that the request would use the network.
5706TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5707 ASSERT_TRUE(test_server_.Start());
5708
5709 TestDelegate d;
5710 {
5711 d.set_quit_on_network_start(true);
5712 GURL test_url(test_server_.GetURL("echo"));
[email protected]f7022f32014-08-21 16:32:195713 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5714 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]1826a402014-01-08 15:40:485715
[email protected]f7022f32014-08-21 16:32:195716 req->Start();
[email protected]1826a402014-01-08 15:40:485717 base::RunLoop().Run();
5718
5719 EXPECT_EQ(1, d.received_before_network_start_count());
5720 EXPECT_EQ(0, d.response_started_count());
5721
[email protected]f7022f32014-08-21 16:32:195722 req->Cancel();
[email protected]1826a402014-01-08 15:40:485723 base::RunLoop().Run();
5724
5725 EXPECT_EQ(1, d.response_started_count());
5726 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195727 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485728 }
5729}
5730
[email protected]316c1e5e2012-09-12 15:17:445731TEST_F(URLRequestTestHTTP, CancelRedirect) {
5732 ASSERT_TRUE(test_server_.Start());
5733
5734 TestDelegate d;
5735 {
5736 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195737 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5738 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
5739 NULL));
5740 req->Start();
[email protected]255620da2013-08-19 13:14:295741 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445742
5743 EXPECT_EQ(1, d.response_started_count());
5744 EXPECT_EQ(0, d.bytes_received());
5745 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195746 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445747 }
5748}
5749
5750TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5751 ASSERT_TRUE(test_server_.Start());
5752
5753 TestDelegate d;
5754 {
5755 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045756 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]f7022f32014-08-21 16:32:195757 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5758 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:045759
[email protected]f7022f32014-08-21 16:32:195760 req->Start();
[email protected]255620da2013-08-19 13:14:295761 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445762
5763 EXPECT_EQ(1, d.received_redirect_count());
5764
[email protected]f7022f32014-08-21 16:32:195765 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295766 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445767
5768 EXPECT_EQ(1, d.response_started_count());
5769 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195770 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445771
[email protected]6cdfd7f2013-02-08 20:40:155772 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445773 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5774 path = path.Append(FILE_PATH_LITERAL("net"));
5775 path = path.Append(FILE_PATH_LITERAL("data"));
5776 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5777 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5778
5779 std::string contents;
[email protected]82f84b92013-08-30 18:23:505780 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445781 EXPECT_EQ(contents, d.data_received());
5782 }
5783}
5784
[email protected]79e1fd62013-06-20 06:50:045785TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5786 ASSERT_TRUE(test_server_.Start());
5787
5788 TestDelegate d;
5789 {
5790 d.set_quit_on_redirect(true);
5791 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]f7022f32014-08-21 16:32:195792 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5793 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:045794
5795 EXPECT_FALSE(d.have_full_request_headers());
5796
[email protected]f7022f32014-08-21 16:32:195797 req->Start();
[email protected]255620da2013-08-19 13:14:295798 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045799
5800 EXPECT_EQ(1, d.received_redirect_count());
5801 EXPECT_TRUE(d.have_full_request_headers());
5802 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5803 d.ClearFullRequestHeaders();
5804
[email protected]f7022f32014-08-21 16:32:195805 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295806 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045807
5808 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5809 EXPECT_EQ(1, d.response_started_count());
5810 EXPECT_TRUE(d.have_full_request_headers());
5811 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5812 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195813 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:045814
5815 base::FilePath path;
5816 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5817 path = path.Append(FILE_PATH_LITERAL("net"));
5818 path = path.Append(FILE_PATH_LITERAL("data"));
5819 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5820 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5821
5822 std::string contents;
[email protected]82f84b92013-08-30 18:23:505823 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045824 EXPECT_EQ(contents, d.data_received());
5825 }
5826}
5827
[email protected]316c1e5e2012-09-12 15:17:445828TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5829 ASSERT_TRUE(test_server_.Start());
5830
5831 TestDelegate d;
5832 {
5833 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:195834 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5835 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
5836 NULL));
5837 req->Start();
[email protected]255620da2013-08-19 13:14:295838 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445839
5840 EXPECT_EQ(1, d.received_redirect_count());
5841
[email protected]f7022f32014-08-21 16:32:195842 req->Cancel();
[email protected]255620da2013-08-19 13:14:295843 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445844
5845 EXPECT_EQ(1, d.response_started_count());
5846 EXPECT_EQ(0, d.bytes_received());
5847 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195848 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445849 }
5850}
5851
5852TEST_F(URLRequestTestHTTP, VaryHeader) {
5853 ASSERT_TRUE(test_server_.Start());
5854
[email protected]3b23a222013-05-15 21:33:255855 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445856 {
5857 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195858 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5859 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5860 NULL));
[email protected]316c1e5e2012-09-12 15:17:445861 HttpRequestHeaders headers;
5862 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:195863 req->SetExtraRequestHeaders(headers);
5864 req->Start();
[email protected]255620da2013-08-19 13:14:295865 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255866
5867 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195868 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255869 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445870 }
5871
[email protected]3b23a222013-05-15 21:33:255872 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445873 {
5874 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195875 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5876 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5877 NULL));
[email protected]316c1e5e2012-09-12 15:17:445878 HttpRequestHeaders headers;
5879 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:195880 req->SetExtraRequestHeaders(headers);
5881 req->Start();
[email protected]255620da2013-08-19 13:14:295882 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445883
[email protected]f7022f32014-08-21 16:32:195884 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:255885
5886 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195887 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255888 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445889 }
5890
[email protected]3b23a222013-05-15 21:33:255891 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445892 {
5893 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195894 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5895 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
5896 NULL));
[email protected]316c1e5e2012-09-12 15:17:445897 HttpRequestHeaders headers;
5898 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:195899 req->SetExtraRequestHeaders(headers);
5900 req->Start();
[email protected]255620da2013-08-19 13:14:295901 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445902
[email protected]f7022f32014-08-21 16:32:195903 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:255904
5905 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195906 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255907 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445908 }
5909}
5910
5911TEST_F(URLRequestTestHTTP, BasicAuth) {
5912 ASSERT_TRUE(test_server_.Start());
5913
5914 // populate the cache
5915 {
5916 TestDelegate d;
5917 d.set_credentials(AuthCredentials(kUser, kSecret));
5918
[email protected]f7022f32014-08-21 16:32:195919 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5920 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5921 r->Start();
[email protected]316c1e5e2012-09-12 15:17:445922
[email protected]255620da2013-08-19 13:14:295923 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445924
5925 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5926 }
5927
5928 // repeat request with end-to-end validation. since auth-basic results in a
5929 // cachable page, we expect this test to result in a 304. in which case, the
5930 // response should be fetched from the cache.
5931 {
5932 TestDelegate d;
5933 d.set_credentials(AuthCredentials(kUser, kSecret));
5934
[email protected]f7022f32014-08-21 16:32:195935 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5936 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
5937 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
5938 r->Start();
[email protected]316c1e5e2012-09-12 15:17:445939
[email protected]255620da2013-08-19 13:14:295940 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445941
5942 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5943
5944 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:195945 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:445946 }
5947}
5948
5949// Check that Set-Cookie headers in 401 responses are respected.
5950// http://crbug.com/6450
5951TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5952 ASSERT_TRUE(test_server_.Start());
5953
5954 GURL url_requiring_auth =
5955 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5956
5957 // Request a page that will give a 401 containing a Set-Cookie header.
5958 // Verify that when the transaction is restarted, it includes the new cookie.
5959 {
[email protected]ceefd7fd2012-11-29 00:36:245960 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445961 TestURLRequestContext context(true);
5962 context.set_network_delegate(&network_delegate);
5963 context.Init();
5964
5965 TestDelegate d;
5966 d.set_credentials(AuthCredentials(kUser, kSecret));
5967
[email protected]f7022f32014-08-21 16:32:195968 scoped_ptr<URLRequest> r(context.CreateRequest(
5969 url_requiring_auth, DEFAULT_PRIORITY, &d, NULL));
5970 r->Start();
[email protected]316c1e5e2012-09-12 15:17:445971
[email protected]255620da2013-08-19 13:14:295972 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445973
5974 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5975
5976 // Make sure we sent the cookie in the restarted transaction.
5977 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5978 != std::string::npos);
5979 }
5980
5981 // Same test as above, except this time the restart is initiated earlier
5982 // (without user intervention since identity is embedded in the URL).
5983 {
[email protected]ceefd7fd2012-11-29 00:36:245984 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445985 TestURLRequestContext context(true);
5986 context.set_network_delegate(&network_delegate);
5987 context.Init();
5988
5989 TestDelegate d;
5990
5991 GURL::Replacements replacements;
5992 std::string username("user2");
5993 std::string password("secret");
5994 replacements.SetUsernameStr(username);
5995 replacements.SetPasswordStr(password);
5996 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5997
[email protected]f7022f32014-08-21 16:32:195998 scoped_ptr<URLRequest> r(context.CreateRequest(
5999 url_with_identity, DEFAULT_PRIORITY, &d, NULL));
6000 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446001
[email protected]255620da2013-08-19 13:14:296002 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446003
6004 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6005
6006 // Make sure we sent the cookie in the restarted transaction.
6007 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6008 != std::string::npos);
6009 }
6010}
6011
[email protected]58e32bb2013-01-21 18:23:256012// Tests that load timing works as expected with auth and the cache.
6013TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6014 ASSERT_TRUE(test_server_.Start());
6015
6016 // populate the cache
6017 {
6018 TestDelegate d;
6019 d.set_credentials(AuthCredentials(kUser, kSecret));
6020
[email protected]f7022f32014-08-21 16:32:196021 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6022 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6023 r->Start();
[email protected]58e32bb2013-01-21 18:23:256024
[email protected]255620da2013-08-19 13:14:296025 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256026
6027 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6028
6029 LoadTimingInfo load_timing_info_before_auth;
6030 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6031 &load_timing_info_before_auth));
6032 TestLoadTimingNotReused(load_timing_info_before_auth,
6033 CONNECT_TIMING_HAS_DNS_TIMES);
6034
6035 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196036 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256037 // The test server does not support keep alive sockets, so the second
6038 // request with auth should use a new socket.
6039 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6040 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6041 load_timing_info.socket_log_id);
6042 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6043 load_timing_info.connect_timing.connect_start);
6044 }
6045
[email protected]3b23a222013-05-15 21:33:256046 // Repeat request with end-to-end validation. Since auth-basic results in a
6047 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256048 // response should be fetched from the cache.
6049 {
6050 TestDelegate d;
6051 d.set_credentials(AuthCredentials(kUser, kSecret));
6052
[email protected]f7022f32014-08-21 16:32:196053 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6054 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6055 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6056 r->Start();
[email protected]58e32bb2013-01-21 18:23:256057
[email protected]255620da2013-08-19 13:14:296058 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256059
6060 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6061
6062 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196063 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256064
[email protected]3b23a222013-05-15 21:33:256065 // Since there was a request that went over the wire, the load timing
6066 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256067 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196068 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256069 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256070 }
6071}
6072
[email protected]316c1e5e2012-09-12 15:17:446073// In this test, we do a POST which the server will 302 redirect.
6074// The subsequent transaction should use GET, and should not send the
6075// Content-Type header.
6076// http://code.google.com/p/chromium/issues/detail?id=843
6077TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6078 ASSERT_TRUE(test_server_.Start());
6079
6080 const char kData[] = "hello world";
6081
6082 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196083 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6084 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
6085 NULL));
6086 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076087 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446088
6089 // Set headers (some of which are specific to the POST).
6090 HttpRequestHeaders headers;
6091 headers.AddHeadersFromString(
6092 "Content-Type: multipart/form-data; "
6093 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6094 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6095 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6096 "Accept-Language: en-US,en\r\n"
6097 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6098 "Content-Length: 11\r\n"
6099 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196100 req->SetExtraRequestHeaders(headers);
6101 req->Start();
[email protected]255620da2013-08-19 13:14:296102 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446103
6104 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196105 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446106 EXPECT_EQ("text/html", mime_type);
6107
6108 const std::string& data = d.data_received();
6109
6110 // Check that the post-specific headers were stripped:
6111 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6112 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6113 EXPECT_FALSE(ContainsString(data, "Origin:"));
6114
6115 // These extra request headers should not have been stripped.
6116 EXPECT_TRUE(ContainsString(data, "Accept:"));
6117 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6118 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6119}
6120
6121// The following tests check that we handle mutating the request method for
6122// HTTP redirects as expected.
6123// See http://crbug.com/56373 and http://crbug.com/102130.
6124
6125TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6126 ASSERT_TRUE(test_server_.Start());
6127
6128 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6129
6130 HTTPRedirectMethodTest(url, "POST", "GET", true);
6131 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6132 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6133}
6134
6135TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6136 ASSERT_TRUE(test_server_.Start());
6137
6138 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6139
6140 HTTPRedirectMethodTest(url, "POST", "GET", true);
6141 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6142 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6143}
6144
6145TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6146 ASSERT_TRUE(test_server_.Start());
6147
6148 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6149
6150 HTTPRedirectMethodTest(url, "POST", "GET", true);
6151 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6152 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6153}
6154
6155TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6156 ASSERT_TRUE(test_server_.Start());
6157
6158 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6159
6160 HTTPRedirectMethodTest(url, "POST", "POST", true);
6161 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6162 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6163}
6164
[email protected]0a17aab32014-04-24 03:32:376165TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6166 ASSERT_TRUE(test_server_.Start());
6167
6168 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6169
6170 HTTPRedirectMethodTest(url, "POST", "POST", true);
6171 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6172 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6173}
6174
6175// Make sure that 308 responses without bodies are not treated as redirects.
6176// Certain legacy apis that pre-date the response code expect this behavior
6177// (Like Google Drive).
6178TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6179 ASSERT_TRUE(test_server_.Start());
6180
6181 TestDelegate d;
6182 const GURL url = test_server_.GetURL("files/308-without-location-header");
6183
[email protected]f7022f32014-08-21 16:32:196184 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
6185 url, DEFAULT_PRIORITY, &d, NULL));
[email protected]0a17aab32014-04-24 03:32:376186
[email protected]f7022f32014-08-21 16:32:196187 request->Start();
[email protected]0a17aab32014-04-24 03:32:376188 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196189 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6190 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376191 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196192 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376193 EXPECT_EQ("This is not a redirect.", d.data_received());
6194}
6195
[email protected]f878230e2014-04-03 15:36:146196TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6197 ASSERT_TRUE(test_server_.Start());
6198
6199 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6200 GURL expected_url(test_server_.GetURL("echo#fragment"));
6201
6202 TestDelegate d;
6203 {
[email protected]f7022f32014-08-21 16:32:196204 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6205 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:146206
[email protected]f7022f32014-08-21 16:32:196207 r->Start();
[email protected]f878230e2014-04-03 15:36:146208 base::RunLoop().Run();
6209
[email protected]f7022f32014-08-21 16:32:196210 EXPECT_EQ(2U, r->url_chain().size());
6211 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6212 EXPECT_EQ(OK, r->status().error());
6213 EXPECT_EQ(original_url, r->original_url());
6214 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146215 }
6216}
6217
[email protected]cba24642014-08-15 20:49:596218TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6219 ASSERT_TRUE(test_server_.Start());
6220
6221 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6222 GURL first_party_url("http://example.com");
6223
6224 TestDelegate d;
6225 {
[email protected]f7022f32014-08-21 16:32:196226 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6227 url, DEFAULT_PRIORITY, &d, NULL));
6228 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596229
[email protected]f7022f32014-08-21 16:32:196230 r->Start();
[email protected]cba24642014-08-15 20:49:596231 base::RunLoop().Run();
6232
[email protected]f7022f32014-08-21 16:32:196233 EXPECT_EQ(2U, r->url_chain().size());
6234 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6235 EXPECT_EQ(OK, r->status().error());
6236 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596237 }
6238}
6239
6240TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6241 ASSERT_TRUE(test_server_.Start());
6242
6243 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6244 GURL original_first_party_url("http://example.com");
6245 GURL expected_first_party_url(test_server_.GetURL("echo"));
6246
6247 TestDelegate d;
6248 {
[email protected]f7022f32014-08-21 16:32:196249 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6250 url, DEFAULT_PRIORITY, &d, NULL));
6251 r->set_first_party_for_cookies(original_first_party_url);
6252 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596253 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6254
[email protected]f7022f32014-08-21 16:32:196255 r->Start();
[email protected]cba24642014-08-15 20:49:596256 base::RunLoop().Run();
6257
[email protected]f7022f32014-08-21 16:32:196258 EXPECT_EQ(2U, r->url_chain().size());
6259 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6260 EXPECT_EQ(OK, r->status().error());
6261 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596262 }
6263}
6264
[email protected]316c1e5e2012-09-12 15:17:446265TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6266 ASSERT_TRUE(test_server_.Start());
6267
6268 const char kData[] = "hello world";
6269
6270 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196271 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6272 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6273 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076274 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446275 HttpRequestHeaders headers;
6276 headers.SetHeader(HttpRequestHeaders::kContentLength,
6277 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196278 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446279
6280 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196281 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096282 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446283 AddTestInterceptor()->set_main_intercept_job(job);
6284
[email protected]f7022f32014-08-21 16:32:196285 req->Start();
[email protected]255620da2013-08-19 13:14:296286 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196287 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446288}
6289
6290TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6291 ASSERT_TRUE(test_server_.Start());
6292
6293 const char kData[] = "hello world";
6294
6295 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196296 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6297 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6298 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076299 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446300 HttpRequestHeaders headers;
6301 headers.SetHeader(HttpRequestHeaders::kContentLength,
6302 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196303 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446304
6305 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196306 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096307 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6308 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446309 AddTestInterceptor()->set_main_intercept_job(job);
6310
[email protected]f7022f32014-08-21 16:32:196311 req->Start();
[email protected]255620da2013-08-19 13:14:296312 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196313 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446314 EXPECT_EQ(kData, d.data_received());
6315}
6316
6317// Check that default A-L header is sent.
6318TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6319 ASSERT_TRUE(test_server_.Start());
6320
[email protected]8790210c2013-12-02 05:29:536321 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246322 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446323 TestURLRequestContext context(true);
6324 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436325 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446326 context.Init();
6327
6328 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196329 scoped_ptr<URLRequest> req(context.CreateRequest(
6330 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6331 NULL));
6332 req->Start();
[email protected]255620da2013-08-19 13:14:296333 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446334 EXPECT_EQ("en", d.data_received());
6335}
6336
6337// Check that an empty A-L header is not sent. http://crbug.com/77365.
6338TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6339 ASSERT_TRUE(test_server_.Start());
6340
[email protected]8790210c2013-12-02 05:29:536341 std::string empty_string; // Avoid most vexing parse on line below.
6342 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246343 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446344 TestURLRequestContext context(true);
6345 context.set_network_delegate(&network_delegate);
6346 context.Init();
6347 // We override the language after initialization because empty entries
6348 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436349 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446350
6351 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196352 scoped_ptr<URLRequest> req(context.CreateRequest(
6353 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6354 NULL));
6355 req->Start();
[email protected]255620da2013-08-19 13:14:296356 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446357 EXPECT_EQ("None", d.data_received());
6358}
6359
6360// Check that if request overrides the A-L header, the default is not appended.
6361// See http://crbug.com/20894
6362TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6363 ASSERT_TRUE(test_server_.Start());
6364
6365 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196366 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6367 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6368 NULL));
[email protected]316c1e5e2012-09-12 15:17:446369 HttpRequestHeaders headers;
6370 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196371 req->SetExtraRequestHeaders(headers);
6372 req->Start();
[email protected]255620da2013-08-19 13:14:296373 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446374 EXPECT_EQ(std::string("ru"), d.data_received());
6375}
6376
6377// Check that default A-E header is sent.
6378TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6379 ASSERT_TRUE(test_server_.Start());
6380
6381 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196382 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6383 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6384 NULL));
[email protected]316c1e5e2012-09-12 15:17:446385 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196386 req->SetExtraRequestHeaders(headers);
6387 req->Start();
[email protected]255620da2013-08-19 13:14:296388 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446389 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6390}
6391
6392// Check that if request overrides the A-E header, the default is not appended.
6393// See http://crbug.com/47381
6394TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6395 ASSERT_TRUE(test_server_.Start());
6396
6397 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196398 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6399 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6400 NULL));
[email protected]316c1e5e2012-09-12 15:17:446401 HttpRequestHeaders headers;
6402 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196403 req->SetExtraRequestHeaders(headers);
6404 req->Start();
[email protected]255620da2013-08-19 13:14:296405 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446406 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6407 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6408}
6409
[email protected]84f05432013-03-15 01:00:126410// Check that setting the A-C header sends the proper header.
6411TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446412 ASSERT_TRUE(test_server_.Start());
6413
6414 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196415 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6416 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d,
6417 NULL));
[email protected]316c1e5e2012-09-12 15:17:446418 HttpRequestHeaders headers;
6419 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196420 req->SetExtraRequestHeaders(headers);
6421 req->Start();
[email protected]255620da2013-08-19 13:14:296422 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446423 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6424}
6425
6426// Check that default User-Agent header is sent.
6427TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6428 ASSERT_TRUE(test_server_.Start());
6429
6430 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196431 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6432 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6433 NULL));
6434 req->Start();
[email protected]255620da2013-08-19 13:14:296435 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196436 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376437 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446438}
6439
6440// Check that if request overrides the User-Agent header,
6441// the default is not appended.
6442TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6443 ASSERT_TRUE(test_server_.Start());
6444
6445 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196446 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6447 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6448 NULL));
[email protected]316c1e5e2012-09-12 15:17:446449 HttpRequestHeaders headers;
6450 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196451 req->SetExtraRequestHeaders(headers);
6452 req->Start();
[email protected]255620da2013-08-19 13:14:296453 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356454 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446455}
6456
[email protected]ee4c30d2012-11-07 15:08:436457// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6458// User-Agent header to be sent but does not send the Accept-Language and
6459// Accept-Charset headers.
6460TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6461 ASSERT_TRUE(test_server_.Start());
6462
[email protected]ceefd7fd2012-11-29 00:36:246463 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436464 TestURLRequestContext context(true);
6465 context.set_network_delegate(&network_delegate);
6466 context.Init();
6467 // We override the HttpUserAgentSettings after initialization because empty
6468 // entries get overridden by Init().
6469 context.set_http_user_agent_settings(NULL);
6470
6471 struct {
6472 const char* request;
6473 const char* expected_response;
6474 } tests[] = { { "echoheader?Accept-Language", "None" },
6475 { "echoheader?Accept-Charset", "None" },
6476 { "echoheader?User-Agent", "" } };
6477
viettrungluue4a8b882014-10-16 06:17:386478 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436479 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196480 scoped_ptr<URLRequest> req(context.CreateRequest(
6481 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
6482 req->Start();
[email protected]255620da2013-08-19 13:14:296483 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436484 EXPECT_EQ(tests[i].expected_response, d.data_received())
6485 << " Request = \"" << tests[i].request << "\"";
6486 }
6487}
6488
[email protected]5033ab82013-03-22 20:17:466489// Make sure that URLRequest passes on its priority updates to
6490// newly-created jobs after the first one.
6491TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6492 ASSERT_TRUE(test_server_.Start());
6493
6494 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196495 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6496 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6497 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466498
6499 scoped_refptr<URLRequestRedirectJob> redirect_job =
6500 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196501 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096502 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506503 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466504
[email protected]f7022f32014-08-21 16:32:196505 req->SetPriority(LOW);
6506 req->Start();
6507 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466508
6509 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196510 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506511 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466512
6513 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296514 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466515 EXPECT_EQ(LOW, job->priority());
6516}
6517
[email protected]80abdad2014-03-15 00:20:546518// Check that creating a network request while entering/exiting suspend mode
6519// fails as it should. This is the only case where an HttpTransactionFactory
6520// does not return an HttpTransaction.
6521TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6522 // Create a new HttpNetworkLayer that thinks it's suspended.
6523 HttpNetworkSession::Params params;
6524 params.host_resolver = default_context_.host_resolver();
6525 params.cert_verifier = default_context_.cert_verifier();
6526 params.transport_security_state = default_context_.transport_security_state();
6527 params.proxy_service = default_context_.proxy_service();
6528 params.ssl_config_service = default_context_.ssl_config_service();
6529 params.http_auth_handler_factory =
6530 default_context_.http_auth_handler_factory();
6531 params.network_delegate = &default_network_delegate_;
6532 params.http_server_properties = default_context_.http_server_properties();
6533 scoped_ptr<HttpNetworkLayer> network_layer(
6534 new HttpNetworkLayer(new HttpNetworkSession(params)));
6535 network_layer->OnSuspend();
6536
6537 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6538 HttpCache::DefaultBackend::InMemory(0));
6539
6540 TestURLRequestContext context(true);
6541 context.set_http_transaction_factory(&http_cache);
6542 context.Init();
6543
6544 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196545 scoped_ptr<URLRequest> req(context.CreateRequest(
6546 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
6547 req->Start();
[email protected]80abdad2014-03-15 00:20:546548 base::RunLoop().Run();
6549
6550 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196551 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6552 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546553}
6554
6555// Check that creating a network request while entering/exiting suspend mode
6556// fails as it should in the case there is no cache. This is the only case
6557// where an HttpTransactionFactory does not return an HttpTransaction.
6558TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6559 // Create a new HttpNetworkLayer that thinks it's suspended.
6560 HttpNetworkSession::Params params;
6561 params.host_resolver = default_context_.host_resolver();
6562 params.cert_verifier = default_context_.cert_verifier();
6563 params.transport_security_state = default_context_.transport_security_state();
6564 params.proxy_service = default_context_.proxy_service();
6565 params.ssl_config_service = default_context_.ssl_config_service();
6566 params.http_auth_handler_factory =
6567 default_context_.http_auth_handler_factory();
6568 params.network_delegate = &default_network_delegate_;
6569 params.http_server_properties = default_context_.http_server_properties();
6570 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6571 network_layer.OnSuspend();
6572
6573 TestURLRequestContext context(true);
6574 context.set_http_transaction_factory(&network_layer);
6575 context.Init();
6576
6577 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196578 scoped_ptr<URLRequest> req(context.CreateRequest(
6579 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
6580 req->Start();
[email protected]80abdad2014-03-15 00:20:546581 base::RunLoop().Run();
6582
6583 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196584 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6585 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546586}
6587
bengr1bf8e942014-11-07 01:36:506588class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6589 public:
6590 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6591 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6592 // tests into the factory tests.
6593 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6594 }
6595
6596 void SetUpFactory() override {
6597 interceptor_ = new MockURLRequestInterceptor();
6598 job_factory_.reset(new URLRequestInterceptingJobFactory(
6599 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6600 }
6601
6602 MockURLRequestInterceptor* interceptor() const {
6603 return interceptor_;
6604 }
6605
6606 private:
6607 MockURLRequestInterceptor* interceptor_;
6608};
6609
6610TEST_F(URLRequestInterceptorTestHTTP,
6611 NetworkDelegateNotificationOnRedirectIntercept) {
6612 interceptor()->set_intercept_redirect(true);
6613 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6614 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6615
6616 ASSERT_TRUE(test_server()->Start());
6617
6618 TestDelegate d;
6619 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6620 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY,
6621 &d, nullptr));
6622 req->Start();
6623 base::RunLoop().Run();
6624
6625 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6626 // Check we got one good response
6627 EXPECT_TRUE(req->status().is_success());
6628 if (req->status().is_success())
6629 EXPECT_EQ(200, req->response_headers()->response_code());
6630
6631 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6632 EXPECT_EQ(1, d.response_started_count());
6633 EXPECT_EQ(0, d.received_redirect_count());
6634
6635 EXPECT_EQ(1, default_network_delegate()->created_requests());
6636 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6637 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6638}
6639
6640TEST_F(URLRequestInterceptorTestHTTP,
6641 NetworkDelegateNotificationOnErrorIntercept) {
6642 // Intercept that error and respond with an OK response.
6643 interceptor()->set_intercept_final_response(true);
6644 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6645 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6646 default_network_delegate()->set_can_be_intercepted_on_error(true);
6647
6648 ASSERT_TRUE(test_server()->Start());
6649
6650 TestDelegate d;
6651 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6652 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
6653 &d, nullptr));
6654 req->set_method("GET");
6655 req->Start();
6656 base::RunLoop().Run();
6657
6658 EXPECT_TRUE(interceptor()->did_intercept_final());
6659
6660 // Check we received one good response.
6661 EXPECT_TRUE(req->status().is_success());
6662 if (req->status().is_success())
6663 EXPECT_EQ(200, req->response_headers()->response_code());
6664 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6665 EXPECT_EQ(1, d.response_started_count());
6666 EXPECT_EQ(0, d.received_redirect_count());
6667
6668 EXPECT_EQ(1, default_network_delegate()->created_requests());
6669 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6670 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6671}
6672
6673TEST_F(URLRequestInterceptorTestHTTP,
6674 NetworkDelegateNotificationOnResponseIntercept) {
6675 // Intercept that error and respond with an OK response.
6676 interceptor()->set_intercept_final_response(true);
6677
6678 // Intercept with a real URLRequestHttpJob.
6679 interceptor()->set_use_url_request_http_job(true);
6680
6681 ASSERT_TRUE(test_server()->Start());
6682
6683 TestDelegate d;
6684 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6685 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY,
6686 &d, nullptr));
6687 req->set_method("GET");
6688 req->Start();
6689 base::RunLoop().Run();
6690
6691 EXPECT_TRUE(interceptor()->did_intercept_final());
6692
6693 // Check we received one good response.
6694 EXPECT_TRUE(req->status().is_success());
6695 if (req->status().is_success())
6696 EXPECT_EQ(200, req->response_headers()->response_code());
6697 EXPECT_EQ("hello", d.data_received());
6698 EXPECT_EQ(1, d.response_started_count());
6699 EXPECT_EQ(0, d.received_redirect_count());
6700
6701 EXPECT_EQ(1, default_network_delegate()->created_requests());
6702 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
6703 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
6704}
6705
mkwst0c5eab872014-11-21 14:18:546706class URLRequestTestReferrerPolicy : public URLRequestTest {
6707 public:
6708 URLRequestTestReferrerPolicy() {}
6709
6710 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
6711 origin_server_.reset(new SpawnedTestServer(
6712 origin_type, SpawnedTestServer::kLocalhost,
6713 origin_type == SpawnedTestServer::TYPE_HTTPS
6714 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6715 : base::FilePath(
6716 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6717 ASSERT_TRUE(origin_server_->Start());
6718 }
6719
6720 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
6721 SpawnedTestServer::Type destination_type) {
6722 origin_server_.reset(new SpawnedTestServer(
6723 origin_type, SpawnedTestServer::kLocalhost,
6724 origin_type == SpawnedTestServer::TYPE_HTTPS
6725 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6726 : base::FilePath(
6727 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6728 ASSERT_TRUE(origin_server_->Start());
6729
6730 destination_server_.reset(new SpawnedTestServer(
6731 destination_type, SpawnedTestServer::kLocalhost,
6732 destination_type == SpawnedTestServer::TYPE_HTTPS
6733 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6734 : base::FilePath(
6735 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6736 ASSERT_TRUE(destination_server_->Start());
6737 }
6738
6739 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
6740 const GURL& referrer,
6741 const GURL& expected) {
6742 // Create and execute the request: we'll only have a |destination_server_|
6743 // if the origins are meant to be distinct. Otherwise, we'll use the
6744 // |origin_server_| for both endpoints.
6745 GURL destination_url =
6746 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
6747 : origin_server_->GetURL("echoheader?Referer");
6748 GURL origin_url =
6749 origin_server_->GetURL("server-redirect?" + destination_url.spec());
6750
6751 TestDelegate d;
6752 scoped_ptr<URLRequest> req(
6753 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d, NULL));
6754 req->set_referrer_policy(policy);
6755 req->SetReferrer(referrer.spec());
6756 req->Start();
6757 base::RunLoop().Run();
6758
6759 EXPECT_EQ(1, d.response_started_count());
6760 EXPECT_EQ(1, d.received_redirect_count());
6761 EXPECT_EQ(destination_url, req->url());
6762 EXPECT_TRUE(req->status().is_success());
6763 EXPECT_EQ(200, req->response_headers()->response_code());
6764
6765 EXPECT_EQ(expected.spec(), req->referrer());
6766 if (expected.is_empty())
6767 EXPECT_EQ("None", d.data_received());
6768 else
6769 EXPECT_EQ(expected.spec(), d.data_received());
6770 }
6771
6772 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
6773
6774 private:
6775 scoped_ptr<SpawnedTestServer> origin_server_;
6776 scoped_ptr<SpawnedTestServer> destination_server_;
6777};
6778
6779TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
6780 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
6781
6782 VerifyReferrerAfterRedirect(
6783 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6784 origin_server()->GetURL("path/to/file.html"),
6785 origin_server()->GetURL("path/to/file.html"));
6786
6787 VerifyReferrerAfterRedirect(
6788 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6789 origin_server()->GetURL("path/to/file.html"),
6790 origin_server()->GetURL("path/to/file.html"));
6791
6792 VerifyReferrerAfterRedirect(
6793 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6794 origin_server()->GetURL("path/to/file.html"),
6795 origin_server()->GetURL("path/to/file.html"));
6796
6797 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6798 origin_server()->GetURL("path/to/file.html"),
6799 origin_server()->GetURL("path/to/file.html"));
6800}
6801
6802TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
6803 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
6804 SpawnedTestServer::TYPE_HTTP);
6805
6806 VerifyReferrerAfterRedirect(
6807 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6808 origin_server()->GetURL("path/to/file.html"),
6809 origin_server()->GetURL("path/to/file.html"));
6810
6811 VerifyReferrerAfterRedirect(
6812 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6813 origin_server()->GetURL("path/to/file.html"),
6814 origin_server()->GetURL(std::string()));
6815
6816 VerifyReferrerAfterRedirect(
6817 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6818 origin_server()->GetURL("path/to/file.html"),
6819 origin_server()->GetURL(std::string()));
6820
6821 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6822 origin_server()->GetURL("path/to/file.html"),
6823 origin_server()->GetURL("path/to/file.html"));
6824}
6825
6826TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
6827 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
6828
6829 VerifyReferrerAfterRedirect(
6830 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6831 origin_server()->GetURL("path/to/file.html"),
6832 origin_server()->GetURL("path/to/file.html"));
6833
6834 VerifyReferrerAfterRedirect(
6835 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6836 origin_server()->GetURL("path/to/file.html"),
6837 origin_server()->GetURL("path/to/file.html"));
6838
6839 VerifyReferrerAfterRedirect(
6840 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6841 origin_server()->GetURL("path/to/file.html"),
6842 origin_server()->GetURL("path/to/file.html"));
6843
6844 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6845 origin_server()->GetURL("path/to/file.html"),
6846 origin_server()->GetURL("path/to/file.html"));
6847}
6848
6849TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
6850 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
6851 SpawnedTestServer::TYPE_HTTPS);
6852
6853 VerifyReferrerAfterRedirect(
6854 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6855 origin_server()->GetURL("path/to/file.html"),
6856 origin_server()->GetURL("path/to/file.html"));
6857
6858 VerifyReferrerAfterRedirect(
6859 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6860 origin_server()->GetURL("path/to/file.html"),
6861 origin_server()->GetURL(std::string()));
6862
6863 VerifyReferrerAfterRedirect(
6864 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6865 origin_server()->GetURL("path/to/file.html"),
6866 origin_server()->GetURL(std::string()));
6867
6868 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6869 origin_server()->GetURL("path/to/file.html"),
6870 origin_server()->GetURL("path/to/file.html"));
6871}
6872
6873TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
6874 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
6875 SpawnedTestServer::TYPE_HTTPS);
6876
6877 VerifyReferrerAfterRedirect(
6878 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6879 origin_server()->GetURL("path/to/file.html"),
6880 origin_server()->GetURL("path/to/file.html"));
6881
6882 VerifyReferrerAfterRedirect(
6883 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6884 origin_server()->GetURL("path/to/file.html"),
6885 origin_server()->GetURL(std::string()));
6886
6887 VerifyReferrerAfterRedirect(
6888 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6889 origin_server()->GetURL("path/to/file.html"),
6890 origin_server()->GetURL(std::string()));
6891
6892 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6893 origin_server()->GetURL("path/to/file.html"),
6894 origin_server()->GetURL("path/to/file.html"));
6895}
6896
6897TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
6898 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
6899 SpawnedTestServer::TYPE_HTTP);
6900
6901 VerifyReferrerAfterRedirect(
6902 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6903 origin_server()->GetURL("path/to/file.html"), GURL());
6904
6905 VerifyReferrerAfterRedirect(
6906 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6907 origin_server()->GetURL("path/to/file.html"), GURL());
6908
6909 VerifyReferrerAfterRedirect(
6910 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6911 origin_server()->GetURL("path/to/file.html"),
6912 origin_server()->GetURL(std::string()));
6913
6914 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6915 origin_server()->GetURL("path/to/file.html"),
6916 origin_server()->GetURL("path/to/file.html"));
6917}
6918
[email protected]73e0bba2009-02-19 22:57:096919class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:506920 public:
[email protected]ef2bf422012-05-11 03:27:096921 HTTPSRequestTest() : default_context_(true) {
6922 default_context_.set_network_delegate(&default_network_delegate_);
6923 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:506924 }
dcheng67be2b1f2014-10-27 21:47:296925 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:506926
6927 protected:
[email protected]ceefd7fd2012-11-29 00:36:246928 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:096929 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:466930};
6931
[email protected]c044616e2013-02-20 02:01:266932TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226933 SpawnedTestServer test_server(
6934 SpawnedTestServer::TYPE_HTTPS,
6935 SpawnedTestServer::kLocalhost,
6936 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116937 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:466938
[email protected]ea224582008-12-07 20:25:466939 TestDelegate d;
6940 {
[email protected]f7022f32014-08-21 16:32:196941 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6942 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
6943 r->Start();
6944 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:466945
[email protected]255620da2013-08-19 13:14:296946 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:466947
6948 EXPECT_EQ(1, d.response_started_count());
6949 EXPECT_FALSE(d.received_data_before_response());
6950 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196951 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:196952 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:196953 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:196954 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:196955 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:466956 }
[email protected]ea224582008-12-07 20:25:466957}
6958
[email protected]5774ada2010-07-15 06:30:546959TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226960 SpawnedTestServer::SSLOptions ssl_options(
6961 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6962 SpawnedTestServer test_server(
6963 SpawnedTestServer::TYPE_HTTPS,
6964 ssl_options,
6965 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:116966 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:336967
6968 bool err_allowed = true;
6969 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6970 TestDelegate d;
6971 {
6972 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:196973 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6974 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]bacff652009-03-31 17:50:336975
[email protected]f7022f32014-08-21 16:32:196976 r->Start();
6977 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:336978
[email protected]255620da2013-08-19 13:14:296979 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:336980
6981 EXPECT_EQ(1, d.response_started_count());
6982 EXPECT_FALSE(d.received_data_before_response());
6983 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:176984 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:336985 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196986 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:176987 } else {
[email protected]bacff652009-03-31 17:50:336988 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:176989 }
[email protected]bacff652009-03-31 17:50:336990 }
6991 }
6992}
6993
[email protected]5774ada2010-07-15 06:30:546994TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:226995 SpawnedTestServer::SSLOptions ssl_options(
6996 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6997 SpawnedTestServer test_server(
6998 SpawnedTestServer::TYPE_HTTPS,
6999 ssl_options,
7000 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117001 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337002
7003 // Iterate from false to true, just so that we do the opposite of the
7004 // previous test in order to increase test coverage.
7005 bool err_allowed = false;
7006 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7007 TestDelegate d;
7008 {
7009 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197010 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7011 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]bacff652009-03-31 17:50:337012
[email protected]f7022f32014-08-21 16:32:197013 r->Start();
7014 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337015
[email protected]255620da2013-08-19 13:14:297016 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337017
7018 EXPECT_EQ(1, d.response_started_count());
7019 EXPECT_FALSE(d.received_data_before_response());
7020 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177021 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337022 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197023 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177024 } else {
[email protected]bacff652009-03-31 17:50:337025 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177026 }
[email protected]bacff652009-03-31 17:50:337027 }
7028 }
7029}
[email protected]73e0bba2009-02-19 22:57:097030
[email protected]316c1e5e2012-09-12 15:17:447031// This tests that a load of www.google.com with a certificate error sets
7032// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7033// the interstitial to be fatal.
7034TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227035 SpawnedTestServer::SSLOptions ssl_options(
7036 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7037 SpawnedTestServer test_server(
7038 SpawnedTestServer::TYPE_HTTPS,
7039 ssl_options,
7040 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447041 ASSERT_TRUE(test_server.Start());
7042
7043 // We require that the URL be www.google.com in order to pick up the
7044 // preloaded HSTS entries in the TransportSecurityState. This means that we
7045 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247046 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447047
7048 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247049 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447050 TestURLRequestContext context(true);
7051 context.set_network_delegate(&network_delegate);
7052 context.set_host_resolver(&host_resolver);
7053 TransportSecurityState transport_security_state;
7054 context.set_transport_security_state(&transport_security_state);
7055 context.Init();
7056
7057 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197058 scoped_ptr<URLRequest> r(context.CreateRequest(
7059 GURL(base::StringPrintf("https://www.google.com:%d",
7060 test_server.host_port_pair().port())),
7061 DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447062
[email protected]f7022f32014-08-21 16:32:197063 r->Start();
7064 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447065
[email protected]255620da2013-08-19 13:14:297066 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447067
7068 EXPECT_EQ(1, d.response_started_count());
7069 EXPECT_FALSE(d.received_data_before_response());
7070 EXPECT_TRUE(d.have_certificate_errors());
7071 EXPECT_TRUE(d.certificate_errors_are_fatal());
7072}
7073
7074// This tests that cached HTTPS page loads do not cause any updates to the
7075// TransportSecurityState.
7076TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7077 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7078 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227079 SpawnedTestServer::SSLOptions ssl_options(
7080 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7081 SpawnedTestServer test_server(
7082 SpawnedTestServer::TYPE_HTTPS,
7083 ssl_options,
7084 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447085 ASSERT_TRUE(test_server.Start());
7086
[email protected]9e6968d2014-05-07 21:46:267087 // We require that the URL be www.google.com in order to pick up the static
7088 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7089 // that we have to use a MockHostResolver in order to direct www.google.com to
7090 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447091
7092 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247093 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447094 TestURLRequestContext context(true);
7095 context.set_network_delegate(&network_delegate);
7096 context.set_host_resolver(&host_resolver);
7097 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267098
7099 TransportSecurityState::DomainState static_domain_state;
7100 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127101 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447102 context.set_transport_security_state(&transport_security_state);
7103 context.Init();
7104
[email protected]9e6968d2014-05-07 21:46:267105 TransportSecurityState::DomainState dynamic_domain_state;
7106 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7107 "www.google.com", &dynamic_domain_state));
7108
[email protected]316c1e5e2012-09-12 15:17:447109 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197110 scoped_ptr<URLRequest> r(context.CreateRequest(
7111 GURL(base::StringPrintf("https://www.google.com:%d",
7112 test_server.host_port_pair().port())),
7113 DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447114
[email protected]f7022f32014-08-21 16:32:197115 r->Start();
7116 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447117
[email protected]255620da2013-08-19 13:14:297118 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447119
7120 EXPECT_EQ(1, d.response_started_count());
7121 EXPECT_FALSE(d.received_data_before_response());
7122 EXPECT_TRUE(d.have_certificate_errors());
7123 EXPECT_TRUE(d.certificate_errors_are_fatal());
7124
[email protected]9e6968d2014-05-07 21:46:267125 // Get a fresh copy of the states, and check that they haven't changed.
7126 TransportSecurityState::DomainState new_static_domain_state;
7127 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127128 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267129 TransportSecurityState::DomainState new_dynamic_domain_state;
7130 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7131 "www.google.com", &new_dynamic_domain_state));
7132
7133 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7134 static_domain_state.sts.upgrade_mode);
7135 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7136 static_domain_state.sts.include_subdomains);
7137 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7138 static_domain_state.pkp.include_subdomains);
7139 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7140 static_domain_state.pkp.spki_hashes));
7141 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7142 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447143}
7144
[email protected]8ccc69f2012-11-28 19:52:147145// Make sure HSTS preserves a POST request's method and body.
7146TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7147 static const char kData[] = "hello world";
7148
[email protected]ce7d0cbc2013-05-03 18:57:227149 SpawnedTestServer::SSLOptions ssl_options(
7150 SpawnedTestServer::SSLOptions::CERT_OK);
7151 SpawnedTestServer test_server(
7152 SpawnedTestServer::TYPE_HTTPS,
7153 ssl_options,
7154 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147155 ASSERT_TRUE(test_server.Start());
7156
7157
7158 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7159 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227160 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7161 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147162 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147163
7164 // Force https for www.somewhere.com.
7165 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207166 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7167 bool include_subdomains = false;
7168 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7169 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147170
7171 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7172
7173 TestURLRequestContext context(true);
7174 context.set_host_resolver(&host_resolver);
7175 context.set_transport_security_state(&transport_security_state);
7176 context.set_network_delegate(&network_delegate);
7177 context.Init();
7178
7179 TestDelegate d;
7180 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7181 // cause a certificate error. Ignore the error.
7182 d.set_allow_certificate_errors(true);
7183
[email protected]f7022f32014-08-21 16:32:197184 scoped_ptr<URLRequest> req(context.CreateRequest(
7185 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7186 test_server.host_port_pair().port())),
7187 DEFAULT_PRIORITY, &d, NULL));
7188 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077189 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147190
[email protected]f7022f32014-08-21 16:32:197191 req->Start();
[email protected]255620da2013-08-19 13:14:297192 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147193
[email protected]f7022f32014-08-21 16:32:197194 EXPECT_EQ("https", req->url().scheme());
7195 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147196 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407197
7198 LoadTimingInfo load_timing_info;
7199 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7200 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7201 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147202}
7203
rob4e0be1f2014-09-11 23:40:227204// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7205TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7206 static const char kOriginHeaderValue[] = "http://www.example.com";
7207
7208 SpawnedTestServer::SSLOptions ssl_options(
7209 SpawnedTestServer::SSLOptions::CERT_OK);
7210 SpawnedTestServer test_server(
7211 SpawnedTestServer::TYPE_HTTPS,
7212 ssl_options,
7213 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7214 ASSERT_TRUE(test_server.Start());
7215
7216 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7217 // address, so a MockHostResolver is needed to redirect example.net to the
7218 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7219 MockHostResolver host_resolver;
7220
7221 TransportSecurityState transport_security_state;
7222 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7223 bool include_subdomains = false;
7224 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7225
7226 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7227
7228 MockCertVerifier cert_verifier;
7229 cert_verifier.set_default_result(OK);
7230
7231 TestURLRequestContext context(true);
7232 context.set_host_resolver(&host_resolver);
7233 context.set_transport_security_state(&transport_security_state);
7234 context.set_network_delegate(&network_delegate);
7235 context.set_cert_verifier(&cert_verifier);
7236 context.Init();
7237
7238 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7239 test_server.host_port_pair().port()));
7240 url::Replacements<char> replacements;
7241 const char kNewScheme[] = "https";
7242 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7243 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7244
7245 TestDelegate d;
7246 // Quit on redirect to allow response header inspection upon redirect.
7247 d.set_quit_on_redirect(true);
7248
7249 scoped_ptr<URLRequest> req(context.CreateRequest(hsts_http_url,
7250 DEFAULT_PRIORITY, &d, NULL));
7251 // Set Origin header to simulate a cross-origin request.
7252 HttpRequestHeaders request_headers;
7253 request_headers.SetHeader("Origin", kOriginHeaderValue);
7254 req->SetExtraRequestHeaders(request_headers);
7255
7256 req->Start();
7257 base::RunLoop().Run();
7258
7259 EXPECT_EQ(1, d.received_redirect_count());
7260
7261 const HttpResponseHeaders* headers = req->response_headers();
7262 std::string redirect_location;
7263 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7264 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7265
7266 std::string received_cors_header;
7267 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7268 &received_cors_header));
7269 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7270}
7271
[email protected]316c1e5e2012-09-12 15:17:447272namespace {
7273
7274class SSLClientAuthTestDelegate : public TestDelegate {
7275 public:
7276 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7277 }
dchengb03027d2014-10-21 12:00:207278 void OnCertificateRequested(URLRequest* request,
7279 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447280 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347281 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447282 }
7283 int on_certificate_requested_count() {
7284 return on_certificate_requested_count_;
7285 }
7286 private:
7287 int on_certificate_requested_count_;
7288};
7289
7290} // namespace
7291
7292// TODO(davidben): Test the rest of the code. Specifically,
7293// - Filtering which certificates to select.
7294// - Sending a certificate back.
7295// - Getting a certificate request in an SSL renegotiation sending the
7296// HTTP request.
7297TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227298 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447299 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227300 SpawnedTestServer test_server(
7301 SpawnedTestServer::TYPE_HTTPS,
7302 ssl_options,
7303 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447304 ASSERT_TRUE(test_server.Start());
7305
7306 SSLClientAuthTestDelegate d;
7307 {
[email protected]f7022f32014-08-21 16:32:197308 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7309 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447310
[email protected]f7022f32014-08-21 16:32:197311 r->Start();
7312 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447313
[email protected]255620da2013-08-19 13:14:297314 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447315
7316 EXPECT_EQ(1, d.on_certificate_requested_count());
7317 EXPECT_FALSE(d.received_data_before_response());
7318 EXPECT_EQ(0, d.bytes_received());
7319
7320 // Send no certificate.
7321 // TODO(davidben): Get temporary client cert import (with keys) working on
7322 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197323 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447324
[email protected]255620da2013-08-19 13:14:297325 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447326
7327 EXPECT_EQ(1, d.response_started_count());
7328 EXPECT_FALSE(d.received_data_before_response());
7329 EXPECT_NE(0, d.bytes_received());
7330 }
7331}
7332
7333TEST_F(HTTPSRequestTest, ResumeTest) {
7334 // Test that we attempt a session resume when making two connections to the
7335 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227336 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447337 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227338 SpawnedTestServer test_server(
7339 SpawnedTestServer::TYPE_HTTPS,
7340 ssl_options,
7341 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447342 ASSERT_TRUE(test_server.Start());
7343
7344 SSLClientSocket::ClearSessionCache();
7345
7346 {
7347 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197348 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7349 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447350
[email protected]f7022f32014-08-21 16:32:197351 r->Start();
7352 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447353
[email protected]255620da2013-08-19 13:14:297354 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447355
7356 EXPECT_EQ(1, d.response_started_count());
7357 }
7358
7359 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7360 CloseAllConnections();
7361
7362 {
7363 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197364 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7365 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447366
[email protected]f7022f32014-08-21 16:32:197367 r->Start();
7368 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447369
[email protected]255620da2013-08-19 13:14:297370 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447371
7372 // The response will look like;
7373 // insert abc
7374 // lookup abc
7375 // insert xyz
7376 //
7377 // With a newline at the end which makes the split think that there are
7378 // four lines.
7379
7380 EXPECT_EQ(1, d.response_started_count());
7381 std::vector<std::string> lines;
7382 base::SplitString(d.data_received(), '\n', &lines);
7383 ASSERT_EQ(4u, lines.size()) << d.data_received();
7384
7385 std::string session_id;
7386
7387 for (size_t i = 0; i < 2; i++) {
7388 std::vector<std::string> parts;
7389 base::SplitString(lines[i], '\t', &parts);
7390 ASSERT_EQ(2u, parts.size());
7391 if (i == 0) {
7392 EXPECT_EQ("insert", parts[0]);
7393 session_id = parts[1];
7394 } else {
7395 EXPECT_EQ("lookup", parts[0]);
7396 EXPECT_EQ(session_id, parts[1]);
7397 }
7398 }
7399 }
7400}
7401
Adam Langley32352ad2014-10-14 22:31:007402// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7403// the result of fetching "ssl-session-cache" from the test server, indicates
7404// that exactly two different sessions were inserted, with no lookups etc.
7405static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7406 std::vector<std::string> lines;
7407 base::SplitString(session_info, '\n', &lines);
7408 ASSERT_EQ(3u, lines.size()) << session_info;
7409
7410 std::string session_id;
7411 for (size_t i = 0; i < 2; i++) {
7412 std::vector<std::string> parts;
7413 base::SplitString(lines[i], '\t', &parts);
7414 ASSERT_EQ(2u, parts.size());
7415 EXPECT_EQ("insert", parts[0]);
7416 if (i == 0) {
7417 session_id = parts[1];
7418 } else {
7419 EXPECT_NE(session_id, parts[1]);
7420 }
7421 }
7422}
7423
[email protected]316c1e5e2012-09-12 15:17:447424TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7425 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7426 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227427 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447428 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227429 SpawnedTestServer test_server(
7430 SpawnedTestServer::TYPE_HTTPS,
7431 ssl_options,
7432 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447433 ASSERT_TRUE(test_server.Start());
7434
7435 SSLClientSocket::ClearSessionCache();
7436
7437 {
7438 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197439 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7440 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447441
[email protected]f7022f32014-08-21 16:32:197442 r->Start();
7443 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447444
[email protected]255620da2013-08-19 13:14:297445 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447446
7447 EXPECT_EQ(1, d.response_started_count());
7448 }
7449
7450 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7451 HttpNetworkSession::Params params;
7452 params.host_resolver = default_context_.host_resolver();
7453 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117454 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447455 params.proxy_service = default_context_.proxy_service();
7456 params.ssl_config_service = default_context_.ssl_config_service();
7457 params.http_auth_handler_factory =
7458 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417459 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447460 params.http_server_properties = default_context_.http_server_properties();
7461 params.ssl_session_cache_shard = "alternate";
7462
[email protected]cba24642014-08-15 20:49:597463 scoped_ptr<HttpCache> cache(new HttpCache(
7464 new HttpNetworkSession(params),
7465 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447466
7467 default_context_.set_http_transaction_factory(cache.get());
7468
7469 {
7470 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197471 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7472 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447473
[email protected]f7022f32014-08-21 16:32:197474 r->Start();
7475 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447476
[email protected]255620da2013-08-19 13:14:297477 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447478
7479 // The response will look like;
7480 // insert abc
7481 // insert xyz
7482 //
7483 // With a newline at the end which makes the split think that there are
7484 // three lines.
7485
7486 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007487 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447488 }
7489}
7490
davidben8ecc3072014-09-03 23:19:097491#if defined(OS_WIN)
7492
7493namespace {
7494
7495bool IsECDSACipherSuite(uint16_t cipher_suite) {
7496 const char* key_exchange;
7497 const char* cipher;
7498 const char* mac;
7499 bool is_aead;
7500 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7501 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7502}
7503
7504} // namespace
7505
7506// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7507// verified.
davidben9399c952014-10-07 04:09:117508TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097509 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7510 LOG(INFO) << "Skipping test on this version.";
7511 return;
7512 }
7513
7514 SpawnedTestServer test_server(
7515 SpawnedTestServer::TYPE_HTTPS,
7516 SpawnedTestServer::kLocalhost,
7517 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7518 ASSERT_TRUE(test_server.Start());
7519
7520 TestDelegate d;
7521 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7522 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d, NULL));
7523 r->Start();
7524 EXPECT_TRUE(r->is_pending());
7525
7526 base::RunLoop().Run();
7527
7528 EXPECT_EQ(1, d.response_started_count());
7529 std::vector<std::string> lines;
7530 base::SplitString(d.data_received(), '\n', &lines);
7531
7532 for (size_t i = 0; i < lines.size(); i++) {
7533 int cipher_suite;
7534 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7535 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7536 << "ClientHello advertised " << cipher_suite;
7537 }
7538}
7539
7540#endif // OS_WIN
7541
Adam Langley32352ad2014-10-14 22:31:007542class TestSSLConfigService : public SSLConfigService {
7543 public:
7544 TestSSLConfigService(bool ev_enabled,
7545 bool online_rev_checking,
7546 bool rev_checking_required_local_anchors)
7547 : ev_enabled_(ev_enabled),
7548 online_rev_checking_(online_rev_checking),
7549 rev_checking_required_local_anchors_(
7550 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027551 min_version_(kDefaultSSLVersionMin),
7552 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7553
7554 void set_min_version(uint16 version) {
7555 min_version_ = version;
7556 }
Adam Langley32352ad2014-10-14 22:31:007557
7558 void set_fallback_min_version(uint16 version) {
7559 fallback_min_version_ = version;
7560 }
7561
7562 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207563 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007564 *config = SSLConfig();
7565 config->rev_checking_enabled = online_rev_checking_;
7566 config->verify_ev_cert = ev_enabled_;
7567 config->rev_checking_required_local_anchors =
7568 rev_checking_required_local_anchors_;
7569 if (fallback_min_version_) {
7570 config->version_fallback_min = fallback_min_version_;
7571 }
Adam Langleyac6f24b42014-10-31 20:24:027572 if (min_version_) {
7573 config->version_min = min_version_;
7574 }
Adam Langley32352ad2014-10-14 22:31:007575 }
7576
7577 protected:
dchengb03027d2014-10-21 12:00:207578 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007579
7580 private:
7581 const bool ev_enabled_;
7582 const bool online_rev_checking_;
7583 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027584 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007585 uint16 fallback_min_version_;
7586};
7587
7588class FallbackTestURLRequestContext : public TestURLRequestContext {
7589 public:
7590 explicit FallbackTestURLRequestContext(bool delay_initialization)
7591 : TestURLRequestContext(delay_initialization) {}
7592
7593 void set_fallback_min_version(uint16 version) {
7594 TestSSLConfigService *ssl_config_service =
7595 new TestSSLConfigService(true /* check for EV */,
7596 false /* online revocation checking */,
7597 false /* require rev. checking for local
7598 anchors */);
Adam Langleyac6f24b42014-10-31 20:24:027599 ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
Adam Langley32352ad2014-10-14 22:31:007600 ssl_config_service->set_fallback_min_version(version);
7601 set_ssl_config_service(ssl_config_service);
7602 }
7603};
7604
[email protected]48d2b7c52014-06-27 01:16:557605class HTTPSFallbackTest : public testing::Test {
7606 public:
Adam Langley32352ad2014-10-14 22:31:007607 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297608 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557609
7610 protected:
7611 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7612 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:007613 context_.Init();
7614 delegate_.set_allow_certificate_errors(true);
7615
[email protected]48d2b7c52014-06-27 01:16:557616 SpawnedTestServer test_server(
7617 SpawnedTestServer::TYPE_HTTPS,
7618 ssl_options,
7619 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7620 ASSERT_TRUE(test_server.Start());
7621
[email protected]f7022f32014-08-21 16:32:197622 request_ = context_.CreateRequest(
7623 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate_, NULL);
[email protected]48d2b7c52014-06-27 01:16:557624 request_->Start();
7625
7626 base::RunLoop().Run();
7627 }
7628
Adam Langley32352ad2014-10-14 22:31:007629 void set_fallback_min_version(uint16 version) {
7630 context_.set_fallback_min_version(version);
7631 }
7632
[email protected]48d2b7c52014-06-27 01:16:557633 void ExpectConnection(int version) {
7634 EXPECT_EQ(1, delegate_.response_started_count());
7635 EXPECT_NE(0, delegate_.bytes_received());
7636 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7637 request_->ssl_info().connection_status));
7638 EXPECT_TRUE(request_->ssl_info().connection_status &
7639 SSL_CONNECTION_VERSION_FALLBACK);
7640 }
7641
7642 void ExpectFailure(int error) {
7643 EXPECT_EQ(1, delegate_.response_started_count());
7644 EXPECT_FALSE(request_->status().is_success());
7645 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7646 EXPECT_EQ(error, request_->status().error());
7647 }
7648
7649 private:
7650 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:007651 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:557652 scoped_ptr<URLRequest> request_;
7653};
7654
7655// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7656// than necessary.
7657TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7658 SpawnedTestServer::SSLOptions ssl_options(
7659 SpawnedTestServer::SSLOptions::CERT_OK);
7660 ssl_options.tls_intolerant =
7661 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7662
7663 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7664 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7665}
7666
7667// This test is disabled on Android because the remote test server doesn't cause
7668// a TCP reset.
7669#if !defined(OS_ANDROID)
7670// Tests fallback to TLS 1.0 on connection reset.
7671TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7672 SpawnedTestServer::SSLOptions ssl_options(
7673 SpawnedTestServer::SSLOptions::CERT_OK);
7674 ssl_options.tls_intolerant =
7675 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7676 ssl_options.tls_intolerance_type =
7677 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7678
7679 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7680 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7681}
7682#endif // !OS_ANDROID
7683
[email protected]12833302014-07-02 01:57:317684// Tests that we don't fallback on handshake failure with servers that implement
7685// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:557686TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:557687 SpawnedTestServer::SSLOptions ssl_options(
7688 SpawnedTestServer::SSLOptions::CERT_OK);
7689 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7690 // a version fallback.
7691 ssl_options.tls_intolerant =
7692 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7693 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7694 // connections are rejected.
7695 ssl_options.fallback_scsv_enabled = true;
7696
7697 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7698
7699 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7700 // intolerance. If the fallback SCSV is processed when the original error
7701 // that caused the fallback should be returned, which should be
7702 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7703 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7704}
7705
[email protected]12833302014-07-02 01:57:317706// Tests that we don't fallback on connection closed with servers that implement
7707// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:317708TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:317709 SpawnedTestServer::SSLOptions ssl_options(
7710 SpawnedTestServer::SSLOptions::CERT_OK);
7711 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7712 // a version fallback.
7713 ssl_options.tls_intolerant =
7714 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7715 ssl_options.tls_intolerance_type =
7716 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7717 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7718 // connections are rejected.
7719 ssl_options.fallback_scsv_enabled = true;
7720
7721 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7722
7723 // The original error should be replayed on rejected fallback.
7724 ExpectFailure(ERR_CONNECTION_CLOSED);
7725}
7726
Adam Langley32352ad2014-10-14 22:31:007727// Tests that the SSLv3 fallback doesn't happen by default.
[email protected]48d2b7c52014-06-27 01:16:557728TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7729 SpawnedTestServer::SSLOptions ssl_options(
7730 SpawnedTestServer::SSLOptions::CERT_OK);
7731 ssl_options.tls_intolerant =
7732 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7733
7734 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:027735 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:007736}
7737
7738// Tests that the SSLv3 fallback works when explicitly enabled.
7739TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7740 SpawnedTestServer::SSLOptions ssl_options(
7741 SpawnedTestServer::SSLOptions::CERT_OK);
7742 ssl_options.tls_intolerant =
7743 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7744 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7745
7746 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:557747 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7748}
7749
Adam Langley32352ad2014-10-14 22:31:007750// Tests that the SSLv3 fallback triggers on closed connections when explicitly
7751// enabled.
[email protected]48d2b7c52014-06-27 01:16:557752TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
7753 SpawnedTestServer::SSLOptions ssl_options(
7754 SpawnedTestServer::SSLOptions::CERT_OK);
7755 ssl_options.tls_intolerant =
7756 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7757 ssl_options.tls_intolerance_type =
7758 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
Adam Langley32352ad2014-10-14 22:31:007759 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
[email protected]48d2b7c52014-06-27 01:16:557760
7761 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7762 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7763}
7764
Adam Langley32352ad2014-10-14 22:31:007765// Test that SSLv3 fallback probe connections don't cause sessions to be cached.
7766TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
7767 SpawnedTestServer::SSLOptions ssl_options(
7768 SpawnedTestServer::SSLOptions::CERT_OK);
7769 ssl_options.tls_intolerant =
7770 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7771 ssl_options.tls_intolerance_type =
7772 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7773 ssl_options.record_resume = true;
7774
7775 SpawnedTestServer test_server(
7776 SpawnedTestServer::TYPE_HTTPS,
7777 ssl_options,
7778 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7779 ASSERT_TRUE(test_server.Start());
7780
7781 SSLClientSocket::ClearSessionCache();
7782
7783 // Make a connection that does a probe fallback to SSLv3 but fails because
7784 // SSLv3 fallback is disabled. We don't wish a session for this connection to
7785 // be inserted locally.
7786 {
7787 TestDelegate delegate;
7788 FallbackTestURLRequestContext context(true);
7789
Adam Langleyac6f24b42014-10-31 20:24:027790 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:007791 context.Init();
7792 scoped_ptr<URLRequest> request(context.CreateRequest(
7793 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate, NULL));
7794 request->Start();
7795
7796 base::RunLoop().Run();
7797
7798 EXPECT_EQ(1, delegate.response_started_count());
7799 EXPECT_FALSE(request->status().is_success());
7800 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
7801 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
7802 request->status().error());
7803 }
7804
7805 // Now allow SSLv3 connections and request the session cache log.
7806 {
7807 TestDelegate delegate;
7808 FallbackTestURLRequestContext context(true);
7809 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7810
7811 context.Init();
7812 scoped_ptr<URLRequest> request(
7813 context.CreateRequest(test_server.GetURL("ssl-session-cache"),
7814 DEFAULT_PRIORITY,
7815 &delegate,
7816 NULL));
7817 request->Start();
7818
7819 base::RunLoop().Run();
7820
7821 EXPECT_EQ(1, delegate.response_started_count());
7822 EXPECT_NE(0, delegate.bytes_received());
7823 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
7824 request->ssl_info().connection_status));
7825 EXPECT_TRUE(request->ssl_info().connection_status &
7826 SSL_CONNECTION_VERSION_FALLBACK);
7827
7828 std::vector<std::string> lines;
7829 // If no sessions were cached then the server should have seen two sessions
7830 // inserted with no lookups.
7831 AssertTwoDistinctSessionsInserted(delegate.data_received());
7832 }
7833}
7834
[email protected]48d2b7c52014-06-27 01:16:557835// This test is disabled on Android because the remote test server doesn't cause
[email protected]5aea79182014-07-14 20:43:417836// a TCP reset.
7837#if !defined(OS_ANDROID)
[email protected]48d2b7c52014-06-27 01:16:557838// Tests that a reset connection does not fallback down to SSL3.
7839TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
7840 SpawnedTestServer::SSLOptions ssl_options(
7841 SpawnedTestServer::SSLOptions::CERT_OK);
7842 ssl_options.tls_intolerant =
7843 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7844 ssl_options.tls_intolerance_type =
7845 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7846
7847 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7848 ExpectFailure(ERR_CONNECTION_RESET);
7849}
[email protected]5aea79182014-07-14 20:43:417850#endif // !OS_ANDROID
[email protected]48d2b7c52014-06-27 01:16:557851
[email protected]a8fed1742013-12-27 02:14:247852class HTTPSSessionTest : public testing::Test {
7853 public:
7854 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:597855 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:247856
7857 default_context_.set_network_delegate(&default_network_delegate_);
7858 default_context_.set_cert_verifier(&cert_verifier_);
7859 default_context_.Init();
7860 }
dcheng67be2b1f2014-10-27 21:47:297861 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:247862
7863 protected:
7864 MockCertVerifier cert_verifier_;
7865 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7866 TestURLRequestContext default_context_;
7867};
7868
7869// Tests that session resumption is not attempted if an invalid certificate
7870// is presented.
7871TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7872 SpawnedTestServer::SSLOptions ssl_options;
7873 ssl_options.record_resume = true;
7874 SpawnedTestServer test_server(
7875 SpawnedTestServer::TYPE_HTTPS,
7876 ssl_options,
7877 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7878 ASSERT_TRUE(test_server.Start());
7879
7880 SSLClientSocket::ClearSessionCache();
7881
7882 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:597883 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:247884 {
7885 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197886 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7887 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]a8fed1742013-12-27 02:14:247888
[email protected]f7022f32014-08-21 16:32:197889 r->Start();
7890 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:247891
7892 base::RunLoop().Run();
7893
7894 EXPECT_EQ(1, d.response_started_count());
7895 }
7896
7897 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7898 CloseAllConnections();
7899
7900 // Now change the certificate to be acceptable (so that the response is
7901 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:597902 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:247903 {
7904 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197905 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7906 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]a8fed1742013-12-27 02:14:247907
[email protected]f7022f32014-08-21 16:32:197908 r->Start();
7909 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:247910
7911 base::RunLoop().Run();
7912
7913 // The response will look like;
7914 // insert abc
7915 // insert xyz
7916 //
7917 // With a newline at the end which makes the split think that there are
7918 // three lines.
7919 //
7920 // If a session was presented (eg: a bug), then the response would look
7921 // like;
7922 // insert abc
7923 // lookup abc
7924 // insert xyz
7925
7926 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007927 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:247928 }
7929}
7930
[email protected]dffe8242012-03-20 15:14:277931// This the fingerprint of the "Testing CA" certificate used by the testserver.
7932// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:267933static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:277934 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7935 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7936
[email protected]51523f52013-07-31 21:57:287937// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7938// testserver.
7939static const SHA256HashValue kOCSPTestCertSPKI = { {
7940 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7941 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7942 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7943 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7944} };
7945
[email protected]dffe8242012-03-20 15:14:277946// This is the policy OID contained in the certificates that testserver
7947// generates.
7948static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7949
7950class HTTPSOCSPTest : public HTTPSRequestTest {
7951 public:
7952 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:097953 : context_(true),
[email protected]b6f2de32012-08-17 04:35:087954 ev_test_policy_(
7955 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7956 kOCSPTestCertFingerprint,
7957 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:027958 }
7959
dcheng67be2b1f2014-10-27 21:47:297960 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:097961 SetupContext(&context_);
7962 context_.Init();
[email protected]dffe8242012-03-20 15:14:277963
[email protected]cba24642014-08-15 20:49:597964 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:207965 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:427966 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:507967 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:277968
[email protected]a592c0432012-12-01 18:10:297969#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:097970 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:277971 EnsureNSSHttpIOInit();
7972#endif
7973 }
7974
[email protected]ce7d0cbc2013-05-03 18:57:227975 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:277976 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:537977 // We always overwrite out_cert_status.
7978 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:227979 SpawnedTestServer test_server(
7980 SpawnedTestServer::TYPE_HTTPS,
7981 ssl_options,
7982 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:277983 ASSERT_TRUE(test_server.Start());
7984
7985 TestDelegate d;
7986 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:197987 scoped_ptr<URLRequest> r(context_.CreateRequest(
7988 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7989 r->Start();
[email protected]dffe8242012-03-20 15:14:277990
[email protected]255620da2013-08-19 13:14:297991 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:277992
7993 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:197994 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:277995 }
7996
dcheng67be2b1f2014-10-27 21:47:297997 ~HTTPSOCSPTest() override {
[email protected]a592c0432012-12-01 18:10:297998#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:277999 ShutdownNSSHttpIO();
8000#endif
8001 }
8002
[email protected]a13234c2012-03-20 21:45:028003 protected:
8004 // SetupContext configures the URLRequestContext that will be used for making
8005 // connetions to testserver. This can be overridden in test subclasses for
8006 // different behaviour.
8007 virtual void SetupContext(URLRequestContext* context) {
8008 context->set_ssl_config_service(
8009 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208010 true /* online revocation checking */,
8011 false /* require rev. checking for local
8012 anchors */));
[email protected]a13234c2012-03-20 21:45:028013 }
8014
[email protected]dffe8242012-03-20 15:14:278015 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098016 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088017 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278018};
8019
[email protected]a13234c2012-03-20 21:45:028020static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018021#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028022 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8023 // have that ability on other platforms.
8024 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8025#else
8026 return 0;
8027#endif
8028}
8029
[email protected]3a86a712013-07-30 07:16:208030// SystemSupportsHardFailRevocationChecking returns true iff the current
8031// operating system supports revocation checking and can distinguish between
8032// situations where a given certificate lacks any revocation information (eg:
8033// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8034// revocation information cannot be obtained (eg: the CRL was unreachable).
8035// If it does not, then tests which rely on 'hard fail' behaviour should be
8036// skipped.
8037static bool SystemSupportsHardFailRevocationChecking() {
8038#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8039 return true;
8040#else
8041 return false;
8042#endif
8043}
8044
[email protected]a13234c2012-03-20 21:45:028045// SystemUsesChromiumEVMetadata returns true iff the current operating system
8046// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8047// several tests are effected because our testing EV certificate won't be
8048// recognised as EV.
8049static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328050#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578051 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8052 return false;
[email protected]e1b2d732014-03-28 16:20:328053#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8054 // On OS X and Android, we use the system to tell us whether a certificate is
8055 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018056 return false;
8057#else
8058 return true;
8059#endif
8060}
8061
[email protected]b6f2de32012-08-17 04:35:088062static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008063#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578064 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8065 return false;
8066#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028067 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8068#elif defined(OS_ANDROID)
8069 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8070 return false;
8071#else
8072 return true;
8073#endif
8074}
8075
davidbend1fb2f12014-11-08 02:51:008076static bool SystemSupportsOCSPStapling() {
8077#if defined(USE_NSS)
8078 return true;
8079#elif defined(OS_WIN)
8080 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8081#else
8082 return false;
8083#endif
8084}
8085
[email protected]dffe8242012-03-20 15:14:278086TEST_F(HTTPSOCSPTest, Valid) {
8087 if (!SystemSupportsOCSP()) {
8088 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8089 return;
8090 }
8091
[email protected]ce7d0cbc2013-05-03 18:57:228092 SpawnedTestServer::SSLOptions ssl_options(
8093 SpawnedTestServer::SSLOptions::CERT_AUTO);
8094 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278095
[email protected]924e9f92012-12-16 22:00:538096 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128097 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278098
8099 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8100
[email protected]a13234c2012-03-20 21:45:028101 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8102 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278103
8104 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8105}
8106
8107TEST_F(HTTPSOCSPTest, Revoked) {
8108 if (!SystemSupportsOCSP()) {
8109 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8110 return;
8111 }
8112
[email protected]ce7d0cbc2013-05-03 18:57:228113 SpawnedTestServer::SSLOptions ssl_options(
8114 SpawnedTestServer::SSLOptions::CERT_AUTO);
8115 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278116
8117 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128118 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278119
[email protected]a592c0432012-12-01 18:10:298120#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278121 // Doesn't pass on OS X yet for reasons that need to be investigated.
8122 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8123#endif
8124 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8125 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8126}
8127
8128TEST_F(HTTPSOCSPTest, Invalid) {
8129 if (!SystemSupportsOCSP()) {
8130 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8131 return;
8132 }
8133
[email protected]ce7d0cbc2013-05-03 18:57:228134 SpawnedTestServer::SSLOptions ssl_options(
8135 SpawnedTestServer::SSLOptions::CERT_AUTO);
8136 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278137
[email protected]924e9f92012-12-16 22:00:538138 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128139 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278140
[email protected]a13234c2012-03-20 21:45:028141 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278142 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278143
8144 // Without a positive OCSP response, we shouldn't show the EV status.
8145 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8146 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8147}
[email protected]a13234c2012-03-20 21:45:028148
davidbend1fb2f12014-11-08 02:51:008149TEST_F(HTTPSOCSPTest, ValidStapled) {
8150 if (!SystemSupportsOCSPStapling()) {
8151 LOG(WARNING)
8152 << "Skipping test because system doesn't support OCSP stapling";
8153 return;
8154 }
8155
8156 SpawnedTestServer::SSLOptions ssl_options(
8157 SpawnedTestServer::SSLOptions::CERT_AUTO);
8158 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8159 ssl_options.staple_ocsp_response = true;
8160 ssl_options.ocsp_server_unavailable = true;
8161
8162 CertStatus cert_status;
8163 DoConnection(ssl_options, &cert_status);
8164
8165 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8166
8167 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8168 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8169
8170 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8171}
8172
davidben6c3191b2014-11-21 22:38:048173// Disabled on NSS ports. See https://crbug.com/431716.
8174#if defined(USE_NSS)
8175#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8176#else
8177#define MAYBE_RevokedStapled RevokedStapled
8178#endif
8179TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008180 if (!SystemSupportsOCSPStapling()) {
8181 LOG(WARNING)
8182 << "Skipping test because system doesn't support OCSP stapling";
8183 return;
8184 }
8185
8186 SpawnedTestServer::SSLOptions ssl_options(
8187 SpawnedTestServer::SSLOptions::CERT_AUTO);
8188 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8189 ssl_options.staple_ocsp_response = true;
8190 ssl_options.ocsp_server_unavailable = true;
8191
8192 CertStatus cert_status;
8193 DoConnection(ssl_options, &cert_status);
8194
8195 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8196 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8197 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8198}
8199
[email protected]3a86a712013-07-30 07:16:208200class HTTPSHardFailTest : public HTTPSOCSPTest {
8201 protected:
dchengb03027d2014-10-21 12:00:208202 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208203 context->set_ssl_config_service(
8204 new TestSSLConfigService(false /* check for EV */,
8205 false /* online revocation checking */,
8206 true /* require rev. checking for local
8207 anchors */));
8208 }
8209};
8210
[email protected]3a86a712013-07-30 07:16:208211TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8212 if (!SystemSupportsOCSP()) {
8213 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8214 return;
8215 }
8216
8217 if (!SystemSupportsHardFailRevocationChecking()) {
8218 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8219 << "revocation checking";
8220 return;
8221 }
8222
8223 SpawnedTestServer::SSLOptions ssl_options(
8224 SpawnedTestServer::SSLOptions::CERT_AUTO);
8225 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8226
8227 CertStatus cert_status;
8228 DoConnection(ssl_options, &cert_status);
8229
8230 EXPECT_EQ(CERT_STATUS_REVOKED,
8231 cert_status & CERT_STATUS_REVOKED);
8232
8233 // Without a positive OCSP response, we shouldn't show the EV status.
8234 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8235}
8236
[email protected]a13234c2012-03-20 21:45:028237class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8238 protected:
dchengb03027d2014-10-21 12:00:208239 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028240 context->set_ssl_config_service(
8241 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208242 false /* online revocation checking */,
8243 false /* require rev. checking for local
8244 anchors */));
[email protected]a13234c2012-03-20 21:45:028245 }
8246};
8247
8248TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8249 if (!SystemSupportsOCSP()) {
8250 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8251 return;
8252 }
8253
[email protected]ce7d0cbc2013-05-03 18:57:228254 SpawnedTestServer::SSLOptions ssl_options(
8255 SpawnedTestServer::SSLOptions::CERT_AUTO);
8256 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028257 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8258
[email protected]924e9f92012-12-16 22:00:538259 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128260 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028261
8262 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8263 cert_status & CERT_STATUS_ALL_ERRORS);
8264
8265 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088266 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8267 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028268}
8269
[email protected]be0fff62013-08-29 23:37:488270TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8271 if (!SystemSupportsOCSP()) {
8272 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8273 return;
8274 }
8275
8276 SpawnedTestServer::SSLOptions ssl_options(
8277 SpawnedTestServer::SSLOptions::CERT_AUTO);
8278 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8279 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8280
8281 CertStatus cert_status;
8282 DoConnection(ssl_options, &cert_status);
8283
8284 // Currently only works for Windows. When using NSS or OS X, it's not
8285 // possible to determine whether the check failed because of actual
8286 // revocation or because there was an OCSP failure.
8287#if defined(OS_WIN)
8288 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8289#else
8290 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8291#endif
8292
8293 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8294 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8295 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8296}
8297
[email protected]a13234c2012-03-20 21:45:028298TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8299 if (!SystemSupportsOCSP()) {
8300 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8301 return;
8302 }
8303
[email protected]ce7d0cbc2013-05-03 18:57:228304 SpawnedTestServer::SSLOptions ssl_options(
8305 SpawnedTestServer::SSLOptions::CERT_AUTO);
8306 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028307 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8308
8309 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128310 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028311
8312 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8313
8314 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8315 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088316 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8317 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028318}
8319
8320TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8321 if (!SystemSupportsOCSP()) {
8322 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8323 return;
8324 }
8325
[email protected]ce7d0cbc2013-05-03 18:57:228326 SpawnedTestServer::SSLOptions ssl_options(
8327 SpawnedTestServer::SSLOptions::CERT_AUTO);
8328 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028329 SSLConfigService::SetCRLSet(
8330 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8331
8332 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128333 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028334
8335 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8336 cert_status & CERT_STATUS_ALL_ERRORS);
8337
8338 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088339 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8340 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028341}
8342
[email protected]51523f52013-07-31 21:57:288343TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8344 if (!SystemSupportsOCSP()) {
8345 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8346 return;
8347 }
8348
8349 SpawnedTestServer::SSLOptions ssl_options(
8350 SpawnedTestServer::SSLOptions::CERT_AUTO);
8351 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8352 SSLConfigService::SetCRLSet(
8353 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8354 false, &kOCSPTestCertSPKI, "")));
8355
8356 CertStatus cert_status;
8357 DoConnection(ssl_options, &cert_status);
8358
8359 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8360 // revocation check for EV.
8361 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8362 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8363 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8364 EXPECT_FALSE(
8365 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8366}
8367
8368TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8369 if (!SystemSupportsOCSP()) {
8370 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8371 return;
8372 }
8373
[email protected]ce7d0cbc2013-05-03 18:57:228374 SpawnedTestServer::SSLOptions ssl_options(
8375 SpawnedTestServer::SSLOptions::CERT_AUTO);
8376 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028377 SSLConfigService::SetCRLSet(
8378 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8379
[email protected]51523f52013-07-31 21:57:288380 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128381 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028382
[email protected]51523f52013-07-31 21:57:288383 // Even with a fresh CRLSet, we should still do online revocation checks when
8384 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8385 // test.
8386 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8387 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028388
[email protected]51523f52013-07-31 21:57:288389 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028390 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288391 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028392}
8393
[email protected]b6f2de32012-08-17 04:35:088394TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8395 // Test that when EV verification is requested, but online revocation
8396 // checking is disabled, and the leaf certificate is not in fact EV, that
8397 // no revocation checking actually happens.
8398 if (!SystemSupportsOCSP()) {
8399 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8400 return;
8401 }
8402
8403 // Unmark the certificate's OID as EV, which should disable revocation
8404 // checking (as per the user preference)
8405 ev_test_policy_.reset();
8406
[email protected]ce7d0cbc2013-05-03 18:57:228407 SpawnedTestServer::SSLOptions ssl_options(
8408 SpawnedTestServer::SSLOptions::CERT_AUTO);
8409 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088410 SSLConfigService::SetCRLSet(
8411 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8412
8413 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128414 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088415
8416 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8417
8418 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8419 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8420}
8421
[email protected]a13234c2012-03-20 21:45:028422class HTTPSCRLSetTest : public HTTPSOCSPTest {
8423 protected:
dchengb03027d2014-10-21 12:00:208424 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028425 context->set_ssl_config_service(
8426 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208427 false /* online revocation checking */,
8428 false /* require rev. checking for local
8429 anchors */));
[email protected]a13234c2012-03-20 21:45:028430 }
8431};
8432
8433TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228434 SpawnedTestServer::SSLOptions ssl_options(
8435 SpawnedTestServer::SSLOptions::CERT_AUTO);
8436 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028437 SSLConfigService::SetCRLSet(
8438 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8439
[email protected]924e9f92012-12-16 22:00:538440 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128441 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028442
8443 // If we're not trying EV verification then, even if the CRLSet has expired,
8444 // we don't fall back to online revocation checks.
8445 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8446 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8447 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8448}
[email protected]51523f52013-07-31 21:57:288449
8450TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308451#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288452 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8453 return;
8454#endif
8455
8456 SpawnedTestServer::SSLOptions ssl_options(
8457 SpawnedTestServer::SSLOptions::CERT_AUTO);
8458 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8459 ssl_options.cert_serial = 10;
8460 SSLConfigService::SetCRLSet(
8461 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8462 false, &kOCSPTestCertSPKI, "\x0a")));
8463
8464 CertStatus cert_status = 0;
8465 DoConnection(ssl_options, &cert_status);
8466
8467 // If the certificate is recorded as revoked in the CRLSet, that should be
8468 // reflected without online revocation checking.
8469 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8470 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8471 EXPECT_FALSE(
8472 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8473}
[email protected]316c1e5e2012-09-12 15:17:448474#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278475
[email protected]316c1e5e2012-09-12 15:17:448476#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318477class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118478 public:
[email protected]d9fca99a2012-02-24 16:16:208479 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228480 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158481 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118482 }
8483
[email protected]b89ca032009-08-31 21:41:318484 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228485 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318486};
8487
[email protected]d2a133182012-08-05 16:44:088488// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098489TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088490 ASSERT_TRUE(test_server_.Start());
8491
[email protected]9d5730b2012-08-24 17:42:498492 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348493 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088494
8495 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088496 job_factory.SetProtocolHandler(
8497 "ftp",
[email protected]e0f35c92013-05-08 16:04:348498 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088499 default_context_.set_job_factory(&job_factory);
8500
8501 TestDelegate d;
8502 {
[email protected]f7022f32014-08-21 16:32:198503 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8504 url, DEFAULT_PRIORITY, &d, NULL));
8505 r->Start();
8506 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088507
[email protected]255620da2013-08-19 13:14:298508 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088509
[email protected]f7022f32014-08-21 16:32:198510 EXPECT_FALSE(r->is_pending());
8511 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8512 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088513 }
8514}
8515
[email protected]5accf7332009-11-24 03:41:388516// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128517TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118518 ASSERT_TRUE(test_server_.Start());
8519
[email protected]a25e90e2009-09-09 17:05:378520 TestDelegate d;
8521 {
[email protected]f7022f32014-08-21 16:32:198522 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8523 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, NULL));
8524 r->Start();
8525 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378526
[email protected]255620da2013-08-19 13:14:298527 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378528
[email protected]f7022f32014-08-21 16:32:198529 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378530 EXPECT_EQ(1, d.response_started_count());
8531 EXPECT_FALSE(d.received_data_before_response());
8532 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198533 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198534 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198535 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198536 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378537 }
8538}
8539
[email protected]7df70012010-02-04 00:09:558540// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128541TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118542 ASSERT_TRUE(test_server_.Start());
8543
[email protected]6cdfd7f2013-02-08 20:40:158544 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278545 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028546 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278547 TestDelegate d;
8548 {
[email protected]f7022f32014-08-21 16:32:198549 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8550 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d, NULL));
8551 r->Start();
8552 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278553
[email protected]255620da2013-08-19 13:14:298554 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278555
8556 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498557 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278558
[email protected]f7022f32014-08-21 16:32:198559 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278560 EXPECT_EQ(1, d.response_started_count());
8561 EXPECT_FALSE(d.received_data_before_response());
8562 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198563 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198564 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198565 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198566 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278567 }
8568}
8569
[email protected]e9ecbd12009-12-20 18:44:408570// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128571TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118572 ASSERT_TRUE(test_server_.Start());
8573
[email protected]6cdfd7f2013-02-08 20:40:158574 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278575 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028576 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278577 TestDelegate d;
8578 {
[email protected]f7022f32014-08-21 16:32:198579 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118580 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]f7022f32014-08-21 16:32:198581 DEFAULT_PRIORITY, &d, NULL));
8582 r->Start();
8583 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278584
[email protected]255620da2013-08-19 13:14:298585 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278586
8587 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498588 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278589
[email protected]f7022f32014-08-21 16:32:198590 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198591 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198592 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198593 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198594 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278595 EXPECT_EQ(1, d.response_started_count());
8596 EXPECT_FALSE(d.received_data_before_response());
8597 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258598
8599 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198600 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258601 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278602 }
8603}
8604
[email protected]49abd652010-08-05 05:04:538605// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128606TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118607 ASSERT_TRUE(test_server_.Start());
8608
[email protected]6cdfd7f2013-02-08 20:40:158609 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278610 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028611 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278612 TestDelegate d;
8613 {
[email protected]f7022f32014-08-21 16:32:198614 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8615 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8616 "wrong_password"),
8617 DEFAULT_PRIORITY, &d, NULL));
8618 r->Start();
8619 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278620
[email protected]255620da2013-08-19 13:14:298621 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278622
8623 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498624 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278625
[email protected]f7022f32014-08-21 16:32:198626 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278627 EXPECT_EQ(1, d.response_started_count());
8628 EXPECT_FALSE(d.received_data_before_response());
8629 EXPECT_EQ(d.bytes_received(), 0);
8630 }
8631}
8632
[email protected]cde4e80d2009-10-16 19:58:158633// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128634TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118635 ASSERT_TRUE(test_server_.Start());
8636
[email protected]6cdfd7f2013-02-08 20:40:158637 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588638 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8639 app_path = app_path.AppendASCII("LICENSE");
8640 TestDelegate d;
8641 // Set correct login credentials. The delegate will be asked for them when
8642 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588643 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588644 {
[email protected]f7022f32014-08-21 16:32:198645 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8646 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8647 "wrong_password"),
8648 DEFAULT_PRIORITY, &d, NULL));
8649 r->Start();
8650 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588651
[email protected]255620da2013-08-19 13:14:298652 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588653
8654 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498655 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588656
[email protected]f7022f32014-08-21 16:32:198657 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588658 EXPECT_EQ(1, d.response_started_count());
8659 EXPECT_FALSE(d.received_data_before_response());
8660 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8661 }
8662}
8663
[email protected]49abd652010-08-05 05:04:538664// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128665TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:118666 ASSERT_TRUE(test_server_.Start());
8667
[email protected]6cdfd7f2013-02-08 20:40:158668 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278669 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028670 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278671 TestDelegate d;
8672 {
[email protected]f7022f32014-08-21 16:32:198673 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8674 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8675 "chrome"),
8676 DEFAULT_PRIORITY, &d, NULL));
8677 r->Start();
8678 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278679
[email protected]255620da2013-08-19 13:14:298680 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278681
8682 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498683 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278684
[email protected]f7022f32014-08-21 16:32:198685 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278686 EXPECT_EQ(1, d.response_started_count());
8687 EXPECT_FALSE(d.received_data_before_response());
8688 EXPECT_EQ(d.bytes_received(), 0);
8689 }
8690}
[email protected]8b8a197d2009-08-26 15:57:588691
[email protected]cde4e80d2009-10-16 19:58:158692// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128693TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:118694 ASSERT_TRUE(test_server_.Start());
8695
[email protected]6cdfd7f2013-02-08 20:40:158696 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588697 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8698 app_path = app_path.AppendASCII("LICENSE");
8699 TestDelegate d;
8700 // Set correct login credentials. The delegate will be asked for them when
8701 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588702 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588703 {
[email protected]f7022f32014-08-21 16:32:198704 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8705 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8706 "chrome"),
8707 DEFAULT_PRIORITY, &d, NULL));
8708 r->Start();
8709 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588710
[email protected]255620da2013-08-19 13:14:298711 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588712
8713 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498714 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588715
[email protected]f7022f32014-08-21 16:32:198716 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588717 EXPECT_EQ(1, d.response_started_count());
8718 EXPECT_FALSE(d.received_data_before_response());
8719 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8720 }
8721}
[email protected]60a3df52009-09-22 16:13:248722
[email protected]cde4e80d2009-10-16 19:58:158723// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128724TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:118725 ASSERT_TRUE(test_server_.Start());
8726
[email protected]6cdfd7f2013-02-08 20:40:158727 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248728 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8729 app_path = app_path.AppendASCII("LICENSE");
8730
8731 scoped_ptr<TestDelegate> d(new TestDelegate);
8732 {
8733 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:198734 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:198735 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]f7022f32014-08-21 16:32:198736 DEFAULT_PRIORITY, d.get(), NULL));
8737 r->Start();
8738 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248739
[email protected]255620da2013-08-19 13:14:298740 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248741
8742 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498743 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248744
[email protected]f7022f32014-08-21 16:32:198745 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248746 EXPECT_EQ(1, d->response_started_count());
8747 EXPECT_FALSE(d->received_data_before_response());
8748 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8749 }
8750
8751 d.reset(new TestDelegate);
8752 {
8753 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:198754 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8755 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8756 r->Start();
8757 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248758
[email protected]255620da2013-08-19 13:14:298759 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248760
8761 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498762 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248763
[email protected]f7022f32014-08-21 16:32:198764 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248765 EXPECT_EQ(1, d->response_started_count());
8766 EXPECT_FALSE(d->received_data_before_response());
8767 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8768 }
8769}
8770
[email protected]cde4e80d2009-10-16 19:58:158771// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128772TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:118773 ASSERT_TRUE(test_server_.Start());
8774
[email protected]6cdfd7f2013-02-08 20:40:158775 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248776 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8777 app_path = app_path.AppendASCII("LICENSE");
8778
8779 scoped_ptr<TestDelegate> d(new TestDelegate);
8780 // Set correct login credentials. The delegate will be asked for them when
8781 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588782 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:248783 {
[email protected]f7022f32014-08-21 16:32:198784 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8785 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8786 "wrong_password"),
8787 DEFAULT_PRIORITY, d.get(), NULL));
8788 r->Start();
8789 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248790
[email protected]255620da2013-08-19 13:14:298791 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248792
8793 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498794 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248795
[email protected]f7022f32014-08-21 16:32:198796 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248797 EXPECT_EQ(1, d->response_started_count());
8798 EXPECT_FALSE(d->received_data_before_response());
8799 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8800 }
8801
8802 // Use a new delegate without explicit credentials. The cached ones should be
8803 // used.
8804 d.reset(new TestDelegate);
8805 {
8806 // Don't pass wrong credentials in the URL, they would override valid cached
8807 // ones.
[email protected]f7022f32014-08-21 16:32:198808 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8809 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8810 r->Start();
8811 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248812
[email protected]255620da2013-08-19 13:14:298813 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248814
8815 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498816 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248817
[email protected]f7022f32014-08-21 16:32:198818 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248819 EXPECT_EQ(1, d->response_started_count());
8820 EXPECT_FALSE(d->received_data_before_response());
8821 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8822 }
8823}
[email protected]316c1e5e2012-09-12 15:17:448824#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:518825
8826} // namespace net