blob: 3bb7c1544099f777b14def5060396b38f64b3902 [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.
[email protected]7461a402011-03-24 23:19:51261 int cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17262 ssl_info.connection_status);
263 EXPECT_NE(0, cipher_suite);
264}
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
1161// An Interceptor for use with interceptor tests
1162class TestInterceptor : URLRequest::Interceptor {
1163 public:
1164 TestInterceptor()
1165 : intercept_main_request_(false), restart_main_request_(false),
1166 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1167 simulate_main_network_error_(false),
1168 intercept_redirect_(false), cancel_redirect_request_(false),
1169 intercept_final_response_(false), cancel_final_request_(false),
1170 did_intercept_main_(false), did_restart_main_(false),
1171 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1172 did_simulate_error_main_(false),
1173 did_intercept_redirect_(false), did_cancel_redirect_(false),
1174 did_intercept_final_(false), did_cancel_final_(false) {
1175 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1176 }
1177
dchengb03027d2014-10-21 12:00:201178 ~TestInterceptor() override {
[email protected]316c1e5e2012-09-12 15:17:441179 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1180 }
1181
dchengb03027d2014-10-21 12:00:201182 URLRequestJob* MaybeIntercept(URLRequest* request,
1183 NetworkDelegate* network_delegate) override {
[email protected]316c1e5e2012-09-12 15:17:441184 if (restart_main_request_) {
1185 restart_main_request_ = false;
1186 did_restart_main_ = true;
1187 return new RestartTestJob(request, network_delegate);
1188 }
1189 if (cancel_main_request_) {
1190 cancel_main_request_ = false;
1191 did_cancel_main_ = true;
1192 return new CancelTestJob(request, network_delegate);
1193 }
1194 if (cancel_then_restart_main_request_) {
1195 cancel_then_restart_main_request_ = false;
1196 did_cancel_then_restart_main_ = true;
1197 return new CancelThenRestartTestJob(request, network_delegate);
1198 }
1199 if (simulate_main_network_error_) {
1200 simulate_main_network_error_ = false;
1201 did_simulate_error_main_ = true;
1202 // will error since the requeted url is not one of its canned urls
1203 return new URLRequestTestJob(request, network_delegate, true);
1204 }
1205 if (!intercept_main_request_)
1206 return NULL;
1207 intercept_main_request_ = false;
1208 did_intercept_main_ = true;
[email protected]2bba3252013-04-08 19:50:591209 URLRequestTestJob* job = new URLRequestTestJob(request,
1210 network_delegate,
1211 main_headers_,
1212 main_data_,
1213 true);
1214 job->set_load_timing_info(main_request_load_timing_info_);
1215 return job;
[email protected]316c1e5e2012-09-12 15:17:441216 }
1217
dchengb03027d2014-10-21 12:00:201218 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1219 NetworkDelegate* network_delegate,
1220 const GURL& location) override {
[email protected]316c1e5e2012-09-12 15:17:441221 if (cancel_redirect_request_) {
1222 cancel_redirect_request_ = false;
1223 did_cancel_redirect_ = true;
1224 return new CancelTestJob(request, network_delegate);
1225 }
1226 if (!intercept_redirect_)
1227 return NULL;
1228 intercept_redirect_ = false;
1229 did_intercept_redirect_ = true;
1230 return new URLRequestTestJob(request,
1231 network_delegate,
1232 redirect_headers_,
1233 redirect_data_,
1234 true);
1235 }
1236
dchengb03027d2014-10-21 12:00:201237 URLRequestJob* MaybeInterceptResponse(
1238 URLRequest* request,
1239 NetworkDelegate* network_delegate) override {
[email protected]316c1e5e2012-09-12 15:17:441240 if (cancel_final_request_) {
1241 cancel_final_request_ = false;
1242 did_cancel_final_ = true;
1243 return new CancelTestJob(request, network_delegate);
1244 }
1245 if (!intercept_final_response_)
1246 return NULL;
1247 intercept_final_response_ = false;
1248 did_intercept_final_ = true;
1249 return new URLRequestTestJob(request,
1250 network_delegate,
1251 final_headers_,
1252 final_data_,
1253 true);
1254 }
1255
[email protected]2bba3252013-04-08 19:50:591256 // Whether to intercept the main request, and if so the response to return and
1257 // the LoadTimingInfo to use.
[email protected]316c1e5e2012-09-12 15:17:441258 bool intercept_main_request_;
1259 std::string main_headers_;
1260 std::string main_data_;
[email protected]2bba3252013-04-08 19:50:591261 LoadTimingInfo main_request_load_timing_info_;
[email protected]316c1e5e2012-09-12 15:17:441262
1263 // Other actions we take at MaybeIntercept time
1264 bool restart_main_request_;
1265 bool cancel_main_request_;
1266 bool cancel_then_restart_main_request_;
1267 bool simulate_main_network_error_;
1268
1269 // Whether to intercept redirects, and if so the response to return.
1270 bool intercept_redirect_;
1271 std::string redirect_headers_;
1272 std::string redirect_data_;
1273
1274 // Other actions we can take at MaybeInterceptRedirect time
1275 bool cancel_redirect_request_;
1276
1277 // Whether to intercept final response, and if so the response to return.
1278 bool intercept_final_response_;
1279 std::string final_headers_;
1280 std::string final_data_;
1281
1282 // Other actions we can take at MaybeInterceptResponse time
1283 bool cancel_final_request_;
1284
1285 // If we did something or not
1286 bool did_intercept_main_;
1287 bool did_restart_main_;
1288 bool did_cancel_main_;
1289 bool did_cancel_then_restart_main_;
1290 bool did_simulate_error_main_;
1291 bool did_intercept_redirect_;
1292 bool did_cancel_redirect_;
1293 bool did_intercept_final_;
1294 bool did_cancel_final_;
1295
1296 // Static getters for canned response header and data strings
1297
1298 static std::string ok_data() {
1299 return URLRequestTestJob::test_data_1();
1300 }
1301
1302 static std::string ok_headers() {
1303 return URLRequestTestJob::test_headers();
1304 }
1305
1306 static std::string redirect_data() {
1307 return std::string();
1308 }
1309
1310 static std::string redirect_headers() {
1311 return URLRequestTestJob::test_redirect_headers();
1312 }
1313
1314 static std::string error_data() {
1315 return std::string("ohhh nooooo mr. bill!");
1316 }
1317
1318 static std::string error_headers() {
1319 return URLRequestTestJob::test_error_headers();
1320 }
1321};
1322
1323TEST_F(URLRequestTest, Intercept) {
1324 TestInterceptor interceptor;
1325
1326 // intercept the main request and respond with a simple response
1327 interceptor.intercept_main_request_ = true;
1328 interceptor.main_headers_ = TestInterceptor::ok_headers();
1329 interceptor.main_data_ = TestInterceptor::ok_data();
1330
1331 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191332 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1333 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:441334 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1335 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1336 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
[email protected]f7022f32014-08-21 16:32:191337 req->SetUserData(NULL, user_data0);
1338 req->SetUserData(&user_data1, user_data1);
1339 req->SetUserData(&user_data2, user_data2);
1340 req->set_method("GET");
1341 req->Start();
[email protected]255620da2013-08-19 13:14:291342 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441343
1344 // Make sure we can retrieve our specific user data
[email protected]f7022f32014-08-21 16:32:191345 EXPECT_EQ(user_data0, req->GetUserData(NULL));
1346 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1347 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]316c1e5e2012-09-12 15:17:441348
1349 // Check the interceptor got called as expected
1350 EXPECT_TRUE(interceptor.did_intercept_main_);
1351
1352 // Check we got one good response
[email protected]f7022f32014-08-21 16:32:191353 EXPECT_TRUE(req->status().is_success());
1354 EXPECT_EQ(200, req->response_headers()->response_code());
[email protected]316c1e5e2012-09-12 15:17:441355 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1356 EXPECT_EQ(1, d.response_started_count());
1357 EXPECT_EQ(0, d.received_redirect_count());
1358}
1359
1360TEST_F(URLRequestTest, InterceptRedirect) {
1361 TestInterceptor interceptor;
1362
1363 // intercept the main request and respond with a redirect
1364 interceptor.intercept_main_request_ = true;
1365 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1366 interceptor.main_data_ = TestInterceptor::redirect_data();
1367
1368 // intercept that redirect and respond a final OK response
1369 interceptor.intercept_redirect_ = true;
1370 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1371 interceptor.redirect_data_ = TestInterceptor::ok_data();
1372
1373 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191374 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1375 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1376 req->set_method("GET");
1377 req->Start();
[email protected]255620da2013-08-19 13:14:291378 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441379
1380 // Check the interceptor got called as expected
1381 EXPECT_TRUE(interceptor.did_intercept_main_);
1382 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1383
1384 // Check we got one good response
[email protected]f7022f32014-08-21 16:32:191385 EXPECT_TRUE(req->status().is_success());
1386 if (req->status().is_success()) {
1387 EXPECT_EQ(200, req->response_headers()->response_code());
[email protected]316c1e5e2012-09-12 15:17:441388 }
1389 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1390 EXPECT_EQ(1, d.response_started_count());
1391 EXPECT_EQ(0, d.received_redirect_count());
1392}
1393
1394TEST_F(URLRequestTest, InterceptServerError) {
1395 TestInterceptor interceptor;
1396
1397 // intercept the main request to generate a server error response
1398 interceptor.intercept_main_request_ = true;
1399 interceptor.main_headers_ = TestInterceptor::error_headers();
1400 interceptor.main_data_ = TestInterceptor::error_data();
1401
1402 // intercept that error and respond with an OK response
1403 interceptor.intercept_final_response_ = true;
1404 interceptor.final_headers_ = TestInterceptor::ok_headers();
1405 interceptor.final_data_ = TestInterceptor::ok_data();
1406
1407 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191408 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1409 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1410 req->set_method("GET");
1411 req->Start();
[email protected]255620da2013-08-19 13:14:291412 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441413
1414 // Check the interceptor got called as expected
1415 EXPECT_TRUE(interceptor.did_intercept_main_);
1416 EXPECT_TRUE(interceptor.did_intercept_final_);
1417
1418 // Check we got one good response
[email protected]f7022f32014-08-21 16:32:191419 EXPECT_TRUE(req->status().is_success());
1420 EXPECT_EQ(200, req->response_headers()->response_code());
[email protected]316c1e5e2012-09-12 15:17:441421 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1422 EXPECT_EQ(1, d.response_started_count());
1423 EXPECT_EQ(0, d.received_redirect_count());
1424}
1425
1426TEST_F(URLRequestTest, InterceptNetworkError) {
1427 TestInterceptor interceptor;
1428
1429 // intercept the main request to simulate a network error
1430 interceptor.simulate_main_network_error_ = true;
1431
1432 // intercept that error and respond with an OK response
1433 interceptor.intercept_final_response_ = true;
1434 interceptor.final_headers_ = TestInterceptor::ok_headers();
1435 interceptor.final_data_ = TestInterceptor::ok_data();
1436
1437 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191438 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1439 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1440 req->set_method("GET");
1441 req->Start();
[email protected]255620da2013-08-19 13:14:291442 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441443
1444 // Check the interceptor got called as expected
1445 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1446 EXPECT_TRUE(interceptor.did_intercept_final_);
1447
1448 // Check we received one good response
[email protected]f7022f32014-08-21 16:32:191449 EXPECT_TRUE(req->status().is_success());
1450 EXPECT_EQ(200, req->response_headers()->response_code());
[email protected]316c1e5e2012-09-12 15:17:441451 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1452 EXPECT_EQ(1, d.response_started_count());
1453 EXPECT_EQ(0, d.received_redirect_count());
1454}
1455
1456TEST_F(URLRequestTest, InterceptRestartRequired) {
1457 TestInterceptor interceptor;
1458
1459 // restart the main request
1460 interceptor.restart_main_request_ = true;
1461
1462 // then intercept the new main request and respond with an OK response
1463 interceptor.intercept_main_request_ = true;
1464 interceptor.main_headers_ = TestInterceptor::ok_headers();
1465 interceptor.main_data_ = TestInterceptor::ok_data();
1466
1467 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191468 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1469 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1470 req->set_method("GET");
1471 req->Start();
[email protected]255620da2013-08-19 13:14:291472 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441473
1474 // Check the interceptor got called as expected
1475 EXPECT_TRUE(interceptor.did_restart_main_);
1476 EXPECT_TRUE(interceptor.did_intercept_main_);
1477
1478 // Check we received one good response
[email protected]f7022f32014-08-21 16:32:191479 EXPECT_TRUE(req->status().is_success());
1480 if (req->status().is_success()) {
1481 EXPECT_EQ(200, req->response_headers()->response_code());
[email protected]316c1e5e2012-09-12 15:17:441482 }
1483 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1484 EXPECT_EQ(1, d.response_started_count());
1485 EXPECT_EQ(0, d.received_redirect_count());
1486}
1487
1488TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1489 TestInterceptor interceptor;
1490
1491 // intercept the main request and cancel from within the restarted job
1492 interceptor.cancel_main_request_ = true;
1493
1494 // setup to intercept final response and override it with an OK response
1495 interceptor.intercept_final_response_ = true;
1496 interceptor.final_headers_ = TestInterceptor::ok_headers();
1497 interceptor.final_data_ = TestInterceptor::ok_data();
1498
1499 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191500 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1501 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1502 req->set_method("GET");
1503 req->Start();
[email protected]255620da2013-08-19 13:14:291504 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441505
1506 // Check the interceptor got called as expected
1507 EXPECT_TRUE(interceptor.did_cancel_main_);
1508 EXPECT_FALSE(interceptor.did_intercept_final_);
1509
1510 // Check we see a canceled request
[email protected]f7022f32014-08-21 16:32:191511 EXPECT_FALSE(req->status().is_success());
1512 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:441513}
1514
1515TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1516 TestInterceptor interceptor;
1517
1518 // intercept the main request and respond with a redirect
1519 interceptor.intercept_main_request_ = true;
1520 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1521 interceptor.main_data_ = TestInterceptor::redirect_data();
1522
1523 // intercept the redirect and cancel from within that job
1524 interceptor.cancel_redirect_request_ = true;
1525
1526 // setup to intercept final response and override it with an OK response
1527 interceptor.intercept_final_response_ = true;
1528 interceptor.final_headers_ = TestInterceptor::ok_headers();
1529 interceptor.final_data_ = TestInterceptor::ok_data();
1530
1531 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191532 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1533 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1534 req->set_method("GET");
1535 req->Start();
[email protected]255620da2013-08-19 13:14:291536 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441537
1538 // Check the interceptor got called as expected
1539 EXPECT_TRUE(interceptor.did_intercept_main_);
1540 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1541 EXPECT_FALSE(interceptor.did_intercept_final_);
1542
1543 // Check we see a canceled request
[email protected]f7022f32014-08-21 16:32:191544 EXPECT_FALSE(req->status().is_success());
1545 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:441546}
1547
1548TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1549 TestInterceptor interceptor;
1550
1551 // intercept the main request to simulate a network error
1552 interceptor.simulate_main_network_error_ = true;
1553
1554 // setup to intercept final response and cancel from within that job
1555 interceptor.cancel_final_request_ = true;
1556
1557 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191558 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1559 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1560 req->set_method("GET");
1561 req->Start();
[email protected]255620da2013-08-19 13:14:291562 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441563
1564 // Check the interceptor got called as expected
1565 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1566 EXPECT_TRUE(interceptor.did_cancel_final_);
1567
1568 // Check we see a canceled request
[email protected]f7022f32014-08-21 16:32:191569 EXPECT_FALSE(req->status().is_success());
1570 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:441571}
1572
1573TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1574 TestInterceptor interceptor;
1575
1576 // intercept the main request and cancel then restart from within that job
1577 interceptor.cancel_then_restart_main_request_ = true;
1578
1579 // setup to intercept final response and override it with an OK response
1580 interceptor.intercept_final_response_ = true;
1581 interceptor.final_headers_ = TestInterceptor::ok_headers();
1582 interceptor.final_data_ = TestInterceptor::ok_data();
1583
1584 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191585 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1586 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1587 req->set_method("GET");
1588 req->Start();
[email protected]255620da2013-08-19 13:14:291589 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441590
1591 // Check the interceptor got called as expected
1592 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1593 EXPECT_FALSE(interceptor.did_intercept_final_);
1594
1595 // Check we see a canceled request
[email protected]f7022f32014-08-21 16:32:191596 EXPECT_FALSE(req->status().is_success());
1597 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:441598}
1599
bengr1bf8e942014-11-07 01:36:501600// An Interceptor for use with interceptor tests.
1601class MockURLRequestInterceptor : public URLRequestInterceptor {
1602 public:
1603 // Static getters for canned response header and data strings.
1604 static std::string ok_data() {
1605 return URLRequestTestJob::test_data_1();
1606 }
1607
1608 static std::string ok_headers() {
1609 return URLRequestTestJob::test_headers();
1610 }
1611
1612 static std::string redirect_data() {
1613 return std::string();
1614 }
1615
1616 static std::string redirect_headers() {
1617 return URLRequestTestJob::test_redirect_headers();
1618 }
1619
1620 static std::string error_data() {
1621 return std::string("ohhh nooooo mr. bill!");
1622 }
1623
1624 static std::string error_headers() {
1625 return URLRequestTestJob::test_error_headers();
1626 }
1627
1628 MockURLRequestInterceptor()
1629 : intercept_main_request_(false), restart_main_request_(false),
1630 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1631 simulate_main_network_error_(false),
1632 intercept_redirect_(false), cancel_redirect_request_(false),
1633 intercept_final_response_(false), cancel_final_request_(false),
1634 use_url_request_http_job_(false),
1635 did_intercept_main_(false), did_restart_main_(false),
1636 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1637 did_simulate_error_main_(false),
1638 did_intercept_redirect_(false), did_cancel_redirect_(false),
1639 did_intercept_final_(false), did_cancel_final_(false) {
1640 }
1641
1642 ~MockURLRequestInterceptor() override {
1643 }
1644
1645 // URLRequestInterceptor implementation:
1646 URLRequestJob* MaybeInterceptRequest(
1647 URLRequest* request,
1648 NetworkDelegate* network_delegate) const override {
1649 if (restart_main_request_) {
1650 restart_main_request_ = false;
1651 did_restart_main_ = true;
1652 return new RestartTestJob(request, network_delegate);
1653 }
1654 if (cancel_main_request_) {
1655 cancel_main_request_ = false;
1656 did_cancel_main_ = true;
1657 return new CancelTestJob(request, network_delegate);
1658 }
1659 if (cancel_then_restart_main_request_) {
1660 cancel_then_restart_main_request_ = false;
1661 did_cancel_then_restart_main_ = true;
1662 return new CancelThenRestartTestJob(request, network_delegate);
1663 }
1664 if (simulate_main_network_error_) {
1665 simulate_main_network_error_ = false;
1666 did_simulate_error_main_ = true;
1667 if (use_url_request_http_job_) {
1668 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1669 }
1670 // This job will result in error since the requested URL is not one of the
1671 // URLs supported by these tests.
1672 return new URLRequestTestJob(request, network_delegate, true);
1673 }
1674 if (!intercept_main_request_)
1675 return nullptr;
1676 intercept_main_request_ = false;
1677 did_intercept_main_ = true;
1678 URLRequestTestJob* job = new URLRequestTestJob(request,
1679 network_delegate,
1680 main_headers_,
1681 main_data_,
1682 true);
1683 job->set_load_timing_info(main_request_load_timing_info_);
1684 return job;
1685 }
1686
1687 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1688 NetworkDelegate* network_delegate,
1689 const GURL& location) const override {
1690 if (cancel_redirect_request_) {
1691 cancel_redirect_request_ = false;
1692 did_cancel_redirect_ = true;
1693 return new CancelTestJob(request, network_delegate);
1694 }
1695 if (!intercept_redirect_)
1696 return nullptr;
1697 intercept_redirect_ = false;
1698 did_intercept_redirect_ = true;
1699 if (use_url_request_http_job_) {
1700 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1701 }
1702 return new URLRequestTestJob(request,
1703 network_delegate,
1704 redirect_headers_,
1705 redirect_data_,
1706 true);
1707 }
1708
1709 URLRequestJob* MaybeInterceptResponse(
1710 URLRequest* request,
1711 NetworkDelegate* network_delegate) const override {
1712 if (cancel_final_request_) {
1713 cancel_final_request_ = false;
1714 did_cancel_final_ = true;
1715 return new CancelTestJob(request, network_delegate);
1716 }
1717 if (!intercept_final_response_)
1718 return nullptr;
1719 intercept_final_response_ = false;
1720 did_intercept_final_ = true;
1721 if (use_url_request_http_job_) {
1722 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1723 }
1724 return new URLRequestTestJob(request,
1725 network_delegate,
1726 final_headers_,
1727 final_data_,
1728 true);
1729 }
1730
1731 void set_intercept_main_request(bool intercept_main_request) {
1732 intercept_main_request_ = intercept_main_request;
1733 }
1734
1735 void set_main_headers(const std::string& main_headers) {
1736 main_headers_ = main_headers;
1737 }
1738
1739 void set_main_data(const std::string& main_data) {
1740 main_data_ = main_data;
1741 }
1742
1743 void set_main_request_load_timing_info(
1744 const LoadTimingInfo& main_request_load_timing_info) {
1745 main_request_load_timing_info_ = main_request_load_timing_info;
1746 }
1747
1748 void set_restart_main_request(bool restart_main_request) {
1749 restart_main_request_ = restart_main_request;
1750 }
1751
1752 void set_cancel_main_request(bool cancel_main_request) {
1753 cancel_main_request_ = cancel_main_request;
1754 }
1755
1756 void set_cancel_then_restart_main_request(
1757 bool cancel_then_restart_main_request) {
1758 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1759 }
1760
1761 void set_simulate_main_network_error(bool simulate_main_network_error) {
1762 simulate_main_network_error_ = simulate_main_network_error;
1763 }
1764
1765 void set_intercept_redirect(bool intercept_redirect) {
1766 intercept_redirect_ = intercept_redirect;
1767 }
1768
1769 void set_redirect_headers(const std::string& redirect_headers) {
1770 redirect_headers_ = redirect_headers;
1771 }
1772
1773 void set_redirect_data(const std::string& redirect_data) {
1774 redirect_data_ = redirect_data;
1775 }
1776
1777 void set_cancel_redirect_request(bool cancel_redirect_request) {
1778 cancel_redirect_request_ = cancel_redirect_request;
1779 }
1780
1781 void set_intercept_final_response(bool intercept_final_response) {
1782 intercept_final_response_ = intercept_final_response;
1783 }
1784
1785 void set_final_headers(const std::string& final_headers) {
1786 final_headers_ = final_headers;
1787 }
1788
1789 void set_final_data(const std::string& final_data) {
1790 final_data_ = final_data;
1791 }
1792
1793 void set_cancel_final_request(bool cancel_final_request) {
1794 cancel_final_request_ = cancel_final_request;
1795 }
1796
1797 void set_use_url_request_http_job(bool use_url_request_http_job) {
1798 use_url_request_http_job_ = use_url_request_http_job;
1799 }
1800
1801 bool did_intercept_main() const {
1802 return did_intercept_main_;
1803 }
1804
1805 bool did_restart_main() const {
1806 return did_restart_main_;
1807 }
1808
1809 bool did_cancel_main() const {
1810 return did_cancel_main_;
1811 }
1812
1813 bool did_cancel_then_restart_main() const {
1814 return did_cancel_then_restart_main_;
1815 }
1816
1817 bool did_simulate_error_main() const {
1818 return did_simulate_error_main_;
1819 }
1820
1821 bool did_intercept_redirect() const {
1822 return did_intercept_redirect_;
1823 }
1824
1825 bool did_cancel_redirect() const {
1826 return did_cancel_redirect_;
1827 }
1828
1829 bool did_intercept_final() const {
1830 return did_intercept_final_;
1831 }
1832
1833 bool did_cancel_final() const {
1834 return did_cancel_final_;
1835 }
1836
1837 private:
1838 // Indicate whether to intercept the main request, and if so specify the
1839 // response to return and the LoadTimingInfo to use.
1840 mutable bool intercept_main_request_;
1841 mutable std::string main_headers_;
1842 mutable std::string main_data_;
1843 mutable LoadTimingInfo main_request_load_timing_info_;
1844
1845 // These indicate actions that can be taken within MaybeInterceptRequest.
1846 mutable bool restart_main_request_;
1847 mutable bool cancel_main_request_;
1848 mutable bool cancel_then_restart_main_request_;
1849 mutable bool simulate_main_network_error_;
1850
1851 // Indicate whether to intercept redirects, and if so specify the response to
1852 // return.
1853 mutable bool intercept_redirect_;
1854 mutable std::string redirect_headers_;
1855 mutable std::string redirect_data_;
1856
1857 // Cancel the request within MaybeInterceptRedirect.
1858 mutable bool cancel_redirect_request_;
1859
1860 // Indicate whether to intercept the final response, and if so specify the
1861 // response to return.
1862 mutable bool intercept_final_response_;
1863 mutable std::string final_headers_;
1864 mutable std::string final_data_;
1865
1866 // Cancel the final request within MaybeInterceptResponse.
1867 mutable bool cancel_final_request_;
1868
1869 // Instruct the interceptor to use a real URLRequestHTTPJob.
1870 mutable bool use_url_request_http_job_;
1871
1872 // These indicate if the interceptor did something or not.
1873 mutable bool did_intercept_main_;
1874 mutable bool did_restart_main_;
1875 mutable bool did_cancel_main_;
1876 mutable bool did_cancel_then_restart_main_;
1877 mutable bool did_simulate_error_main_;
1878 mutable bool did_intercept_redirect_;
1879 mutable bool did_cancel_redirect_;
1880 mutable bool did_intercept_final_;
1881 mutable bool did_cancel_final_;
1882};
1883
1884// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1885class URLRequestInterceptorTest : public URLRequestTest {
1886 public:
1887 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1888 }
1889
1890 ~URLRequestInterceptorTest() override {
1891 // URLRequestJobs may post clean-up tasks on destruction.
1892 base::RunLoop().RunUntilIdle();
1893 }
1894
1895 void SetUpFactory() override {
1896 interceptor_ = new MockURLRequestInterceptor();
1897 job_factory_.reset(new URLRequestInterceptingJobFactory(
1898 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1899 }
1900
1901 MockURLRequestInterceptor* interceptor() const {
1902 return interceptor_;
1903 }
1904
1905 private:
1906 MockURLRequestInterceptor* interceptor_;
1907};
1908
1909TEST_F(URLRequestInterceptorTest, Intercept) {
1910 // Intercept the main request and respond with a simple response.
1911 interceptor()->set_intercept_main_request(true);
1912 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1913 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591914 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501915 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1916 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1917 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1918 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1919 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1920 req->SetUserData(nullptr, user_data0);
1921 req->SetUserData(&user_data1, user_data1);
1922 req->SetUserData(&user_data2, user_data2);
1923 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191924 req->Start();
[email protected]255620da2013-08-19 13:14:291925 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591926
bengr1bf8e942014-11-07 01:36:501927 // Make sure we can retrieve our specific user data.
1928 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1929 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1930 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591931
bengr1bf8e942014-11-07 01:36:501932 // Check that we got one good response.
1933 EXPECT_TRUE(req->status().is_success());
1934 EXPECT_EQ(200, req->response_headers()->response_code());
1935 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1936 EXPECT_EQ(1, d.response_started_count());
1937 EXPECT_EQ(0, d.received_redirect_count());
1938}
[email protected]2bba3252013-04-08 19:50:591939
bengr1bf8e942014-11-07 01:36:501940TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1941 // Intercept the main request and respond with a redirect.
1942 interceptor()->set_intercept_main_request(true);
1943 interceptor()->set_main_headers(
1944 MockURLRequestInterceptor::redirect_headers());
1945 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1946
1947 // Intercept that redirect and respond with a final OK response.
1948 interceptor()->set_intercept_redirect(true);
1949 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1950 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1951
1952 TestDelegate d;
1953 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1954 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1955 req->set_method("GET");
1956 req->Start();
1957 base::RunLoop().Run();
1958
1959 // Check that the interceptor got called as expected.
1960 EXPECT_TRUE(interceptor()->did_intercept_main());
1961 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1962
1963 // Check that we got one good response.
1964 EXPECT_TRUE(req->status().is_success());
1965 if (req->status().is_success())
1966 EXPECT_EQ(200, req->response_headers()->response_code());
1967
1968 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1969 EXPECT_EQ(1, d.response_started_count());
1970 EXPECT_EQ(0, d.received_redirect_count());
1971}
1972
1973TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1974 // Intercept the main request to generate a server error response.
1975 interceptor()->set_intercept_main_request(true);
1976 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1977 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1978
1979 // Intercept that error and respond with an OK response.
1980 interceptor()->set_intercept_final_response(true);
1981 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1982 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1983
1984 TestDelegate d;
1985 scoped_ptr<URLRequest> req(default_context().CreateRequest(
1986 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
1987 req->set_method("GET");
1988 req->Start();
1989 base::RunLoop().Run();
1990
1991 // Check that the interceptor got called as expected.
1992 EXPECT_TRUE(interceptor()->did_intercept_main());
1993 EXPECT_TRUE(interceptor()->did_intercept_final());
1994
1995 // Check that we got one good response.
1996 EXPECT_TRUE(req->status().is_success());
1997 EXPECT_EQ(200, req->response_headers()->response_code());
1998 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1999 EXPECT_EQ(1, d.response_started_count());
2000 EXPECT_EQ(0, d.received_redirect_count());
2001}
2002
2003TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
2004 // Intercept the main request to simulate a network error.
2005 interceptor()->set_simulate_main_network_error(true);
2006
2007 // Intercept that error and respond with an OK response.
2008 interceptor()->set_intercept_final_response(true);
2009 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2010 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2011
2012 TestDelegate d;
2013 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2014 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2015 req->set_method("GET");
2016 req->Start();
2017 base::RunLoop().Run();
2018
2019 // Check that the interceptor got called as expected.
2020 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2021 EXPECT_TRUE(interceptor()->did_intercept_final());
2022
2023 // Check that we received one good response.
2024 EXPECT_TRUE(req->status().is_success());
2025 EXPECT_EQ(200, req->response_headers()->response_code());
2026 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2027 EXPECT_EQ(1, d.response_started_count());
2028 EXPECT_EQ(0, d.received_redirect_count());
2029}
2030
2031TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
2032 // Restart the main request.
2033 interceptor()->set_restart_main_request(true);
2034
2035 // then intercept the new main request and respond with an OK response
2036 interceptor()->set_intercept_main_request(true);
2037 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
2038 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
2039
2040 TestDelegate d;
2041 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2042 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2043 req->set_method("GET");
2044 req->Start();
2045 base::RunLoop().Run();
2046
2047 // Check that the interceptor got called as expected.
2048 EXPECT_TRUE(interceptor()->did_restart_main());
2049 EXPECT_TRUE(interceptor()->did_intercept_main());
2050
2051 // Check that we received one good response.
2052 EXPECT_TRUE(req->status().is_success());
2053 if (req->status().is_success())
2054 EXPECT_EQ(200, req->response_headers()->response_code());
2055
2056 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
2057 EXPECT_EQ(1, d.response_started_count());
2058 EXPECT_EQ(0, d.received_redirect_count());
2059}
2060
2061TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
2062 // Intercept the main request and cancel from within the restarted job.
2063 interceptor()->set_cancel_main_request(true);
2064
2065 // Set up to intercept the final response and override it with an OK response.
2066 interceptor()->set_intercept_final_response(true);
2067 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2068 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2069
2070 TestDelegate d;
2071 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2072 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2073 req->set_method("GET");
2074 req->Start();
2075 base::RunLoop().Run();
2076
2077 // Check that the interceptor got called as expected.
2078 EXPECT_TRUE(interceptor()->did_cancel_main());
2079 EXPECT_FALSE(interceptor()->did_intercept_final());
2080
2081 // Check that we see a canceled request.
2082 EXPECT_FALSE(req->status().is_success());
2083 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2084}
2085
2086TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
2087 // Intercept the main request and respond with a redirect.
2088 interceptor()->set_intercept_main_request(true);
2089 interceptor()->set_main_headers(
2090 MockURLRequestInterceptor::redirect_headers());
2091 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
2092
2093 // Intercept the redirect and cancel from within that job.
2094 interceptor()->set_cancel_redirect_request(true);
2095
2096 // Set up to intercept the final response and override it with an OK response.
2097 interceptor()->set_intercept_final_response(true);
2098 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
2099 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
2100
2101 TestDelegate d;
2102 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2103 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2104 req->set_method("GET");
2105 req->Start();
2106 base::RunLoop().Run();
2107
2108 // Check that the interceptor got called as expected.
2109 EXPECT_TRUE(interceptor()->did_intercept_main());
2110 EXPECT_TRUE(interceptor()->did_cancel_redirect());
2111 EXPECT_FALSE(interceptor()->did_intercept_final());
2112
2113 // Check that we see a canceled request.
2114 EXPECT_FALSE(req->status().is_success());
2115 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2116}
2117
2118TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
2119 // Intercept the main request to simulate a network error.
2120 interceptor()->set_simulate_main_network_error(true);
2121
2122 // Set up to intercept final the response and cancel from within that job.
2123 interceptor()->set_cancel_final_request(true);
2124
2125 TestDelegate d;
2126 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2127 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2128 req->set_method("GET");
2129 req->Start();
2130 base::RunLoop().Run();
2131
2132 // Check that the interceptor got called as expected.
2133 EXPECT_TRUE(interceptor()->did_simulate_error_main());
2134 EXPECT_TRUE(interceptor()->did_cancel_final());
2135
2136 // Check that we see a canceled request.
2137 EXPECT_FALSE(req->status().is_success());
2138 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
2139}
2140
2141TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
2142 // Intercept the main request and cancel then restart from within that job.
2143 interceptor()->set_cancel_then_restart_main_request(true);
2144
2145 // Set up to intercept the final response and override it with an OK response.
2146 interceptor()->set_intercept_final_response(true);
2147 interceptor()->set_final_headers(TestInterceptor::ok_headers());
2148 interceptor()->set_final_data(TestInterceptor::ok_data());
2149
2150 TestDelegate d;
2151 scoped_ptr<URLRequest> req(default_context().CreateRequest(
2152 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2153 req->set_method("GET");
2154 req->Start();
2155 base::RunLoop().Run();
2156
2157 // Check that the interceptor got called as expected.
2158 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
2159 EXPECT_FALSE(interceptor()->did_intercept_final());
2160
2161 // Check that we see a canceled request.
2162 EXPECT_FALSE(req->status().is_success());
2163 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:592164}
2165
2166// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
2167// reused. |connect_time_flags| is used to indicate if there should be dns
2168// or SSL times, and |used_proxy| is used for proxy times.
2169LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
2170 int connect_time_flags,
2171 bool used_proxy) {
2172 LoadTimingInfo load_timing;
2173 load_timing.socket_log_id = 1;
2174
2175 if (used_proxy) {
2176 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2177 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2178 }
2179
2180 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
2181 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
2182 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
2183 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
2184 }
2185 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
2186 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
2187 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
2188 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
2189 }
2190 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
2191
2192 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2193 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2194 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2195 return load_timing;
2196}
2197
2198// Same as above, but in the case of a reused socket.
2199LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
2200 bool used_proxy) {
2201 LoadTimingInfo load_timing;
2202 load_timing.socket_log_id = 1;
2203 load_timing.socket_reused = true;
2204
2205 if (used_proxy) {
2206 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
2207 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
2208 }
2209
2210 load_timing.send_start = now + base::TimeDelta::FromDays(9);
2211 load_timing.send_end = now + base::TimeDelta::FromDays(10);
2212 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
2213 return load_timing;
2214}
2215
bengr1bf8e942014-11-07 01:36:502216LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
2217 const LoadTimingInfo& job_load_timing,
2218 const URLRequestContext& context,
2219 MockURLRequestInterceptor* interceptor) {
2220 interceptor->set_intercept_main_request(true);
2221 interceptor->set_main_request_load_timing_info(job_load_timing);
2222 TestDelegate d;
2223 scoped_ptr<URLRequest> req(context.CreateRequest(
2224 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, nullptr));
2225 req->Start();
2226 base::RunLoop().Run();
2227
2228 LoadTimingInfo resulting_load_timing;
2229 req->GetLoadTimingInfo(&resulting_load_timing);
2230
2231 // None of these should be modified by the URLRequest.
2232 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
2233 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
2234 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
2235 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
2236 EXPECT_EQ(job_load_timing.receive_headers_end,
2237 resulting_load_timing.receive_headers_end);
2238
2239 return resulting_load_timing;
2240}
2241
[email protected]2bba3252013-04-08 19:50:592242// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:502243TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:592244 base::TimeTicks now = base::TimeTicks::Now();
2245 LoadTimingInfo job_load_timing =
2246 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
2247
[email protected]2ca01e52013-10-31 22:05:192248 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502249 RunURLRequestInterceptorLoadTimingTest(
2250 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592251
2252 // Nothing should have been changed by the URLRequest.
2253 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2254 load_timing_result.proxy_resolve_start);
2255 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2256 load_timing_result.proxy_resolve_end);
2257 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2258 load_timing_result.connect_timing.dns_start);
2259 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2260 load_timing_result.connect_timing.dns_end);
2261 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2262 load_timing_result.connect_timing.connect_start);
2263 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2264 load_timing_result.connect_timing.connect_end);
2265 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2266 load_timing_result.connect_timing.ssl_start);
2267 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2268 load_timing_result.connect_timing.ssl_end);
2269
2270 // Redundant sanity check.
2271 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
2272}
2273
2274// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502275TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:592276 base::TimeTicks now = base::TimeTicks::Now();
2277 LoadTimingInfo job_load_timing =
2278 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
2279
[email protected]2ca01e52013-10-31 22:05:192280 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502281 RunURLRequestInterceptorLoadTimingTest(
2282 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592283
2284 // Nothing should have been changed by the URLRequest.
2285 EXPECT_EQ(job_load_timing.proxy_resolve_start,
2286 load_timing_result.proxy_resolve_start);
2287 EXPECT_EQ(job_load_timing.proxy_resolve_end,
2288 load_timing_result.proxy_resolve_end);
2289 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
2290 load_timing_result.connect_timing.dns_start);
2291 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
2292 load_timing_result.connect_timing.dns_end);
2293 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
2294 load_timing_result.connect_timing.connect_start);
2295 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
2296 load_timing_result.connect_timing.connect_end);
2297 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
2298 load_timing_result.connect_timing.ssl_start);
2299 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
2300 load_timing_result.connect_timing.ssl_end);
2301
2302 // Redundant sanity check.
2303 TestLoadTimingNotReusedWithProxy(load_timing_result,
2304 CONNECT_TIMING_HAS_SSL_TIMES);
2305}
2306
2307// Make sure that URLRequest correctly adjusts proxy times when they're before
2308// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:102309// the case of reusing a SPDY session. The connected socket is not considered
2310// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:592311//
2312// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:502313TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:592314 base::TimeTicks now = base::TimeTicks::Now();
2315 LoadTimingInfo job_load_timing =
2316 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
2317 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
2318 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
2319 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
2320 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
2321 job_load_timing.connect_timing.connect_start =
2322 now - base::TimeDelta::FromDays(2);
2323 job_load_timing.connect_timing.connect_end =
2324 now - base::TimeDelta::FromDays(1);
2325
[email protected]2ca01e52013-10-31 22:05:192326 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502327 RunURLRequestInterceptorLoadTimingTest(
2328 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592329
2330 // Proxy times, connect times, and DNS times should all be replaced with
2331 // request_start.
2332 EXPECT_EQ(load_timing_result.request_start,
2333 load_timing_result.proxy_resolve_start);
2334 EXPECT_EQ(load_timing_result.request_start,
2335 load_timing_result.proxy_resolve_end);
2336 EXPECT_EQ(load_timing_result.request_start,
2337 load_timing_result.connect_timing.dns_start);
2338 EXPECT_EQ(load_timing_result.request_start,
2339 load_timing_result.connect_timing.dns_end);
2340 EXPECT_EQ(load_timing_result.request_start,
2341 load_timing_result.connect_timing.connect_start);
2342 EXPECT_EQ(load_timing_result.request_start,
2343 load_timing_result.connect_timing.connect_end);
2344
2345 // Other times should have been left null.
2346 TestLoadTimingNotReusedWithProxy(load_timing_result,
2347 CONNECT_TIMING_HAS_DNS_TIMES);
2348}
2349
2350// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:502351TEST_F(URLRequestInterceptorTest,
2352 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:592353 base::TimeTicks now = base::TimeTicks::Now();
2354 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
2355 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
2356 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
2357
[email protected]2ca01e52013-10-31 22:05:192358 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502359 RunURLRequestInterceptorLoadTimingTest(
2360 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592361
2362 // Proxy times and connect times should all be replaced with request_start.
2363 EXPECT_EQ(load_timing_result.request_start,
2364 load_timing_result.proxy_resolve_start);
2365 EXPECT_EQ(load_timing_result.request_start,
2366 load_timing_result.proxy_resolve_end);
2367
2368 // Other times should have been left null.
2369 TestLoadTimingReusedWithProxy(load_timing_result);
2370}
2371
2372// Make sure that URLRequest correctly adjusts connect times when they're before
2373// |request_start|, due to reusing a connected socket. The connected socket is
2374// not considered reused in this test (May be a preconnect).
2375//
2376// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:502377TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:592378 base::TimeTicks now = base::TimeTicks::Now();
2379 LoadTimingInfo job_load_timing =
2380 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
2381 job_load_timing.connect_timing.connect_start =
2382 now - base::TimeDelta::FromDays(1);
2383 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
2384 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
2385 job_load_timing.connect_timing.connect_end =
2386 now - base::TimeDelta::FromDays(4);
2387
[email protected]2ca01e52013-10-31 22:05:192388 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502389 RunURLRequestInterceptorLoadTimingTest(
2390 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592391
2392 // Connect times, and SSL times should be replaced with request_start.
2393 EXPECT_EQ(load_timing_result.request_start,
2394 load_timing_result.connect_timing.connect_start);
2395 EXPECT_EQ(load_timing_result.request_start,
2396 load_timing_result.connect_timing.ssl_start);
2397 EXPECT_EQ(load_timing_result.request_start,
2398 load_timing_result.connect_timing.ssl_end);
2399 EXPECT_EQ(load_timing_result.request_start,
2400 load_timing_result.connect_timing.connect_end);
2401
2402 // Other times should have been left null.
2403 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
2404}
2405
2406// Make sure that URLRequest correctly adjusts connect times when they're before
2407// |request_start|, due to reusing a connected socket in the case that there
2408// are also proxy times. The connected socket is not considered reused in this
2409// test (May be a preconnect).
2410//
2411// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:502412TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:592413 base::TimeTicks now = base::TimeTicks::Now();
2414 LoadTimingInfo job_load_timing =
2415 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
2416 job_load_timing.connect_timing.connect_start =
2417 now - base::TimeDelta::FromDays(1);
2418 job_load_timing.connect_timing.connect_end =
2419 now - base::TimeDelta::FromDays(2);
2420
[email protected]2ca01e52013-10-31 22:05:192421 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:502422 RunURLRequestInterceptorLoadTimingTest(
2423 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:592424
2425 // Connect times should be replaced with proxy_resolve_end.
2426 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2427 load_timing_result.connect_timing.connect_start);
2428 EXPECT_EQ(load_timing_result.proxy_resolve_end,
2429 load_timing_result.connect_timing.connect_end);
2430
2431 // Other times should have been left null.
2432 TestLoadTimingNotReusedWithProxy(load_timing_result,
2433 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
2434}
2435
[email protected]316c1e5e2012-09-12 15:17:442436// Check that two different URL requests have different identifiers.
2437TEST_F(URLRequestTest, Identifiers) {
2438 TestDelegate d;
2439 TestURLRequestContext context;
mmenke19378d22014-09-09 04:12:592440 scoped_ptr<URLRequest> req(context.CreateRequest(
2441 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2442 scoped_ptr<URLRequest> other_req(context.CreateRequest(
2443 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:442444
mmenke19378d22014-09-09 04:12:592445 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442446}
2447
2448// Check that a failure to connect to the proxy is reported to the network
2449// delegate.
2450TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2451 MockHostResolver host_resolver;
2452 host_resolver.rules()->AddSimulatedFailure("*");
2453
[email protected]ceefd7fd2012-11-29 00:36:242454 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442455 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2456
2457 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192458 scoped_ptr<URLRequest> req(context.CreateRequest(
2459 GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
2460 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442461
[email protected]f7022f32014-08-21 16:32:192462 req->Start();
[email protected]255620da2013-08-19 13:14:292463 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442464
2465 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192466 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152467 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192468 EXPECT_TRUE(req->proxy_server().IsEmpty());
2469 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2470 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442471
2472 EXPECT_EQ(1, network_delegate.error_count());
2473 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2474 EXPECT_EQ(1, network_delegate.completed_requests());
2475}
2476
[email protected]cba24642014-08-15 20:49:592477// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442478// content is empty.
2479TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2480 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192481 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482 GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
2483 req->Start();
[email protected]255620da2013-08-19 13:14:292484 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442485 EXPECT_EQ("", d.data_received());
2486 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2487}
2488
[email protected]5033ab82013-03-22 20:17:462489// Make sure that SetPriority actually sets the URLRequest's priority
2490// correctly, both before and after start.
2491TEST_F(URLRequestTest, SetPriorityBasic) {
2492 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192493 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2494 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2495 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462496
[email protected]f7022f32014-08-21 16:32:192497 req->SetPriority(LOW);
2498 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462499
[email protected]f7022f32014-08-21 16:32:192500 req->Start();
2501 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462502
[email protected]f7022f32014-08-21 16:32:192503 req->SetPriority(MEDIUM);
2504 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462505}
2506
2507// Make sure that URLRequest calls SetPriority on a job before calling
2508// Start on it.
2509TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2510 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192511 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2512 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
2513 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462514
2515 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192516 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502517 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462518 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2519
[email protected]f7022f32014-08-21 16:32:192520 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462521
[email protected]f7022f32014-08-21 16:32:192522 req->Start();
[email protected]5033ab82013-03-22 20:17:462523 EXPECT_EQ(LOW, job->priority());
2524}
2525
2526// Make sure that URLRequest passes on its priority updates to its
2527// job.
2528TEST_F(URLRequestTest, SetJobPriority) {
2529 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192530 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2531 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5033ab82013-03-22 20:17:462532
2533 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192534 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502535 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462536
[email protected]f7022f32014-08-21 16:32:192537 req->SetPriority(LOW);
2538 req->Start();
[email protected]5033ab82013-03-22 20:17:462539 EXPECT_EQ(LOW, job->priority());
2540
[email protected]f7022f32014-08-21 16:32:192541 req->SetPriority(MEDIUM);
2542 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462543 EXPECT_EQ(MEDIUM, job->priority());
2544}
2545
[email protected]bb1c4662013-11-14 00:00:072546// Setting the IGNORE_LIMITS load flag should be okay if the priority
2547// is MAXIMUM_PRIORITY.
2548TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2549 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192550 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2551 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
2552 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072553
2554 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192555 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072556 AddTestInterceptor()->set_main_intercept_job(job.get());
2557
[email protected]f7022f32014-08-21 16:32:192558 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2559 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072560
[email protected]f7022f32014-08-21 16:32:192561 req->SetPriority(MAXIMUM_PRIORITY);
2562 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072563
[email protected]f7022f32014-08-21 16:32:192564 req->Start();
2565 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072566 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2567}
2568
[email protected]ce7d0cbc2013-05-03 18:57:222569// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442570#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:222571// A subclass of SpawnedTestServer that uses a statically-configured hostname.
2572// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:442573// http://crbug.com/114369
[email protected]cd6f2522014-01-16 18:27:352574// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
[email protected]ce7d0cbc2013-05-03 18:57:222575class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442576 public:
[email protected]6cdfd7f2013-02-08 20:40:152577 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222578 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2579 ScopedCustomUrlRequestTestHttpHost::value(),
2580 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442581 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222582 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2583 ScopedCustomUrlRequestTestHttpHost::value(),
2584 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442585};
2586
[email protected]f2f31b32013-01-16 23:24:092587TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442588 LocalHttpTestServer test_server;
2589 ASSERT_TRUE(test_server.Start());
2590
2591 TestURLRequestContext context;
2592 scoped_refptr<DelayedCookieMonster> delayed_cm =
2593 new DelayedCookieMonster();
2594 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502595 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442596
2597 // Set up a cookie.
2598 {
2599 TestNetworkDelegate network_delegate;
2600 context.set_network_delegate(&network_delegate);
2601 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192602 scoped_ptr<URLRequest> req(context.CreateRequest(
2603 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2604 &d, NULL));
2605 req->Start();
[email protected]255620da2013-08-19 13:14:292606 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442607 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2608 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2609 EXPECT_EQ(1, network_delegate.set_cookie_count());
2610 }
2611
2612 // Verify that the cookie is set.
2613 {
2614 TestNetworkDelegate network_delegate;
2615 context.set_network_delegate(&network_delegate);
2616 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192617 scoped_ptr<URLRequest> req(context.CreateRequest(
2618 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2619 req->Start();
[email protected]255620da2013-08-19 13:14:292620 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442621
2622 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2623 != std::string::npos);
2624 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2625 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2626 }
2627}
2628
[email protected]f2f31b32013-01-16 23:24:092629TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442630 LocalHttpTestServer test_server;
2631 ASSERT_TRUE(test_server.Start());
2632
2633 // Set up a cookie.
2634 {
2635 TestNetworkDelegate network_delegate;
2636 default_context_.set_network_delegate(&network_delegate);
2637 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192638 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2639 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2640 &d, NULL));
2641 req->Start();
[email protected]255620da2013-08-19 13:14:292642 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442643 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2644 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2645 }
2646
2647 // Verify that the cookie is set.
2648 {
2649 TestNetworkDelegate network_delegate;
2650 default_context_.set_network_delegate(&network_delegate);
2651 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192652 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2653 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2654 req->Start();
[email protected]255620da2013-08-19 13:14:292655 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442656
2657 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2658 != std::string::npos);
2659 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2660 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2661 }
2662
2663 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2664 {
2665 TestNetworkDelegate network_delegate;
2666 default_context_.set_network_delegate(&network_delegate);
2667 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192668 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2669 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2670 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2671 req->Start();
[email protected]255620da2013-08-19 13:14:292672 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442673
2674 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2675 == std::string::npos);
2676
2677 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2678 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2679 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2680 }
2681}
2682
2683TEST_F(URLRequestTest, DoNotSaveCookies) {
2684 LocalHttpTestServer test_server;
2685 ASSERT_TRUE(test_server.Start());
2686
2687 // Set up a cookie.
2688 {
2689 TestNetworkDelegate network_delegate;
2690 default_context_.set_network_delegate(&network_delegate);
2691 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192692 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2693 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2694 &d, NULL));
2695 req->Start();
[email protected]255620da2013-08-19 13:14:292696 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442697
2698 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2699 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2700 EXPECT_EQ(1, network_delegate.set_cookie_count());
2701 }
2702
2703 // Try to set-up another cookie and update the previous cookie.
2704 {
2705 TestNetworkDelegate network_delegate;
2706 default_context_.set_network_delegate(&network_delegate);
2707 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192708 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442709 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192710 DEFAULT_PRIORITY, &d, NULL));
2711 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2712 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442713
[email protected]255620da2013-08-19 13:14:292714 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442715
2716 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2717 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2718 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2719 EXPECT_EQ(0, network_delegate.set_cookie_count());
2720 }
2721
2722 // Verify the cookies weren't saved or updated.
2723 {
2724 TestNetworkDelegate network_delegate;
2725 default_context_.set_network_delegate(&network_delegate);
2726 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192727 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2728 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2729 req->Start();
[email protected]255620da2013-08-19 13:14:292730 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442731
2732 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2733 == std::string::npos);
2734 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2735 != std::string::npos);
2736
2737 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2738 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2739 EXPECT_EQ(0, network_delegate.set_cookie_count());
2740 }
2741}
2742
2743TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2744 LocalHttpTestServer test_server;
2745 ASSERT_TRUE(test_server.Start());
2746
2747 // Set up a cookie.
2748 {
2749 TestNetworkDelegate network_delegate;
2750 default_context_.set_network_delegate(&network_delegate);
2751 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192752 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2753 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2754 &d, NULL));
2755 req->Start();
[email protected]255620da2013-08-19 13:14:292756 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442757
2758 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2759 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2760 }
2761
2762 // Verify that the cookie is set.
2763 {
2764 TestNetworkDelegate network_delegate;
2765 default_context_.set_network_delegate(&network_delegate);
2766 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192767 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2768 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2769 req->Start();
[email protected]255620da2013-08-19 13:14:292770 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442771
2772 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2773 != std::string::npos);
2774
2775 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2776 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2777 }
2778
2779 // Verify that the cookie isn't sent.
2780 {
2781 TestNetworkDelegate network_delegate;
2782 default_context_.set_network_delegate(&network_delegate);
2783 TestDelegate d;
2784 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192785 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2786 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2787 req->Start();
[email protected]255620da2013-08-19 13:14:292788 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442789
2790 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2791 == std::string::npos);
2792
[email protected]22e045f2013-09-20 03:54:032793 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442794 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2795 }
2796}
2797
2798TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2799 LocalHttpTestServer test_server;
2800 ASSERT_TRUE(test_server.Start());
2801
2802 // Set up a cookie.
2803 {
2804 TestNetworkDelegate network_delegate;
2805 default_context_.set_network_delegate(&network_delegate);
2806 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192807 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2808 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2809 &d, NULL));
2810 req->Start();
[email protected]255620da2013-08-19 13:14:292811 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442812
2813 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2814 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2815 }
2816
2817 // Try to set-up another cookie and update the previous cookie.
2818 {
2819 TestNetworkDelegate network_delegate;
2820 default_context_.set_network_delegate(&network_delegate);
2821 TestDelegate d;
2822 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192823 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442824 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192825 DEFAULT_PRIORITY, &d, NULL));
2826 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442827
[email protected]255620da2013-08-19 13:14:292828 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442829
2830 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2831 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2832 }
2833
2834 // Verify the cookies weren't saved or updated.
2835 {
2836 TestNetworkDelegate network_delegate;
2837 default_context_.set_network_delegate(&network_delegate);
2838 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192839 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2840 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2841 req->Start();
[email protected]255620da2013-08-19 13:14:292842 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442843
2844 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2845 == std::string::npos);
2846 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2847 != std::string::npos);
2848
2849 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2850 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2851 }
2852}
2853
2854TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2855 LocalHttpTestServer test_server;
2856 ASSERT_TRUE(test_server.Start());
2857
2858 // Set up an empty cookie.
2859 {
2860 TestNetworkDelegate network_delegate;
2861 default_context_.set_network_delegate(&network_delegate);
2862 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192863 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2864 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2865 req->Start();
[email protected]255620da2013-08-19 13:14:292866 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442867
2868 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2869 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2870 EXPECT_EQ(0, network_delegate.set_cookie_count());
2871 }
2872}
2873
2874TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2875 LocalHttpTestServer test_server;
2876 ASSERT_TRUE(test_server.Start());
2877
2878 // Set up a cookie.
2879 {
2880 TestNetworkDelegate network_delegate;
2881 default_context_.set_network_delegate(&network_delegate);
2882 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192883 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2884 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2885 &d, NULL));
2886 req->Start();
[email protected]255620da2013-08-19 13:14:292887 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442888
2889 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2890 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2891 }
2892
2893 // Verify that the cookie is set.
2894 {
2895 TestNetworkDelegate network_delegate;
2896 default_context_.set_network_delegate(&network_delegate);
2897 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192898 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2899 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2900 req->Start();
[email protected]255620da2013-08-19 13:14:292901 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442902
2903 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2904 != std::string::npos);
2905
2906 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2907 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2908 }
2909
2910 // Verify that the cookie isn't sent.
2911 {
2912 TestNetworkDelegate network_delegate;
2913 default_context_.set_network_delegate(&network_delegate);
2914 TestDelegate d;
2915 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192916 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2917 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2918 req->Start();
[email protected]255620da2013-08-19 13:14:292919 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442920
2921 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2922 == std::string::npos);
2923
[email protected]22e045f2013-09-20 03:54:032924 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442925 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2926 }
2927}
2928
2929TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2930 LocalHttpTestServer test_server;
2931 ASSERT_TRUE(test_server.Start());
2932
2933 // Set up a cookie.
2934 {
2935 TestNetworkDelegate network_delegate;
2936 default_context_.set_network_delegate(&network_delegate);
2937 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192938 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2939 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2940 &d, NULL));
2941 req->Start();
[email protected]255620da2013-08-19 13:14:292942 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442943
2944 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2945 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2946 }
2947
2948 // Try to set-up another cookie and update the previous cookie.
2949 {
2950 TestNetworkDelegate network_delegate;
2951 default_context_.set_network_delegate(&network_delegate);
2952 TestDelegate d;
2953 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192954 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442955 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
[email protected]f7022f32014-08-21 16:32:192956 DEFAULT_PRIORITY, &d, NULL));
2957 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442958
[email protected]255620da2013-08-19 13:14:292959 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442960
2961 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2962 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2963 }
2964
2965 // Verify the cookies weren't saved or updated.
2966 {
2967 TestNetworkDelegate network_delegate;
2968 default_context_.set_network_delegate(&network_delegate);
2969 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192970 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2971 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2972 req->Start();
[email protected]255620da2013-08-19 13:14:292973 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442974
2975 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2976 == std::string::npos);
2977 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2978 != std::string::npos);
2979
2980 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2981 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2982 }
2983}
2984
[email protected]5095cd72012-11-01 10:29:162985// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2986// value for the |fixed_date| argument given to the constructor.
2987class FixedDateNetworkDelegate : public TestNetworkDelegate {
2988 public:
2989 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2990 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202991 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162992
[email protected]cba24642014-08-15 20:49:592993 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202994 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592995 URLRequest* request,
2996 const CompletionCallback& callback,
2997 const HttpResponseHeaders* original_response_headers,
2998 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132999 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:163000
3001 private:
3002 std::string fixed_date_;
3003
3004 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
3005};
3006
3007int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:593008 URLRequest* request,
3009 const CompletionCallback& callback,
3010 const HttpResponseHeaders* original_response_headers,
3011 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:163012 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:593013 HttpResponseHeaders* new_response_headers =
3014 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:163015
3016 new_response_headers->RemoveHeader("Date");
3017 new_response_headers->AddHeader("Date: " + fixed_date_);
3018
3019 *override_response_headers = new_response_headers;
3020 return TestNetworkDelegate::OnHeadersReceived(request,
3021 callback,
3022 original_response_headers,
[email protected]5f714132014-03-26 10:41:163023 override_response_headers,
3024 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:163025}
3026
3027// Test that cookie expiration times are adjusted for server/client clock
3028// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
3029// headers by defaulting to GMT. (crbug.com/135131)
3030TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
3031 LocalHttpTestServer test_server;
3032 ASSERT_TRUE(test_server.Start());
3033
3034 // Set up an expired cookie.
3035 {
3036 TestNetworkDelegate network_delegate;
3037 default_context_.set_network_delegate(&network_delegate);
3038 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193039 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193040 test_server.GetURL(
3041 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
[email protected]f7022f32014-08-21 16:32:193042 DEFAULT_PRIORITY, &d, NULL));
3043 req->Start();
[email protected]255620da2013-08-19 13:14:293044 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163045 }
3046 // Verify that the cookie is not set.
3047 {
3048 TestNetworkDelegate network_delegate;
3049 default_context_.set_network_delegate(&network_delegate);
3050 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193051 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3052 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3053 req->Start();
[email protected]255620da2013-08-19 13:14:293054 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163055
3056 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
3057 }
3058 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
3059 {
3060 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
3061 default_context_.set_network_delegate(&network_delegate);
3062 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193063 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:193064 test_server.GetURL(
3065 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
[email protected]f7022f32014-08-21 16:32:193066 DEFAULT_PRIORITY, &d, NULL));
3067 req->Start();
[email protected]255620da2013-08-19 13:14:293068 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163069 }
3070 // Verify that the cookie is set.
3071 {
3072 TestNetworkDelegate network_delegate;
3073 default_context_.set_network_delegate(&network_delegate);
3074 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193075 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3076 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
3077 req->Start();
[email protected]255620da2013-08-19 13:14:293078 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:163079
3080 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
3081 }
3082}
3083
3084
[email protected]316c1e5e2012-09-12 15:17:443085// Check that it is impossible to change the referrer in the extra headers of
3086// an URLRequest.
3087TEST_F(URLRequestTest, DoNotOverrideReferrer) {
3088 LocalHttpTestServer test_server;
3089 ASSERT_TRUE(test_server.Start());
3090
3091 // If extra headers contain referer and the request contains a referer,
3092 // only the latter shall be respected.
3093 {
3094 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193095 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3096 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
3097 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:443098
3099 HttpRequestHeaders headers;
3100 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193101 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:443102
[email protected]f7022f32014-08-21 16:32:193103 req->Start();
[email protected]255620da2013-08-19 13:14:293104 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443105
3106 EXPECT_EQ("http://foo.com/", d.data_received());
3107 }
3108
3109 // If extra headers contain a referer but the request does not, no referer
3110 // shall be sent in the header.
3111 {
3112 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193113 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3114 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:443115
3116 HttpRequestHeaders headers;
3117 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:193118 req->SetExtraRequestHeaders(headers);
3119 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:443120
[email protected]f7022f32014-08-21 16:32:193121 req->Start();
[email protected]255620da2013-08-19 13:14:293122 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443123
3124 EXPECT_EQ("None", d.data_received());
3125 }
3126}
3127
[email protected]b89290212009-08-14 22:37:353128class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:113129 public:
3130 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:153131 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:113132 "net/data/url_request_unittest"))) {
3133 }
3134
[email protected]b89290212009-08-14 22:37:353135 protected:
[email protected]21184962011-10-26 00:50:303136 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
3137 // |request_method| is the method to use for the initial request.
3138 // |redirect_method| is the method that is expected to be used for the second
3139 // request, after redirection.
3140 // If |include_data| is true, data is uploaded with the request. The
3141 // response body is expected to match it exactly, if and only if
3142 // |request_method| == |redirect_method|.
3143 void HTTPRedirectMethodTest(const GURL& redirect_url,
3144 const std::string& request_method,
3145 const std::string& redirect_method,
3146 bool include_data) {
3147 static const char kData[] = "hello world";
3148 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193149 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
3150 redirect_url, DEFAULT_PRIORITY, &d, NULL));
3151 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:303152 if (include_data) {
mmenkecbc2b712014-10-09 20:29:073153 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:303154 HttpRequestHeaders headers;
3155 headers.SetHeader(HttpRequestHeaders::kContentLength,
3156 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193157 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:303158 }
[email protected]f7022f32014-08-21 16:32:193159 req->Start();
[email protected]255620da2013-08-19 13:14:293160 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193161 EXPECT_EQ(redirect_method, req->method());
3162 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
3163 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:303164 if (include_data) {
3165 if (request_method == redirect_method) {
3166 EXPECT_EQ(kData, d.data_received());
3167 } else {
3168 EXPECT_NE(kData, d.data_received());
3169 }
3170 }
3171 if (HasFailure())
3172 LOG(WARNING) << "Request method was: " << request_method;
3173 }
3174
[email protected]762d2db2010-01-11 19:03:013175 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:013176 const int kMsgSize = 20000; // multiple of 10
3177 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:483178 char* uploadBytes = new char[kMsgSize+1];
3179 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:013180 char marker = 'a';
3181 for (int idx = 0; idx < kMsgSize/10; idx++) {
3182 memcpy(ptr, "----------", 10);
3183 ptr += 10;
3184 if (idx % 100 == 0) {
3185 ptr--;
3186 *ptr++ = marker;
3187 if (++marker > 'z')
3188 marker = 'a';
3189 }
3190 }
3191 uploadBytes[kMsgSize] = '\0';
3192
[email protected]762d2db2010-01-11 19:03:013193 for (int i = 0; i < kIterations; ++i) {
3194 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193195 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3196 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
3197 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:013198
mmenkecbc2b712014-10-09 20:29:073199 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:013200
[email protected]f7022f32014-08-21 16:32:193201 r->Start();
3202 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:013203
[email protected]255620da2013-08-19 13:14:293204 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:013205
[email protected]329b68b2012-11-14 17:54:273206 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:193207 << "request failed: " << r->status().status()
3208 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:013209
3210 EXPECT_FALSE(d.received_data_before_response());
3211 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:013212 }
3213 delete[] uploadBytes;
3214 }
3215
[email protected]ef2bf422012-05-11 03:27:093216 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:223217 r->AppendChunkToUpload("a", 1, false);
3218 r->AppendChunkToUpload("bcd", 3, false);
3219 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
3220 r->AppendChunkToUpload("\r\n\r\n", 4, false);
3221 r->AppendChunkToUpload("0", 1, false);
3222 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:113223 }
3224
[email protected]ef2bf422012-05-11 03:27:093225 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:113226 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:273227 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:113228 "abcdthis is a longer chunk than before.\r\n\r\n02323";
3229
[email protected]329b68b2012-11-14 17:54:273230 ASSERT_EQ(1, d->response_started_count())
3231 << "request failed: " << r->status().status()
3232 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:113233
3234 EXPECT_FALSE(d->received_data_before_response());
3235
[email protected]329b68b2012-11-14 17:54:273236 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
3237 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:113238 }
3239
[email protected]ede03212012-09-07 12:52:263240 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:343241 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:193242 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
3243 test_server_.GetURL("set-many-cookies?" +
3244 base::IntToString(num_cookies)),
3245 DEFAULT_PRIORITY, &d, NULL));
[email protected]263163f2012-06-14 22:40:343246
[email protected]f7022f32014-08-21 16:32:193247 r->Start();
3248 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:343249
[email protected]255620da2013-08-19 13:14:293250 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:343251
[email protected]f7022f32014-08-21 16:32:193252 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:343253
[email protected]ede03212012-09-07 12:52:263254 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:193255 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:343256 // The test server appears to be unable to handle subsequent requests
3257 // after this error is triggered. Force it to restart.
3258 EXPECT_TRUE(test_server_.Stop());
3259 EXPECT_TRUE(test_server_.Start());
3260 }
3261
3262 return is_success;
3263 }
3264
bengr1bf8e942014-11-07 01:36:503265 LocalHttpTestServer* test_server() {
3266 return &test_server_;
3267 }
3268
3269 protected:
[email protected]1700c6a2012-02-22 18:07:073270 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:353271};
3272
[email protected]95409e12010-08-17 20:07:113273// In this unit test, we're using the HTTPTestServer as a proxy server and
3274// issuing a CONNECT request with the magic host name "www.redirect.com".
3275// The HTTPTestServer will return a 302 response, which we should not
3276// follow.
[email protected]f2f31b32013-01-16 23:24:093277TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:113278 ASSERT_TRUE(test_server_.Start());
3279
[email protected]ceefd7fd2012-11-29 00:36:243280 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043281 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193282 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503283
[email protected]d1ec59082009-02-11 02:48:153284 TestDelegate d;
3285 {
[email protected]f7022f32014-08-21 16:32:193286 scoped_ptr<URLRequest> r(context.CreateRequest(
3287 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3288 r->Start();
3289 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:153290
[email protected]255620da2013-08-19 13:14:293291 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:153292
[email protected]f7022f32014-08-21 16:32:193293 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153294 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193295 EXPECT_TRUE(r->proxy_server().IsEmpty());
3296 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083297 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:153298 // We should not have followed the redirect.
3299 EXPECT_EQ(0, d.received_redirect_count());
3300 }
3301}
3302
[email protected]8202d0c2011-02-23 08:31:143303// This is the same as the previous test, but checks that the network delegate
3304// registers the error.
[email protected]c044616e2013-02-20 02:01:263305TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:143306 ASSERT_TRUE(test_server_.Start());
3307
[email protected]ceefd7fd2012-11-29 00:36:243308 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043309 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193310 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503311
[email protected]8202d0c2011-02-23 08:31:143312 TestDelegate d;
3313 {
[email protected]f7022f32014-08-21 16:32:193314 scoped_ptr<URLRequest> r(context.CreateRequest(
3315 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
3316 r->Start();
3317 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:143318
[email protected]255620da2013-08-19 13:14:293319 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:143320
[email protected]f7022f32014-08-21 16:32:193321 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153322 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193323 EXPECT_TRUE(r->proxy_server().IsEmpty());
3324 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:143325 EXPECT_EQ(1, d.response_started_count());
3326 // We should not have followed the redirect.
3327 EXPECT_EQ(0, d.received_redirect_count());
3328
3329 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:053330 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:143331 }
3332}
3333
[email protected]dc5a5cf2012-09-26 02:49:303334// Tests that we can block and asynchronously return OK in various stages.
3335TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
3336 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
3337 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3338 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3339 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
3340 };
3341 static const size_t blocking_stages_length = arraysize(blocking_stages);
3342
3343 ASSERT_TRUE(test_server_.Start());
3344
3345 TestDelegate d;
3346 BlockingNetworkDelegate network_delegate(
3347 BlockingNetworkDelegate::USER_CALLBACK);
3348 network_delegate.set_block_on(
3349 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3350 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3351 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3352
3353 TestURLRequestContext context(true);
3354 context.set_network_delegate(&network_delegate);
3355 context.Init();
3356
3357 {
[email protected]f7022f32014-08-21 16:32:193358 scoped_ptr<URLRequest> r(context.CreateRequest(
3359 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
[email protected]dc5a5cf2012-09-26 02:49:303360
[email protected]f7022f32014-08-21 16:32:193361 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303362 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293363 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303364 EXPECT_EQ(blocking_stages[i],
3365 network_delegate.stage_blocked_for_callback());
3366 network_delegate.DoCallback(OK);
3367 }
[email protected]255620da2013-08-19 13:14:293368 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193369 EXPECT_EQ(200, r->GetResponseCode());
3370 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303371 EXPECT_EQ(1, network_delegate.created_requests());
3372 EXPECT_EQ(0, network_delegate.destroyed_requests());
3373 }
3374 EXPECT_EQ(1, network_delegate.destroyed_requests());
3375}
3376
[email protected]4c76d7c2011-04-15 19:14:123377// Tests that the network delegate can block and cancel a request.
3378TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3379 ASSERT_TRUE(test_server_.Start());
3380
3381 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303382 BlockingNetworkDelegate network_delegate(
3383 BlockingNetworkDelegate::AUTO_CALLBACK);
3384 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3385 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123386
[email protected]d5a4dd62012-05-23 01:41:043387 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193388 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503389
[email protected]4c76d7c2011-04-15 19:14:123390 {
[email protected]f7022f32014-08-21 16:32:193391 scoped_ptr<URLRequest> r(context.CreateRequest(
3392 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]4c76d7c2011-04-15 19:14:123393
[email protected]f7022f32014-08-21 16:32:193394 r->Start();
[email protected]255620da2013-08-19 13:14:293395 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123396
[email protected]f7022f32014-08-21 16:32:193397 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153398 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193399 EXPECT_TRUE(r->proxy_server().IsEmpty());
3400 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123401 EXPECT_EQ(1, network_delegate.created_requests());
3402 EXPECT_EQ(0, network_delegate.destroyed_requests());
3403 }
3404 EXPECT_EQ(1, network_delegate.destroyed_requests());
3405}
3406
[email protected]b4438d32012-09-27 06:15:303407// Helper function for NetworkDelegateCancelRequestAsynchronously and
3408// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3409// delegate operating in |block_mode| and a request for |url|. It blocks the
3410// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3411void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3412 BlockingNetworkDelegate::Stage stage,
3413 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363414 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303415 BlockingNetworkDelegate network_delegate(block_mode);
3416 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3417 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363418
[email protected]b4438d32012-09-27 06:15:303419 TestURLRequestContext context(true);
3420 context.set_network_delegate(&network_delegate);
3421 context.Init();
[email protected]3cd384c602011-08-31 16:12:363422
3423 {
[email protected]f7022f32014-08-21 16:32:193424 scoped_ptr<URLRequest> r(context.CreateRequest(
3425 url, DEFAULT_PRIORITY, &d, NULL));
[email protected]3cd384c602011-08-31 16:12:363426
[email protected]f7022f32014-08-21 16:32:193427 r->Start();
[email protected]255620da2013-08-19 13:14:293428 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363429
[email protected]f7022f32014-08-21 16:32:193430 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153431 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193432 EXPECT_TRUE(r->proxy_server().IsEmpty());
3433 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363434 EXPECT_EQ(1, network_delegate.created_requests());
3435 EXPECT_EQ(0, network_delegate.destroyed_requests());
3436 }
3437 EXPECT_EQ(1, network_delegate.destroyed_requests());
3438}
3439
[email protected]b4438d32012-09-27 06:15:303440// The following 3 tests check that the network delegate can cancel a request
3441// synchronously in various stages of the request.
3442TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3443 ASSERT_TRUE(test_server_.Start());
3444 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3445 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453446 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303447}
3448
3449TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3450 ASSERT_TRUE(test_server_.Start());
3451 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3452 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453453 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303454}
3455
3456TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3457 ASSERT_TRUE(test_server_.Start());
3458 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3459 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453460 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303461}
3462
3463// The following 3 tests check that the network delegate can cancel a request
3464// asynchronously in various stages of the request.
3465TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3466 ASSERT_TRUE(test_server_.Start());
3467 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3468 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453469 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303470}
3471
3472TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3473 ASSERT_TRUE(test_server_.Start());
3474 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3475 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453476 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303477}
3478
3479TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3480 ASSERT_TRUE(test_server_.Start());
3481 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3482 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453483 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303484}
3485
[email protected]4c76d7c2011-04-15 19:14:123486// Tests that the network delegate can block and redirect a request to a new
3487// URL.
3488TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3489 ASSERT_TRUE(test_server_.Start());
3490
3491 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303492 BlockingNetworkDelegate network_delegate(
3493 BlockingNetworkDelegate::AUTO_CALLBACK);
3494 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123495 GURL redirect_url(test_server_.GetURL("simple.html"));
3496 network_delegate.set_redirect_url(redirect_url);
3497
[email protected]d5a4dd62012-05-23 01:41:043498 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193499 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503500
[email protected]4c76d7c2011-04-15 19:14:123501 {
[email protected]8f1ac082011-04-19 21:14:133502 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193503 scoped_ptr<URLRequest> r(context.CreateRequest(
3504 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]4c76d7c2011-04-15 19:14:123505
[email protected]6be6fa92014-08-06 23:44:563506 // Quit after hitting the redirect, so can check the headers.
3507 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193508 r->Start();
[email protected]255620da2013-08-19 13:14:293509 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123510
[email protected]6be6fa92014-08-06 23:44:563511 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193512 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3513 EXPECT_EQ(307, r->GetResponseCode());
3514 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563515 std::string location;
[email protected]f7022f32014-08-21 16:32:193516 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3517 &location));
[email protected]6be6fa92014-08-06 23:44:563518 EXPECT_EQ(redirect_url, GURL(location));
3519
3520 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193521 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563522 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193523 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3524 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273525 EXPECT_EQ(
3526 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3527 EXPECT_TRUE(
3528 network_delegate.last_observed_proxy().Equals(
3529 test_server_.host_port_pair()));
3530
[email protected]f7022f32014-08-21 16:32:193531 EXPECT_EQ(0, r->status().error());
3532 EXPECT_EQ(redirect_url, r->url());
3533 EXPECT_EQ(original_url, r->original_url());
3534 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123535 EXPECT_EQ(1, network_delegate.created_requests());
3536 EXPECT_EQ(0, network_delegate.destroyed_requests());
3537 }
3538 EXPECT_EQ(1, network_delegate.destroyed_requests());
3539}
3540
[email protected]b813ed72012-04-05 08:21:363541// Tests that the network delegate can block and redirect a request to a new
3542// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3543TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3544 ASSERT_TRUE(test_server_.Start());
3545
3546 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303547 BlockingNetworkDelegate network_delegate(
3548 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363549 GURL redirect_url(test_server_.GetURL("simple.html"));
3550 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363551
[email protected]d5a4dd62012-05-23 01:41:043552 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193553 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363554
3555 {
3556 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193557 scoped_ptr<URLRequest> r(context.CreateRequest(
3558 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]b813ed72012-04-05 08:21:363559
[email protected]6be6fa92014-08-06 23:44:563560 // Quit after hitting the redirect, so can check the headers.
3561 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193562 r->Start();
[email protected]255620da2013-08-19 13:14:293563 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363564
[email protected]6be6fa92014-08-06 23:44:563565 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193566 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3567 EXPECT_EQ(307, r->GetResponseCode());
3568 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563569 std::string location;
[email protected]f7022f32014-08-21 16:32:193570 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3571 &location));
[email protected]6be6fa92014-08-06 23:44:563572 EXPECT_EQ(redirect_url, GURL(location));
3573
3574 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193575 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563576 base::RunLoop().Run();
3577
[email protected]f7022f32014-08-21 16:32:193578 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3579 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273580 EXPECT_EQ(
3581 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3582 EXPECT_TRUE(
3583 network_delegate.last_observed_proxy().Equals(
3584 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193585 EXPECT_EQ(0, r->status().error());
3586 EXPECT_EQ(redirect_url, r->url());
3587 EXPECT_EQ(original_url, r->original_url());
3588 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363589 EXPECT_EQ(1, network_delegate.created_requests());
3590 EXPECT_EQ(0, network_delegate.destroyed_requests());
3591 }
3592 EXPECT_EQ(1, network_delegate.destroyed_requests());
3593}
3594
[email protected]3c5ca8c2011-09-29 01:14:513595// Tests that redirects caused by the network delegate preserve POST data.
3596TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3597 ASSERT_TRUE(test_server_.Start());
3598
3599 const char kData[] = "hello world";
3600
3601 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303602 BlockingNetworkDelegate network_delegate(
3603 BlockingNetworkDelegate::AUTO_CALLBACK);
3604 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513605 GURL redirect_url(test_server_.GetURL("echo"));
3606 network_delegate.set_redirect_url(redirect_url);
3607
[email protected]ef2bf422012-05-11 03:27:093608 TestURLRequestContext context(true);
3609 context.set_network_delegate(&network_delegate);
3610 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513611
3612 {
3613 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193614 scoped_ptr<URLRequest> r(context.CreateRequest(
3615 original_url, DEFAULT_PRIORITY, &d, NULL));
3616 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073617 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513618 HttpRequestHeaders headers;
3619 headers.SetHeader(HttpRequestHeaders::kContentLength,
3620 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193621 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563622
3623 // Quit after hitting the redirect, so can check the headers.
3624 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193625 r->Start();
[email protected]255620da2013-08-19 13:14:293626 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513627
[email protected]6be6fa92014-08-06 23:44:563628 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193629 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3630 EXPECT_EQ(307, r->GetResponseCode());
3631 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563632 std::string location;
[email protected]f7022f32014-08-21 16:32:193633 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3634 &location));
[email protected]6be6fa92014-08-06 23:44:563635 EXPECT_EQ(redirect_url, GURL(location));
3636
3637 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193638 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563639 base::RunLoop().Run();
3640
[email protected]f7022f32014-08-21 16:32:193641 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3642 EXPECT_EQ(0, r->status().error());
3643 EXPECT_EQ(redirect_url, r->url());
3644 EXPECT_EQ(original_url, r->original_url());
3645 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513646 EXPECT_EQ(1, network_delegate.created_requests());
3647 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193648 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513649 EXPECT_EQ(kData, d.data_received());
3650 }
3651 EXPECT_EQ(1, network_delegate.destroyed_requests());
3652}
3653
[email protected]5f714132014-03-26 10:41:163654// Tests that the network delegate can block and redirect a request to a new
3655// URL during OnHeadersReceived.
3656TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3657 ASSERT_TRUE(test_server_.Start());
3658
3659 TestDelegate d;
3660 BlockingNetworkDelegate network_delegate(
3661 BlockingNetworkDelegate::AUTO_CALLBACK);
3662 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3663 GURL redirect_url(test_server_.GetURL("simple.html"));
3664 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3665
3666 TestURLRequestContextWithProxy context(
3667 test_server_.host_port_pair().ToString(), &network_delegate);
3668
3669 {
3670 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]f7022f32014-08-21 16:32:193671 scoped_ptr<URLRequest> r(context.CreateRequest(
3672 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:163673
[email protected]f7022f32014-08-21 16:32:193674 r->Start();
[email protected]5f714132014-03-26 10:41:163675 base::RunLoop().Run();
3676
[email protected]f7022f32014-08-21 16:32:193677 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3678 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273679 EXPECT_EQ(
3680 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3681 EXPECT_TRUE(
3682 network_delegate.last_observed_proxy().Equals(
3683 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193684
3685 EXPECT_EQ(OK, r->status().error());
3686 EXPECT_EQ(redirect_url, r->url());
3687 EXPECT_EQ(original_url, r->original_url());
3688 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163689 EXPECT_EQ(2, network_delegate.created_requests());
3690 EXPECT_EQ(0, network_delegate.destroyed_requests());
3691 }
3692 EXPECT_EQ(1, network_delegate.destroyed_requests());
3693}
3694
[email protected]c2911d72011-10-03 22:16:363695// Tests that the network delegate can synchronously complete OnAuthRequired
3696// by taking no action. This indicates that the NetworkDelegate does not want to
3697// handle the challenge, and is passing the buck along to the
3698// URLRequest::Delegate.
3699TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3700 ASSERT_TRUE(test_server_.Start());
3701
3702 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303703 BlockingNetworkDelegate network_delegate(
3704 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363705
[email protected]ef2bf422012-05-11 03:27:093706 TestURLRequestContext context(true);
3707 context.set_network_delegate(&network_delegate);
3708 context.Init();
[email protected]c2911d72011-10-03 22:16:363709
[email protected]f3cf9802011-10-28 18:44:583710 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363711
3712 {
3713 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193714 scoped_ptr<URLRequest> r(context.CreateRequest(
3715 url, DEFAULT_PRIORITY, &d, NULL));
3716 r->Start();
[email protected]79e1fd62013-06-20 06:50:043717
[email protected]255620da2013-08-19 13:14:293718 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043719
[email protected]f7022f32014-08-21 16:32:193720 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3721 EXPECT_EQ(0, r->status().error());
3722 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043723 EXPECT_TRUE(d.auth_required_called());
3724 EXPECT_EQ(1, network_delegate.created_requests());
3725 EXPECT_EQ(0, network_delegate.destroyed_requests());
3726 }
3727 EXPECT_EQ(1, network_delegate.destroyed_requests());
3728}
3729
3730TEST_F(URLRequestTestHTTP,
3731 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3732 ASSERT_TRUE(test_server_.Start());
3733
3734 TestDelegate d;
3735 BlockingNetworkDelegate network_delegate(
3736 BlockingNetworkDelegate::SYNCHRONOUS);
3737
3738 TestURLRequestContext context(true);
3739 context.set_network_delegate(&network_delegate);
3740 context.Init();
3741
3742 d.set_credentials(AuthCredentials(kUser, kSecret));
3743
3744 {
3745 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193746 scoped_ptr<URLRequest> r(context.CreateRequest(
3747 url, DEFAULT_PRIORITY, &d, NULL));
3748 r->Start();
[email protected]79e1fd62013-06-20 06:50:043749
3750 {
3751 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193752 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043753 EXPECT_FALSE(headers.HasHeader("Authorization"));
3754 }
3755
[email protected]255620da2013-08-19 13:14:293756 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363757
[email protected]f7022f32014-08-21 16:32:193758 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3759 EXPECT_EQ(0, r->status().error());
3760 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363761 EXPECT_TRUE(d.auth_required_called());
3762 EXPECT_EQ(1, network_delegate.created_requests());
3763 EXPECT_EQ(0, network_delegate.destroyed_requests());
3764 }
3765 EXPECT_EQ(1, network_delegate.destroyed_requests());
3766}
3767
3768// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403769// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363770TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3771 ASSERT_TRUE(test_server_.Start());
3772
3773 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303774 BlockingNetworkDelegate network_delegate(
3775 BlockingNetworkDelegate::SYNCHRONOUS);
3776 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363777 network_delegate.set_auth_retval(
3778 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3779
[email protected]f3cf9802011-10-28 18:44:583780 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363781
[email protected]ef2bf422012-05-11 03:27:093782 TestURLRequestContext context(true);
3783 context.set_network_delegate(&network_delegate);
3784 context.Init();
[email protected]c2911d72011-10-03 22:16:363785
3786 {
3787 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193788 scoped_ptr<URLRequest> r(context.CreateRequest(
3789 url, DEFAULT_PRIORITY, &d, NULL));
3790 r->Start();
[email protected]255620da2013-08-19 13:14:293791 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363792
[email protected]f7022f32014-08-21 16:32:193793 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3794 EXPECT_EQ(0, r->status().error());
3795 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363796 EXPECT_FALSE(d.auth_required_called());
3797 EXPECT_EQ(1, network_delegate.created_requests());
3798 EXPECT_EQ(0, network_delegate.destroyed_requests());
3799 }
3800 EXPECT_EQ(1, network_delegate.destroyed_requests());
3801}
3802
[email protected]79e1fd62013-06-20 06:50:043803// Same as above, but also tests that GetFullRequestHeaders returns the proper
3804// headers (for the first or second request) when called at the proper times.
3805TEST_F(URLRequestTestHTTP,
3806 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3807 ASSERT_TRUE(test_server_.Start());
3808
3809 TestDelegate d;
3810 BlockingNetworkDelegate network_delegate(
3811 BlockingNetworkDelegate::SYNCHRONOUS);
3812 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3813 network_delegate.set_auth_retval(
3814 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3815
3816 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3817
3818 TestURLRequestContext context(true);
3819 context.set_network_delegate(&network_delegate);
3820 context.Init();
3821
3822 {
3823 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193824 scoped_ptr<URLRequest> r(context.CreateRequest(
3825 url, DEFAULT_PRIORITY, &d, NULL));
3826 r->Start();
[email protected]255620da2013-08-19 13:14:293827 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043828
[email protected]f7022f32014-08-21 16:32:193829 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3830 EXPECT_EQ(0, r->status().error());
3831 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043832 EXPECT_FALSE(d.auth_required_called());
3833 EXPECT_EQ(1, network_delegate.created_requests());
3834 EXPECT_EQ(0, network_delegate.destroyed_requests());
3835
3836 {
3837 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193838 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043839 EXPECT_TRUE(headers.HasHeader("Authorization"));
3840 }
3841 }
3842 EXPECT_EQ(1, network_delegate.destroyed_requests());
3843}
3844
[email protected]c2911d72011-10-03 22:16:363845// Tests that the network delegate can synchronously complete OnAuthRequired
3846// by cancelling authentication.
3847TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3848 ASSERT_TRUE(test_server_.Start());
3849
3850 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303851 BlockingNetworkDelegate network_delegate(
3852 BlockingNetworkDelegate::SYNCHRONOUS);
3853 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363854 network_delegate.set_auth_retval(
3855 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3856
[email protected]ef2bf422012-05-11 03:27:093857 TestURLRequestContext context(true);
3858 context.set_network_delegate(&network_delegate);
3859 context.Init();
[email protected]c2911d72011-10-03 22:16:363860
3861 {
3862 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193863 scoped_ptr<URLRequest> r(context.CreateRequest(
3864 url, DEFAULT_PRIORITY, &d, NULL));
3865 r->Start();
[email protected]255620da2013-08-19 13:14:293866 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363867
[email protected]f7022f32014-08-21 16:32:193868 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3869 EXPECT_EQ(OK, r->status().error());
3870 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363871 EXPECT_FALSE(d.auth_required_called());
3872 EXPECT_EQ(1, network_delegate.created_requests());
3873 EXPECT_EQ(0, network_delegate.destroyed_requests());
3874 }
3875 EXPECT_EQ(1, network_delegate.destroyed_requests());
3876}
3877
3878// Tests that the network delegate can asynchronously complete OnAuthRequired
3879// by taking no action. This indicates that the NetworkDelegate does not want
3880// to handle the challenge, and is passing the buck along to the
3881// URLRequest::Delegate.
3882TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3883 ASSERT_TRUE(test_server_.Start());
3884
3885 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303886 BlockingNetworkDelegate network_delegate(
3887 BlockingNetworkDelegate::AUTO_CALLBACK);
3888 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363889
[email protected]ef2bf422012-05-11 03:27:093890 TestURLRequestContext context(true);
3891 context.set_network_delegate(&network_delegate);
3892 context.Init();
[email protected]c2911d72011-10-03 22:16:363893
[email protected]f3cf9802011-10-28 18:44:583894 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363895
3896 {
3897 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193898 scoped_ptr<URLRequest> r(context.CreateRequest(
3899 url, DEFAULT_PRIORITY, &d, NULL));
3900 r->Start();
[email protected]255620da2013-08-19 13:14:293901 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363902
[email protected]f7022f32014-08-21 16:32:193903 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3904 EXPECT_EQ(0, r->status().error());
3905 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363906 EXPECT_TRUE(d.auth_required_called());
3907 EXPECT_EQ(1, network_delegate.created_requests());
3908 EXPECT_EQ(0, network_delegate.destroyed_requests());
3909 }
3910 EXPECT_EQ(1, network_delegate.destroyed_requests());
3911}
3912
3913// Tests that the network delegate can asynchronously complete OnAuthRequired
3914// by setting credentials.
3915TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3916 ASSERT_TRUE(test_server_.Start());
3917
3918 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303919 BlockingNetworkDelegate network_delegate(
3920 BlockingNetworkDelegate::AUTO_CALLBACK);
3921 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363922 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363923 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3924
[email protected]f3cf9802011-10-28 18:44:583925 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363926 network_delegate.set_auth_credentials(auth_credentials);
3927
[email protected]ef2bf422012-05-11 03:27:093928 TestURLRequestContext context(true);
3929 context.set_network_delegate(&network_delegate);
3930 context.Init();
[email protected]c2911d72011-10-03 22:16:363931
3932 {
3933 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193934 scoped_ptr<URLRequest> r(context.CreateRequest(
3935 url, DEFAULT_PRIORITY, &d, NULL));
3936 r->Start();
[email protected]255620da2013-08-19 13:14:293937 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363938
[email protected]f7022f32014-08-21 16:32:193939 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3940 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363941
[email protected]f7022f32014-08-21 16:32:193942 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363943 EXPECT_FALSE(d.auth_required_called());
3944 EXPECT_EQ(1, network_delegate.created_requests());
3945 EXPECT_EQ(0, network_delegate.destroyed_requests());
3946 }
3947 EXPECT_EQ(1, network_delegate.destroyed_requests());
3948}
3949
3950// Tests that the network delegate can asynchronously complete OnAuthRequired
3951// by cancelling authentication.
3952TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3953 ASSERT_TRUE(test_server_.Start());
3954
3955 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303956 BlockingNetworkDelegate network_delegate(
3957 BlockingNetworkDelegate::AUTO_CALLBACK);
3958 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363959 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363960 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3961
[email protected]ef2bf422012-05-11 03:27:093962 TestURLRequestContext context(true);
3963 context.set_network_delegate(&network_delegate);
3964 context.Init();
[email protected]c2911d72011-10-03 22:16:363965
3966 {
3967 GURL url(test_server_.GetURL("auth-basic"));
[email protected]f7022f32014-08-21 16:32:193968 scoped_ptr<URLRequest> r(context.CreateRequest(
3969 url, DEFAULT_PRIORITY, &d, NULL));
3970 r->Start();
[email protected]255620da2013-08-19 13:14:293971 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363972
[email protected]f7022f32014-08-21 16:32:193973 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3974 EXPECT_EQ(OK, r->status().error());
3975 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363976 EXPECT_FALSE(d.auth_required_called());
3977 EXPECT_EQ(1, network_delegate.created_requests());
3978 EXPECT_EQ(0, network_delegate.destroyed_requests());
3979 }
3980 EXPECT_EQ(1, network_delegate.destroyed_requests());
3981}
3982
[email protected]9045b8822012-01-13 20:35:353983// Tests that we can handle when a network request was canceled while we were
3984// waiting for the network delegate.
3985// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3986TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3987 ASSERT_TRUE(test_server_.Start());
3988
3989 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303990 BlockingNetworkDelegate network_delegate(
3991 BlockingNetworkDelegate::USER_CALLBACK);
3992 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353993
[email protected]ef2bf422012-05-11 03:27:093994 TestURLRequestContext context(true);
3995 context.set_network_delegate(&network_delegate);
3996 context.Init();
[email protected]9045b8822012-01-13 20:35:353997
3998 {
[email protected]f7022f32014-08-21 16:32:193999 scoped_ptr<URLRequest> r(context.CreateRequest(
4000 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:354001
[email protected]f7022f32014-08-21 16:32:194002 r->Start();
[email protected]255620da2013-08-19 13:14:294003 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304004 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
4005 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354006 EXPECT_EQ(0, network_delegate.completed_requests());
4007 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194008 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354009 // Ensure that network delegate is notified.
4010 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194011 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4012 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354013 EXPECT_EQ(1, network_delegate.created_requests());
4014 EXPECT_EQ(0, network_delegate.destroyed_requests());
4015 }
4016 EXPECT_EQ(1, network_delegate.destroyed_requests());
4017}
4018
4019// Tests that we can handle when a network request was canceled while we were
4020// waiting for the network delegate.
4021// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
4022TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
4023 ASSERT_TRUE(test_server_.Start());
4024
4025 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304026 BlockingNetworkDelegate network_delegate(
4027 BlockingNetworkDelegate::USER_CALLBACK);
4028 network_delegate.set_block_on(
4029 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:354030
[email protected]ef2bf422012-05-11 03:27:094031 TestURLRequestContext context(true);
4032 context.set_network_delegate(&network_delegate);
4033 context.Init();
[email protected]9045b8822012-01-13 20:35:354034
4035 {
[email protected]f7022f32014-08-21 16:32:194036 scoped_ptr<URLRequest> r(context.CreateRequest(
4037 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:354038
[email protected]f7022f32014-08-21 16:32:194039 r->Start();
[email protected]255620da2013-08-19 13:14:294040 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304041 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
4042 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354043 EXPECT_EQ(0, network_delegate.completed_requests());
4044 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194045 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354046 // Ensure that network delegate is notified.
4047 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194048 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4049 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354050 EXPECT_EQ(1, network_delegate.created_requests());
4051 EXPECT_EQ(0, network_delegate.destroyed_requests());
4052 }
4053 EXPECT_EQ(1, network_delegate.destroyed_requests());
4054}
4055
4056// Tests that we can handle when a network request was canceled while we were
4057// waiting for the network delegate.
4058// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
4059TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
4060 ASSERT_TRUE(test_server_.Start());
4061
4062 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304063 BlockingNetworkDelegate network_delegate(
4064 BlockingNetworkDelegate::USER_CALLBACK);
4065 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:354066
[email protected]ef2bf422012-05-11 03:27:094067 TestURLRequestContext context(true);
4068 context.set_network_delegate(&network_delegate);
4069 context.Init();
[email protected]9045b8822012-01-13 20:35:354070
4071 {
[email protected]f7022f32014-08-21 16:32:194072 scoped_ptr<URLRequest> r(context.CreateRequest(
4073 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:354074
[email protected]f7022f32014-08-21 16:32:194075 r->Start();
[email protected]255620da2013-08-19 13:14:294076 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304077 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
4078 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354079 EXPECT_EQ(0, network_delegate.completed_requests());
4080 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194081 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354082 // Ensure that network delegate is notified.
4083 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194084 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4085 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354086 EXPECT_EQ(1, network_delegate.created_requests());
4087 EXPECT_EQ(0, network_delegate.destroyed_requests());
4088 }
4089 EXPECT_EQ(1, network_delegate.destroyed_requests());
4090}
4091
4092// Tests that we can handle when a network request was canceled while we were
4093// waiting for the network delegate.
4094// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:024095TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:354096 ASSERT_TRUE(test_server_.Start());
4097
4098 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:304099 BlockingNetworkDelegate network_delegate(
4100 BlockingNetworkDelegate::USER_CALLBACK);
4101 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:354102
[email protected]ef2bf422012-05-11 03:27:094103 TestURLRequestContext context(true);
4104 context.set_network_delegate(&network_delegate);
4105 context.Init();
[email protected]9045b8822012-01-13 20:35:354106
4107 {
[email protected]f7022f32014-08-21 16:32:194108 scoped_ptr<URLRequest> r(context.CreateRequest(
4109 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
[email protected]9045b8822012-01-13 20:35:354110
[email protected]f7022f32014-08-21 16:32:194111 r->Start();
[email protected]255620da2013-08-19 13:14:294112 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:304113 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
4114 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:354115 EXPECT_EQ(0, network_delegate.completed_requests());
4116 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:194117 r->Cancel();
[email protected]9045b8822012-01-13 20:35:354118 // Ensure that network delegate is notified.
4119 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:194120 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
4121 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:354122 EXPECT_EQ(1, network_delegate.created_requests());
4123 EXPECT_EQ(0, network_delegate.destroyed_requests());
4124 }
4125 EXPECT_EQ(1, network_delegate.destroyed_requests());
4126}
4127
[email protected]95409e12010-08-17 20:07:114128// In this unit test, we're using the HTTPTestServer as a proxy server and
4129// issuing a CONNECT request with the magic host name "www.server-auth.com".
4130// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:354131TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:114132 ASSERT_TRUE(test_server_.Start());
4133
[email protected]ceefd7fd2012-11-29 00:36:244134 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:044135 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:194136 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:504137
[email protected]dc651782009-02-14 01:45:084138 TestDelegate d;
4139 {
[email protected]f7022f32014-08-21 16:32:194140 scoped_ptr<URLRequest> r(context.CreateRequest(
4141 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, NULL));
[email protected]dc651782009-02-14 01:45:084142
[email protected]f7022f32014-08-21 16:32:194143 r->Start();
4144 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:084145
[email protected]255620da2013-08-19 13:14:294146 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:084147
[email protected]f7022f32014-08-21 16:32:194148 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:154149 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:194150 EXPECT_TRUE(r->proxy_server().IsEmpty());
4151 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:084152 }
4153}
4154
[email protected]b89290212009-08-14 22:37:354155TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:114156 ASSERT_TRUE(test_server_.Start());
4157
initial.commit586acc5fe2008-07-26 22:42:524158 TestDelegate d;
4159 {
[email protected]f7022f32014-08-21 16:32:194160 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4161 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
initial.commit586acc5fe2008-07-26 22:42:524162
[email protected]f7022f32014-08-21 16:32:194163 r->Start();
4164 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524165
[email protected]255620da2013-08-19 13:14:294166 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524167
4168 EXPECT_EQ(1, d.response_started_count());
4169 EXPECT_FALSE(d.received_data_before_response());
4170 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:194171 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194172 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:194173 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194174 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:164175
[email protected]9e743cd2010-03-16 07:03:534176 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:524177 }
initial.commit586acc5fe2008-07-26 22:42:524178}
4179
[email protected]263163f2012-06-14 22:40:344180// This test has the server send a large number of cookies to the client.
4181// To ensure that no number of cookies causes a crash, a galloping binary
4182// search is used to estimate that maximum number of cookies that are accepted
4183// by the browser. Beyond the maximum number, the request will fail with
4184// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:304185#if defined(OS_WIN)
4186// http://crbug.com/177916
4187#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
4188#else
4189#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
4190#endif // defined(OS_WIN)
4191TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:344192 ASSERT_TRUE(test_server_.Start());
4193
4194 int lower_bound = 0;
4195 int upper_bound = 1;
4196
4197 // Double the number of cookies until the response header limits are
4198 // exceeded.
4199 while (DoManyCookiesRequest(upper_bound)) {
4200 lower_bound = upper_bound;
4201 upper_bound *= 2;
4202 ASSERT_LT(upper_bound, 1000000);
4203 }
4204
4205 int tolerance = upper_bound * 0.005;
4206 if (tolerance < 2)
4207 tolerance = 2;
4208
4209 // Perform a binary search to find the highest possible number of cookies,
4210 // within the desired tolerance.
4211 while (upper_bound - lower_bound >= tolerance) {
4212 int num_cookies = (lower_bound + upper_bound) / 2;
4213
4214 if (DoManyCookiesRequest(num_cookies))
4215 lower_bound = num_cookies;
4216 else
4217 upper_bound = num_cookies;
4218 }
4219 // Success: the test did not crash.
4220}
4221
[email protected]b89290212009-08-14 22:37:354222TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:114223 ASSERT_TRUE(test_server_.Start());
4224
initial.commit586acc5fe2008-07-26 22:42:524225 TestDelegate d;
4226 {
[email protected]f7022f32014-08-21 16:32:194227 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4228 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
initial.commit586acc5fe2008-07-26 22:42:524229
[email protected]f7022f32014-08-21 16:32:194230 r->Start();
4231 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:524232
[email protected]255620da2013-08-19 13:14:294233 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:524234
4235 EXPECT_EQ(1, d.response_started_count());
4236 EXPECT_FALSE(d.received_data_before_response());
4237 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:194238 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194239 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:194240 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194241 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:524242 }
[email protected]5d7b373e2009-09-02 07:19:034243}
4244
[email protected]79e1fd62013-06-20 06:50:044245TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
4246 ASSERT_TRUE(test_server_.Start());
4247
4248 TestDelegate d;
4249 {
4250 GURL test_url(test_server_.GetURL(std::string()));
[email protected]f7022f32014-08-21 16:32:194251 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4252 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:044253
4254 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:194255 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:044256
[email protected]f7022f32014-08-21 16:32:194257 r->Start();
4258 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:044259
[email protected]255620da2013-08-19 13:14:294260 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044261
4262 EXPECT_EQ(1, d.response_started_count());
4263 EXPECT_FALSE(d.received_data_before_response());
4264 EXPECT_NE(0, d.bytes_received());
4265 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194266 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:044267 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194268 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:044269
4270 EXPECT_TRUE(d.have_full_request_headers());
4271 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4272 }
4273}
4274
[email protected]58e32bb2013-01-21 18:23:254275TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
4276 ASSERT_TRUE(test_server_.Start());
4277
4278 TestDelegate d;
4279 {
[email protected]f7022f32014-08-21 16:32:194280 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
4281 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]58e32bb2013-01-21 18:23:254282
[email protected]f7022f32014-08-21 16:32:194283 r->Start();
4284 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:254285
[email protected]255620da2013-08-19 13:14:294286 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254287
4288 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194289 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254290 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4291
4292 EXPECT_EQ(1, d.response_started_count());
4293 EXPECT_FALSE(d.received_data_before_response());
4294 EXPECT_NE(0, d.bytes_received());
4295 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:194296 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:254297 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:194298 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:254299 }
4300}
4301
[email protected]aad63572011-05-24 20:14:394302TEST_F(URLRequestTestHTTP, GetZippedTest) {
4303 ASSERT_TRUE(test_server_.Start());
4304
4305 // Parameter that specifies the Content-Length field in the response:
4306 // C - Compressed length.
4307 // U - Uncompressed length.
4308 // L - Large length (larger than both C & U).
4309 // M - Medium length (between C & U).
4310 // S - Small length (smaller than both C & U).
4311 const char test_parameters[] = "CULMS";
4312 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
4313 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:444314 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:394315 // S has too little data, but we seem to accept it.
4316 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:374317 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:394318
4319 for (int i = 0; i < num_tests ; i++) {
4320 TestDelegate d;
4321 {
4322 std::string test_file =
4323 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
4324 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:394325
[email protected]ceefd7fd2012-11-29 00:36:244326 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094327 TestURLRequestContext context(true);
4328 context.set_network_delegate(&network_delegate);
4329 context.Init();
[email protected]87a09a92011-07-14 15:50:504330
[email protected]f7022f32014-08-21 16:32:194331 scoped_ptr<URLRequest> r(context.CreateRequest(
4332 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, NULL));
4333 r->Start();
4334 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:394335
[email protected]255620da2013-08-19 13:14:294336 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:394337
4338 EXPECT_EQ(1, d.response_started_count());
4339 EXPECT_FALSE(d.received_data_before_response());
4340 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:194341 << " status = " << r->status().status()
4342 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:394343 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:194344 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:394345 << " Parameter = \"" << test_file << "\"";
4346 } else {
[email protected]f7022f32014-08-21 16:32:194347 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
4348 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:394349 << " Parameter = \"" << test_file << "\"";
4350 }
4351 }
4352 }
4353}
4354
[email protected]c044616e2013-02-20 02:01:264355TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:114356 ASSERT_TRUE(test_server_.Start());
4357
[email protected]ce7d0cbc2013-05-03 18:57:224358 SpawnedTestServer https_test_server(
4359 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:154360 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114361 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:584362
4363 // An https server is sent a request with an https referer,
4364 // and responds with a redirect to an http url. The http
4365 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:454366 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:584367 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194368 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:194369 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
[email protected]f7022f32014-08-21 16:32:194370 DEFAULT_PRIORITY, &d, NULL));
4371 req->SetReferrer("https://www.referrer.com/");
4372 req->Start();
[email protected]255620da2013-08-19 13:14:294373 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:584374
4375 EXPECT_EQ(1, d.response_started_count());
4376 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194377 EXPECT_EQ(http_destination, req->url());
4378 EXPECT_EQ(std::string(), req->referrer());
[email protected]7844480a2009-12-16 21:18:584379}
4380
[email protected]58e32bb2013-01-21 18:23:254381TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4382 ASSERT_TRUE(test_server_.Start());
4383
[email protected]007b3f82013-04-09 08:46:454384 GURL destination_url = test_server_.GetURL(std::string());
4385 GURL original_url =
4386 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254387 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194388 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4389 original_url, DEFAULT_PRIORITY, &d, NULL));
4390 req->Start();
[email protected]255620da2013-08-19 13:14:294391 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254392
4393 EXPECT_EQ(1, d.response_started_count());
4394 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194395 EXPECT_EQ(destination_url, req->url());
4396 EXPECT_EQ(original_url, req->original_url());
4397 ASSERT_EQ(2U, req->url_chain().size());
4398 EXPECT_EQ(original_url, req->url_chain()[0]);
4399 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254400
4401 LoadTimingInfo load_timing_info_before_redirect;
4402 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4403 &load_timing_info_before_redirect));
4404 TestLoadTimingNotReused(load_timing_info_before_redirect,
4405 CONNECT_TIMING_HAS_DNS_TIMES);
4406
4407 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194408 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254409 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4410
4411 // Check that a new socket was used on redirect, since the server does not
4412 // supposed keep-alive sockets, and that the times before the redirect are
4413 // before the ones recorded for the second request.
4414 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4415 load_timing_info.socket_log_id);
4416 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4417 load_timing_info.connect_timing.connect_start);
4418}
4419
[email protected]8f1ac082011-04-19 21:14:134420TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4421 ASSERT_TRUE(test_server_.Start());
4422
[email protected]007b3f82013-04-09 08:46:454423 GURL destination_url = test_server_.GetURL(std::string());
4424 GURL middle_redirect_url =
4425 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134426 GURL original_url = test_server_.GetURL(
4427 "server-redirect?" + middle_redirect_url.spec());
4428 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194429 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
4430 original_url, DEFAULT_PRIORITY, &d, NULL));
4431 req->Start();
[email protected]255620da2013-08-19 13:14:294432 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134433
4434 EXPECT_EQ(1, d.response_started_count());
4435 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194436 EXPECT_EQ(destination_url, req->url());
4437 EXPECT_EQ(original_url, req->original_url());
4438 ASSERT_EQ(3U, req->url_chain().size());
4439 EXPECT_EQ(original_url, req->url_chain()[0]);
4440 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4441 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134442}
4443
[email protected]abe1c4a2013-10-25 19:28:514444// First and second pieces of information logged by delegates to URLRequests.
4445const char kFirstDelegateInfo[] = "Wonderful delegate";
4446const char kSecondDelegateInfo[] = "Exciting delegate";
4447
4448// Logs delegate information to a URLRequest. The first string is logged
4449// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4450// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4451// another asynchronous call is used to clear the delegate information
4452// before calling a callback. The object then deletes itself.
4453class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4454 public:
4455 typedef base::Callback<void()> Callback;
4456
4457 // Each time delegate information is added to the URLRequest, the resulting
4458 // load state is checked. The expected load state after each request is
4459 // passed in as an argument.
4460 static void Run(URLRequest* url_request,
4461 LoadState expected_first_load_state,
4462 LoadState expected_second_load_state,
4463 LoadState expected_third_load_state,
4464 const Callback& callback) {
4465 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4466 url_request,
4467 expected_first_load_state,
4468 expected_second_load_state,
4469 expected_third_load_state,
4470 callback);
4471 logger->Start();
4472 }
4473
4474 // Checks that the log entries, starting with log_position, contain the
4475 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4476 // recorded. Returns the index of entry after the expected number of
4477 // events this logged, or entries.size() if there aren't enough entries.
4478 static size_t CheckDelegateInfo(
4479 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4480 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4481 if (log_position + 3 >= entries.size()) {
4482 ADD_FAILURE() << "Not enough log entries";
4483 return entries.size();
4484 }
4485 std::string delegate_info;
4486 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4487 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4488 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4489 &delegate_info));
4490 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4491
4492 ++log_position;
4493 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4494 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4495
4496 ++log_position;
4497 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4498 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4499 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4500 &delegate_info));
4501 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4502
4503 ++log_position;
4504 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4505 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4506
4507 return log_position + 1;
4508 }
4509
[email protected]1826a402014-01-08 15:40:484510 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4511 // Returns the position of the end message.
4512 static size_t ExpectBeforeNetworkEvents(
4513 const CapturingNetLog::CapturedEntryList& entries,
4514 size_t log_position) {
4515 log_position =
4516 ExpectLogContainsSomewhereAfter(entries,
4517 log_position,
4518 NetLog::TYPE_URL_REQUEST_DELEGATE,
4519 NetLog::PHASE_BEGIN);
4520 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4521 entries[log_position + 1].type);
4522 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4523 return log_position + 1;
4524 }
4525
[email protected]abe1c4a2013-10-25 19:28:514526 private:
4527 friend class base::RefCounted<AsyncDelegateLogger>;
4528
4529 AsyncDelegateLogger(URLRequest* url_request,
4530 LoadState expected_first_load_state,
4531 LoadState expected_second_load_state,
4532 LoadState expected_third_load_state,
4533 const Callback& callback)
4534 : url_request_(url_request),
4535 expected_first_load_state_(expected_first_load_state),
4536 expected_second_load_state_(expected_second_load_state),
4537 expected_third_load_state_(expected_third_load_state),
4538 callback_(callback) {
4539 }
4540
4541 ~AsyncDelegateLogger() {}
4542
4543 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534544 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514545 LoadStateWithParam load_state = url_request_->GetLoadState();
4546 EXPECT_EQ(expected_first_load_state_, load_state.state);
4547 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4548 base::MessageLoop::current()->PostTask(
4549 FROM_HERE,
4550 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4551 }
4552
4553 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534554 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514555 LoadStateWithParam load_state = url_request_->GetLoadState();
4556 EXPECT_EQ(expected_second_load_state_, load_state.state);
4557 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4558 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4559 } else {
4560 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4561 }
4562 base::MessageLoop::current()->PostTask(
4563 FROM_HERE,
4564 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4565 }
4566
4567 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534568 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514569 LoadStateWithParam load_state = url_request_->GetLoadState();
4570 EXPECT_EQ(expected_third_load_state_, load_state.state);
4571 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084572 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514573 callback_.Run();
4574 }
4575
4576 URLRequest* url_request_;
4577 const int expected_first_load_state_;
4578 const int expected_second_load_state_;
4579 const int expected_third_load_state_;
4580 const Callback callback_;
4581
4582 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4583};
4584
4585// NetworkDelegate that logs delegate information before a request is started,
4586// before headers are sent, when headers are read, and when auth information
4587// is requested. Uses AsyncDelegateLogger.
4588class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4589 public:
4590 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204591 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514592
4593 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204594 int OnBeforeURLRequest(URLRequest* request,
4595 const CompletionCallback& callback,
4596 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514597 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4598 return RunCallbackAsynchronously(request, callback);
4599 }
4600
dchengb03027d2014-10-21 12:00:204601 int OnBeforeSendHeaders(URLRequest* request,
4602 const CompletionCallback& callback,
4603 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514604 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4605 return RunCallbackAsynchronously(request, callback);
4606 }
4607
dchengb03027d2014-10-21 12:00:204608 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514609 URLRequest* request,
4610 const CompletionCallback& callback,
4611 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164612 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134613 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164614 TestNetworkDelegate::OnHeadersReceived(request,
4615 callback,
[email protected]abe1c4a2013-10-25 19:28:514616 original_response_headers,
[email protected]5f714132014-03-26 10:41:164617 override_response_headers,
4618 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514619 return RunCallbackAsynchronously(request, callback);
4620 }
4621
dchengb03027d2014-10-21 12:00:204622 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514623 URLRequest* request,
4624 const AuthChallengeInfo& auth_info,
4625 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134626 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514627 AsyncDelegateLogger::Run(
4628 request,
4629 LOAD_STATE_WAITING_FOR_DELEGATE,
4630 LOAD_STATE_WAITING_FOR_DELEGATE,
4631 LOAD_STATE_WAITING_FOR_DELEGATE,
4632 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4633 callback, credentials));
4634 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4635 }
4636
4637 private:
4638 static int RunCallbackAsynchronously(
4639 URLRequest* request,
4640 const CompletionCallback& callback) {
4641 AsyncDelegateLogger::Run(
4642 request,
4643 LOAD_STATE_WAITING_FOR_DELEGATE,
4644 LOAD_STATE_WAITING_FOR_DELEGATE,
4645 LOAD_STATE_WAITING_FOR_DELEGATE,
4646 base::Bind(callback, OK));
4647 return ERR_IO_PENDING;
4648 }
4649
4650 static void SetAuthAndResume(const AuthCallback& callback,
4651 AuthCredentials* credentials) {
4652 *credentials = AuthCredentials(kUser, kSecret);
4653 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4654 }
4655
4656 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4657};
4658
4659// URLRequest::Delegate that logs delegate information when the headers
4660// are received, when each read completes, and during redirects. Uses
4661// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4662//
4663// Inherits from TestDelegate to reuse the TestDelegate code to handle
4664// advancing to the next step in most cases, as well as cancellation.
4665class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4666 public:
4667 enum CancelStage {
4668 NO_CANCEL = 0,
4669 CANCEL_ON_RECEIVED_REDIRECT,
4670 CANCEL_ON_RESPONSE_STARTED,
4671 CANCEL_ON_READ_COMPLETED
4672 };
4673
4674 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4675 : cancel_stage_(cancel_stage) {
4676 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4677 set_cancel_in_received_redirect(true);
4678 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4679 set_cancel_in_response_started(true);
4680 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4681 set_cancel_in_received_data(true);
4682 }
dchengb03027d2014-10-21 12:00:204683 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514684
4685 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204686 void OnReceivedRedirect(URLRequest* request,
4687 const RedirectInfo& redirect_info,
4688 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514689 *defer_redirect = true;
4690 AsyncDelegateLogger::Run(
4691 request,
4692 LOAD_STATE_WAITING_FOR_DELEGATE,
4693 LOAD_STATE_WAITING_FOR_DELEGATE,
4694 LOAD_STATE_WAITING_FOR_DELEGATE,
4695 base::Bind(
4696 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594697 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514698 }
4699
dchengb03027d2014-10-21 12:00:204700 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514701 AsyncDelegateLogger::Run(
4702 request,
4703 LOAD_STATE_WAITING_FOR_DELEGATE,
4704 LOAD_STATE_WAITING_FOR_DELEGATE,
4705 LOAD_STATE_WAITING_FOR_DELEGATE,
4706 base::Bind(
4707 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4708 base::Unretained(this), request));
4709 }
4710
dchengb03027d2014-10-21 12:00:204711 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514712 AsyncDelegateLogger::Run(
4713 request,
4714 LOAD_STATE_IDLE,
4715 LOAD_STATE_IDLE,
4716 LOAD_STATE_IDLE,
4717 base::Bind(
4718 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4719 base::Unretained(this), request, bytes_read));
4720 }
4721
4722 private:
4723 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594724 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514725 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594726 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514727 // FollowDeferredRedirect should not be called after cancellation.
4728 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4729 return;
4730 if (!defer_redirect)
4731 request->FollowDeferredRedirect();
4732 }
4733
4734 void OnResponseStartedLoggingComplete(URLRequest* request) {
4735 // The parent class continues the request.
4736 TestDelegate::OnResponseStarted(request);
4737 }
4738
4739 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4740 // The parent class continues the request.
4741 TestDelegate::OnReadCompleted(request, bytes_read);
4742 }
4743
4744 const CancelStage cancel_stage_;
4745
4746 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4747};
4748
4749// Tests handling of delegate info before a request starts.
4750TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4751 ASSERT_TRUE(test_server_.Start());
4752
4753 TestDelegate request_delegate;
4754 TestURLRequestContext context(true);
4755 context.set_network_delegate(NULL);
4756 context.set_net_log(&net_log_);
4757 context.Init();
4758
4759 {
[email protected]f7022f32014-08-21 16:32:194760 scoped_ptr<URLRequest> r(context.CreateRequest(
4761 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &request_delegate,
4762 NULL));
4763 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514764 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084765 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514766
4767 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194768 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514769 LOAD_STATE_WAITING_FOR_DELEGATE,
4770 LOAD_STATE_WAITING_FOR_DELEGATE,
4771 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194772 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514773
4774 base::RunLoop().Run();
4775
[email protected]f7022f32014-08-21 16:32:194776 EXPECT_EQ(200, r->GetResponseCode());
4777 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514778 }
4779
4780 CapturingNetLog::CapturedEntryList entries;
4781 net_log_.GetEntries(&entries);
4782 size_t log_position = ExpectLogContainsSomewhereAfter(
4783 entries,
4784 0,
4785 NetLog::TYPE_DELEGATE_INFO,
4786 NetLog::PHASE_BEGIN);
4787
4788 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4789
4790 // Nothing else should add any delegate info to the request.
4791 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4792 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4793}
4794
4795// Tests handling of delegate info from a network delegate.
4796TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4797 ASSERT_TRUE(test_server_.Start());
4798
4799 TestDelegate request_delegate;
4800 AsyncLoggingNetworkDelegate network_delegate;
4801 TestURLRequestContext context(true);
4802 context.set_network_delegate(&network_delegate);
4803 context.set_net_log(&net_log_);
4804 context.Init();
4805
4806 {
[email protected]f7022f32014-08-21 16:32:194807 scoped_ptr<URLRequest> r(context.CreateRequest(
4808 test_server_.GetURL("simple.html"), DEFAULT_PRIORITY, &request_delegate,
4809 NULL));
4810 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514811 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084812 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514813
[email protected]f7022f32014-08-21 16:32:194814 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514815 base::RunLoop().Run();
4816
[email protected]f7022f32014-08-21 16:32:194817 EXPECT_EQ(200, r->GetResponseCode());
4818 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514819 EXPECT_EQ(1, network_delegate.created_requests());
4820 EXPECT_EQ(0, network_delegate.destroyed_requests());
4821 }
4822 EXPECT_EQ(1, network_delegate.destroyed_requests());
4823
4824 size_t log_position = 0;
4825 CapturingNetLog::CapturedEntryList entries;
4826 net_log_.GetEntries(&entries);
4827 for (size_t i = 0; i < 3; ++i) {
4828 log_position = ExpectLogContainsSomewhereAfter(
4829 entries,
4830 log_position + 1,
4831 NetLog::TYPE_URL_REQUEST_DELEGATE,
4832 NetLog::PHASE_BEGIN);
4833
4834 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4835 log_position + 1);
4836
4837 ASSERT_LT(log_position, entries.size());
4838 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4839 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484840
4841 if (i == 1) {
4842 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4843 entries, log_position + 1);
4844 }
[email protected]abe1c4a2013-10-25 19:28:514845 }
4846
4847 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4848 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4849}
4850
4851// Tests handling of delegate info from a network delegate in the case of an
4852// HTTP redirect.
4853TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4854 ASSERT_TRUE(test_server_.Start());
4855
4856 TestDelegate request_delegate;
4857 AsyncLoggingNetworkDelegate network_delegate;
4858 TestURLRequestContext context(true);
4859 context.set_network_delegate(&network_delegate);
4860 context.set_net_log(&net_log_);
4861 context.Init();
4862
4863 {
[email protected]f7022f32014-08-21 16:32:194864 scoped_ptr<URLRequest> r(context.CreateRequest(
4865 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
4866 &request_delegate, NULL));
4867 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514868 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084869 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514870
[email protected]f7022f32014-08-21 16:32:194871 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514872 base::RunLoop().Run();
4873
[email protected]f7022f32014-08-21 16:32:194874 EXPECT_EQ(200, r->GetResponseCode());
4875 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514876 EXPECT_EQ(2, network_delegate.created_requests());
4877 EXPECT_EQ(0, network_delegate.destroyed_requests());
4878 }
4879 EXPECT_EQ(1, network_delegate.destroyed_requests());
4880
4881 size_t log_position = 0;
4882 CapturingNetLog::CapturedEntryList entries;
4883 net_log_.GetEntries(&entries);
4884 // The NetworkDelegate logged information in OnBeforeURLRequest,
4885 // OnBeforeSendHeaders, and OnHeadersReceived.
4886 for (size_t i = 0; i < 3; ++i) {
4887 log_position = ExpectLogContainsSomewhereAfter(
4888 entries,
4889 log_position + 1,
4890 NetLog::TYPE_URL_REQUEST_DELEGATE,
4891 NetLog::PHASE_BEGIN);
4892
4893 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4894 log_position + 1);
4895
4896 ASSERT_LT(log_position, entries.size());
4897 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4898 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484899
4900 if (i == 1) {
4901 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4902 entries, log_position + 1);
4903 }
[email protected]abe1c4a2013-10-25 19:28:514904 }
4905
4906 // The URLRequest::Delegate then gets informed about the redirect.
4907 log_position = ExpectLogContainsSomewhereAfter(
4908 entries,
4909 log_position + 1,
4910 NetLog::TYPE_URL_REQUEST_DELEGATE,
4911 NetLog::PHASE_BEGIN);
4912
4913 // The NetworkDelegate logged information in the same three events as before.
4914 for (size_t i = 0; i < 3; ++i) {
4915 log_position = ExpectLogContainsSomewhereAfter(
4916 entries,
4917 log_position + 1,
4918 NetLog::TYPE_URL_REQUEST_DELEGATE,
4919 NetLog::PHASE_BEGIN);
4920
4921 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4922 log_position + 1);
4923
4924 ASSERT_LT(log_position, entries.size());
4925 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4926 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4927 }
4928
4929 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4930 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4931}
4932
4933// Tests handling of delegate info from a network delegate in the case of HTTP
4934// AUTH.
4935TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4936 ASSERT_TRUE(test_server_.Start());
4937
4938 TestDelegate request_delegate;
4939 AsyncLoggingNetworkDelegate network_delegate;
4940 TestURLRequestContext context(true);
4941 context.set_network_delegate(&network_delegate);
4942 context.set_net_log(&net_log_);
4943 context.Init();
4944
4945 {
[email protected]f7022f32014-08-21 16:32:194946 scoped_ptr<URLRequest> r(context.CreateRequest(
4947 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &request_delegate,
4948 NULL));
4949 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514950 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084951 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514952
[email protected]f7022f32014-08-21 16:32:194953 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514954 base::RunLoop().Run();
4955
[email protected]f7022f32014-08-21 16:32:194956 EXPECT_EQ(200, r->GetResponseCode());
4957 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514958 EXPECT_EQ(1, network_delegate.created_requests());
4959 EXPECT_EQ(0, network_delegate.destroyed_requests());
4960 }
4961 EXPECT_EQ(1, network_delegate.destroyed_requests());
4962
4963 size_t log_position = 0;
4964 CapturingNetLog::CapturedEntryList entries;
4965 net_log_.GetEntries(&entries);
4966 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4967 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4968 // OnBeforeURLRequest and OnBeforeSendHeaders.
4969 for (size_t i = 0; i < 6; ++i) {
4970 log_position = ExpectLogContainsSomewhereAfter(
4971 entries,
4972 log_position + 1,
4973 NetLog::TYPE_URL_REQUEST_DELEGATE,
4974 NetLog::PHASE_BEGIN);
4975
4976 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4977 log_position + 1);
4978
4979 ASSERT_LT(log_position, entries.size());
4980 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4981 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484982
4983 if (i == 1) {
4984 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4985 entries, log_position + 1);
4986 }
[email protected]abe1c4a2013-10-25 19:28:514987 }
4988
4989 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4990 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4991}
4992
4993// Tests handling of delegate info from a URLRequest::Delegate.
4994TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4995 ASSERT_TRUE(test_server_.Start());
4996
4997 AsyncLoggingUrlRequestDelegate request_delegate(
4998 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4999 TestURLRequestContext context(true);
5000 context.set_network_delegate(NULL);
5001 context.set_net_log(&net_log_);
5002 context.Init();
5003
5004 {
5005 // A chunked response with delays between chunks is used to make sure that
5006 // attempts by the URLRequest delegate to log information while reading the
5007 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:485008 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:515009 // that it occurs.
[email protected]f7022f32014-08-21 16:32:195010 scoped_ptr<URLRequest> r(context.CreateRequest(
5011 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
5012 &request_delegate, NULL));
5013 LoadStateWithParam load_state = r->GetLoadState();
5014 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515015 base::RunLoop().Run();
5016
[email protected]f7022f32014-08-21 16:32:195017 EXPECT_EQ(200, r->GetResponseCode());
5018 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515019 }
5020
5021 CapturingNetLog::CapturedEntryList entries;
5022 net_log_.GetEntries(&entries);
5023
[email protected]1826a402014-01-08 15:40:485024 size_t log_position = 0;
5025
5026 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5027 entries, log_position);
5028
[email protected]abe1c4a2013-10-25 19:28:515029 // The delegate info should only have been logged on header complete. Other
5030 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:485031 log_position =
5032 ExpectLogContainsSomewhereAfter(entries,
5033 log_position + 1,
5034 NetLog::TYPE_URL_REQUEST_DELEGATE,
5035 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:515036
5037 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5038 log_position + 1);
5039
5040 ASSERT_LT(log_position, entries.size());
5041 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5042 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5043
5044 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5045 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5046 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5047 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5048}
5049
5050// Tests handling of delegate info from a URLRequest::Delegate in the case of
5051// an HTTP redirect.
5052TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
5053 ASSERT_TRUE(test_server_.Start());
5054
5055 AsyncLoggingUrlRequestDelegate request_delegate(
5056 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
5057 TestURLRequestContext context(true);
5058 context.set_network_delegate(NULL);
5059 context.set_net_log(&net_log_);
5060 context.Init();
5061
5062 {
[email protected]f7022f32014-08-21 16:32:195063 scoped_ptr<URLRequest> r(context.CreateRequest(
5064 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5065 &request_delegate, NULL));
5066 LoadStateWithParam load_state = r->GetLoadState();
5067 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515068 base::RunLoop().Run();
5069
[email protected]f7022f32014-08-21 16:32:195070 EXPECT_EQ(200, r->GetResponseCode());
5071 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515072 }
5073
5074 CapturingNetLog::CapturedEntryList entries;
5075 net_log_.GetEntries(&entries);
5076
5077 // Delegate info should only have been logged in OnReceivedRedirect and
5078 // OnResponseStarted.
5079 size_t log_position = 0;
5080 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485081 if (i == 0) {
5082 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5083 entries, log_position) + 1;
5084 }
5085
[email protected]abe1c4a2013-10-25 19:28:515086 log_position = ExpectLogContainsSomewhereAfter(
5087 entries,
5088 log_position,
5089 NetLog::TYPE_URL_REQUEST_DELEGATE,
5090 NetLog::PHASE_BEGIN);
5091
5092 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5093 log_position + 1);
5094
5095 ASSERT_LT(log_position, entries.size());
5096 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5097 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5098 }
5099
5100 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5101 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5102 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5103 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5104}
5105
5106// Tests handling of delegate info from a URLRequest::Delegate in the case of
5107// an HTTP redirect, with cancellation at various points.
5108TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
5109 ASSERT_TRUE(test_server_.Start());
5110
5111 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
5112 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
5113 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
5114 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
5115 };
5116
5117 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
5118 ++test_case) {
5119 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
5120 TestURLRequestContext context(true);
5121 CapturingNetLog net_log;
5122 context.set_network_delegate(NULL);
5123 context.set_net_log(&net_log);
5124 context.Init();
5125
5126 {
[email protected]f7022f32014-08-21 16:32:195127 scoped_ptr<URLRequest> r(context.CreateRequest(
5128 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
5129 &request_delegate, NULL));
5130 LoadStateWithParam load_state = r->GetLoadState();
5131 r->Start();
[email protected]abe1c4a2013-10-25 19:28:515132 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195133 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:515134 }
5135
5136 CapturingNetLog::CapturedEntryList entries;
5137 net_log.GetEntries(&entries);
5138
5139 // Delegate info is always logged in both OnReceivedRedirect and
5140 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
5141 // OnResponseStarted delegate call is after cancellation, but logging is
5142 // still currently supported in that call.
5143 size_t log_position = 0;
5144 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:485145 if (i == 0) {
5146 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
5147 entries, log_position) + 1;
5148 }
5149
[email protected]abe1c4a2013-10-25 19:28:515150 log_position = ExpectLogContainsSomewhereAfter(
5151 entries,
5152 log_position,
5153 NetLog::TYPE_URL_REQUEST_DELEGATE,
5154 NetLog::PHASE_BEGIN);
5155
5156 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
5157 log_position + 1);
5158
5159 ASSERT_LT(log_position, entries.size());
5160 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
5161 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
5162 }
5163
5164 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5165 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
5166 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
5167 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
5168 }
5169}
5170
[email protected]847c0fa92012-11-06 16:37:425171namespace {
5172
5173const char kExtraHeader[] = "Allow-Snafu";
5174const char kExtraValue[] = "fubar";
5175
5176class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205177 void OnReceivedRedirect(URLRequest* request,
5178 const RedirectInfo& redirect_info,
5179 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595180 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:425181 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
5182 }
5183};
5184
5185} // namespace
5186
5187TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
5188 ASSERT_TRUE(test_server_.Start());
5189
5190 GURL destination_url = test_server_.GetURL(
5191 "echoheader?" + std::string(kExtraHeader));
5192 GURL original_url = test_server_.GetURL(
5193 "server-redirect?" + destination_url.spec());
5194 RedirectWithAdditionalHeadersDelegate d;
[email protected]f7022f32014-08-21 16:32:195195 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5196 original_url, DEFAULT_PRIORITY, &d, NULL));
5197 req->Start();
[email protected]255620da2013-08-19 13:14:295198 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:425199
5200 std::string value;
[email protected]f7022f32014-08-21 16:32:195201 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:425202 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
5203 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:195204 EXPECT_FALSE(req->is_pending());
5205 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:425206 EXPECT_EQ(kExtraValue, d.data_received());
5207}
5208
[email protected]251a1b92012-11-13 11:01:095209namespace {
5210
5211const char kExtraHeaderToRemove[] = "To-Be-Removed";
5212
5213class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:205214 void OnReceivedRedirect(URLRequest* request,
5215 const RedirectInfo& redirect_info,
5216 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:595217 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:095218 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
5219 }
5220};
5221
5222} // namespace
5223
5224TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
5225 ASSERT_TRUE(test_server_.Start());
5226
5227 GURL destination_url = test_server_.GetURL(
5228 "echoheader?" + std::string(kExtraHeaderToRemove));
5229 GURL original_url = test_server_.GetURL(
5230 "server-redirect?" + destination_url.spec());
5231 RedirectWithHeaderRemovalDelegate d;
[email protected]f7022f32014-08-21 16:32:195232 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5233 original_url, DEFAULT_PRIORITY, &d, NULL));
5234 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
5235 req->Start();
[email protected]255620da2013-08-19 13:14:295236 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:095237
5238 std::string value;
[email protected]f7022f32014-08-21 16:32:195239 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:095240 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:195241 EXPECT_FALSE(req->is_pending());
5242 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:095243 EXPECT_EQ("None", d.data_received());
5244}
5245
[email protected]316c1e5e2012-09-12 15:17:445246TEST_F(URLRequestTestHTTP, CancelTest) {
5247 TestDelegate d;
5248 {
[email protected]f7022f32014-08-21 16:32:195249 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5250 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:445251
[email protected]f7022f32014-08-21 16:32:195252 r->Start();
5253 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445254
[email protected]f7022f32014-08-21 16:32:195255 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445256
[email protected]255620da2013-08-19 13:14:295257 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445258
5259 // We expect to receive OnResponseStarted even though the request has been
5260 // cancelled.
5261 EXPECT_EQ(1, d.response_started_count());
5262 EXPECT_EQ(0, d.bytes_received());
5263 EXPECT_FALSE(d.received_data_before_response());
5264 }
5265}
5266
5267TEST_F(URLRequestTestHTTP, CancelTest2) {
5268 ASSERT_TRUE(test_server_.Start());
5269
5270 TestDelegate d;
5271 {
[email protected]f7022f32014-08-21 16:32:195272 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5273 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:445274
5275 d.set_cancel_in_response_started(true);
5276
[email protected]f7022f32014-08-21 16:32:195277 r->Start();
5278 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445279
[email protected]255620da2013-08-19 13:14:295280 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445281
5282 EXPECT_EQ(1, d.response_started_count());
5283 EXPECT_EQ(0, d.bytes_received());
5284 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195285 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445286 }
5287}
5288
5289TEST_F(URLRequestTestHTTP, CancelTest3) {
5290 ASSERT_TRUE(test_server_.Start());
5291
5292 TestDelegate d;
5293 {
[email protected]f7022f32014-08-21 16:32:195294 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5295 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:445296
5297 d.set_cancel_in_received_data(true);
5298
[email protected]f7022f32014-08-21 16:32:195299 r->Start();
5300 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445301
[email protected]255620da2013-08-19 13:14:295302 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445303
5304 EXPECT_EQ(1, d.response_started_count());
5305 // There is no guarantee about how much data was received
5306 // before the cancel was issued. It could have been 0 bytes,
5307 // or it could have been all the bytes.
5308 // EXPECT_EQ(0, d.bytes_received());
5309 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195310 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445311 }
5312}
5313
5314TEST_F(URLRequestTestHTTP, CancelTest4) {
5315 ASSERT_TRUE(test_server_.Start());
5316
5317 TestDelegate d;
5318 {
[email protected]f7022f32014-08-21 16:32:195319 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5320 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:445321
[email protected]f7022f32014-08-21 16:32:195322 r->Start();
5323 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445324
5325 // The request will be implicitly canceled when it is destroyed. The
5326 // test delegate must not post a quit message when this happens because
5327 // this test doesn't actually have a message loop. The quit message would
5328 // get put on this thread's message queue and the next test would exit
5329 // early, causing problems.
5330 d.set_quit_on_complete(false);
5331 }
5332 // expect things to just cleanup properly.
5333
5334 // we won't actually get a received reponse here because we've never run the
5335 // message loop
5336 EXPECT_FALSE(d.received_data_before_response());
5337 EXPECT_EQ(0, d.bytes_received());
5338}
5339
5340TEST_F(URLRequestTestHTTP, CancelTest5) {
5341 ASSERT_TRUE(test_server_.Start());
5342
5343 // populate cache
5344 {
5345 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195346 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5347 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5348 r->Start();
[email protected]255620da2013-08-19 13:14:295349 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195350 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445351 }
5352
5353 // cancel read from cache (see bug 990242)
5354 {
5355 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195356 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5357 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d, NULL));
5358 r->Start();
5359 r->Cancel();
[email protected]255620da2013-08-19 13:14:295360 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445361
[email protected]f7022f32014-08-21 16:32:195362 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:445363 EXPECT_EQ(1, d.response_started_count());
5364 EXPECT_EQ(0, d.bytes_received());
5365 EXPECT_FALSE(d.received_data_before_response());
5366 }
5367}
5368
5369TEST_F(URLRequestTestHTTP, PostTest) {
5370 ASSERT_TRUE(test_server_.Start());
5371 HTTPUploadDataOperationTest("POST");
5372}
5373
5374TEST_F(URLRequestTestHTTP, PutTest) {
5375 ASSERT_TRUE(test_server_.Start());
5376 HTTPUploadDataOperationTest("PUT");
5377}
5378
5379TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5380 ASSERT_TRUE(test_server_.Start());
5381
5382 TestDelegate d;
5383 {
[email protected]f7022f32014-08-21 16:32:195384 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5385 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5386 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445387
[email protected]f7022f32014-08-21 16:32:195388 r->Start();
5389 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445390
[email protected]255620da2013-08-19 13:14:295391 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445392
[email protected]329b68b2012-11-14 17:54:275393 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195394 << "request failed: " << r->status().status()
5395 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445396
5397 EXPECT_FALSE(d.received_data_before_response());
5398 EXPECT_TRUE(d.data_received().empty());
5399 }
5400}
5401
5402TEST_F(URLRequestTestHTTP, PostFileTest) {
5403 ASSERT_TRUE(test_server_.Start());
5404
5405 TestDelegate d;
5406 {
[email protected]f7022f32014-08-21 16:32:195407 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5408 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5409 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445410
[email protected]6cdfd7f2013-02-08 20:40:155411 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445412 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025413 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445414
[email protected]f288ef02012-12-15 20:28:285415 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445416
[email protected]6cdfd7f2013-02-08 20:40:155417 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445418 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5419 path = path.Append(FILE_PATH_LITERAL("net"));
5420 path = path.Append(FILE_PATH_LITERAL("data"));
5421 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5422 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365423 element_readers.push_back(
5424 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5425 path,
5426 0,
5427 kuint64max,
5428 base::Time()));
mmenkecbc2b712014-10-09 20:29:075429 r->set_upload(make_scoped_ptr<UploadDataStream>(
5430 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445431
[email protected]f7022f32014-08-21 16:32:195432 r->Start();
5433 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445434
[email protected]255620da2013-08-19 13:14:295435 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445436
[email protected]329b68b2012-11-14 17:54:275437 int64 size = 0;
[email protected]56285702013-12-04 18:22:495438 ASSERT_EQ(true, base::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:175439 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445440
[email protected]7600d0b2013-12-08 21:43:305441 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445442
[email protected]329b68b2012-11-14 17:54:275443 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195444 << "request failed: " << r->status().status()
5445 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445446
5447 EXPECT_FALSE(d.received_data_before_response());
5448
[email protected]329b68b2012-11-14 17:54:275449 EXPECT_EQ(size, d.bytes_received());
5450 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445451 }
5452}
5453
[email protected]999dd8c2013-11-12 06:45:545454TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5455 ASSERT_TRUE(test_server_.Start());
5456
5457 TestDelegate d;
5458 {
[email protected]f7022f32014-08-21 16:32:195459 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5460 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5461 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545462
5463 ScopedVector<UploadElementReader> element_readers;
5464
5465 element_readers.push_back(new UploadFileElementReader(
5466 base::MessageLoopProxy::current().get(),
5467 base::FilePath(FILE_PATH_LITERAL(
5468 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5469 0,
5470 kuint64max,
5471 base::Time()));
mmenkecbc2b712014-10-09 20:29:075472 r->set_upload(make_scoped_ptr<UploadDataStream>(
5473 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545474
[email protected]f7022f32014-08-21 16:32:195475 r->Start();
5476 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545477
5478 base::RunLoop().Run();
5479
[email protected]999dd8c2013-11-12 06:45:545480 EXPECT_TRUE(d.request_failed());
5481 EXPECT_FALSE(d.received_data_before_response());
5482 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195483 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5484 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545485 }
5486}
5487
[email protected]316c1e5e2012-09-12 15:17:445488TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5489 ASSERT_TRUE(test_server_.Start());
5490
5491 TestDelegate d;
5492 {
[email protected]f7022f32014-08-21 16:32:195493 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5494 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5495 r->EnableChunkedUpload();
5496 r->set_method("POST");
5497 AddChunksToUpload(r.get());
5498 r->Start();
5499 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445500
[email protected]255620da2013-08-19 13:14:295501 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445502
[email protected]f7022f32014-08-21 16:32:195503 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445504 }
5505}
5506
[email protected]329b68b2012-11-14 17:54:275507TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5508 ASSERT_TRUE(test_server_.Start());
5509
5510 TestDelegate d;
5511 {
[email protected]f7022f32014-08-21 16:32:195512 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5513 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5514 r->EnableChunkedUpload();
5515 r->set_method("POST");
5516 r->Start();
5517 EXPECT_TRUE(r->is_pending());
5518 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295519 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275520
[email protected]f7022f32014-08-21 16:32:195521 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275522 }
5523}
5524
[email protected]316c1e5e2012-09-12 15:17:445525TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5526 ASSERT_TRUE(test_server_.Start());
5527
5528 TestDelegate d;
5529 {
[email protected]f7022f32014-08-21 16:32:195530 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5531 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
5532 r->EnableChunkedUpload();
5533 r->set_method("POST");
5534 r->Start();
5535 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445536
[email protected]255620da2013-08-19 13:14:295537 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195538 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295539 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445540
[email protected]f7022f32014-08-21 16:32:195541 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445542 }
5543}
5544
5545TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5546 ASSERT_TRUE(test_server_.Start());
5547
5548 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195549 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5550 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d,
5551 NULL));
5552 req->Start();
[email protected]255620da2013-08-19 13:14:295553 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445554
[email protected]f7022f32014-08-21 16:32:195555 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445556
5557 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195558 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445559
5560 std::string header;
5561 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5562 EXPECT_EQ("private", header);
5563
5564 header.clear();
5565 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5566 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5567
5568 // The response has two "X-Multiple-Entries" headers.
5569 // This verfies our output has them concatenated together.
5570 header.clear();
5571 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5572 EXPECT_EQ("a, b", header);
5573}
5574
[email protected]242d8562012-10-30 21:20:465575TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:225576 SpawnedTestServer::SSLOptions ssl_options;
5577 SpawnedTestServer https_test_server(
5578 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465579 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155580 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465581 ASSERT_TRUE(https_test_server.Start());
5582
5583 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195584 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5585 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY, &d,
5586 NULL));
5587 request->Start();
[email protected]255620da2013-08-19 13:14:295588 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465589
5590 TransportSecurityState* security_state =
5591 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465592 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265593 EXPECT_TRUE(security_state->GetDynamicDomainState(
5594 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465595 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265596 domain_state.sts.upgrade_mode);
5597 EXPECT_TRUE(domain_state.sts.include_subdomains);
5598 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275599#if defined(OS_ANDROID)
5600 // Android's CertVerifyProc does not (yet) handle pins.
5601#else
5602 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5603#endif
5604}
5605
5606// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5607// reject HPKP headers, and a test setting only HPKP headers will fail (no
5608// DomainState present because header rejected).
5609#if defined(OS_ANDROID)
5610#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5611#else
5612#define MAYBE_ProcessPKP ProcessPKP
5613#endif
5614
5615// Tests that enabling HPKP on a domain does not affect the HSTS
5616// validity/expiration.
5617TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5618 SpawnedTestServer::SSLOptions ssl_options;
5619 SpawnedTestServer https_test_server(
5620 SpawnedTestServer::TYPE_HTTPS,
5621 ssl_options,
5622 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5623 ASSERT_TRUE(https_test_server.Start());
5624
5625 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195626 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
5627 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY, &d,
5628 NULL));
5629 request->Start();
[email protected]255620da2013-08-19 13:14:295630 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275631
5632 TransportSecurityState* security_state =
5633 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275634 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265635 EXPECT_TRUE(security_state->GetDynamicDomainState(
5636 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275637 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265638 domain_state.sts.upgrade_mode);
5639 EXPECT_FALSE(domain_state.sts.include_subdomains);
5640 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275641 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265642 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465643}
5644
5645TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:225646 SpawnedTestServer::SSLOptions ssl_options;
5647 SpawnedTestServer https_test_server(
5648 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465649 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155650 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465651 ASSERT_TRUE(https_test_server.Start());
5652
5653 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195654 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465655 https_test_server.GetURL("files/hsts-multiple-headers.html"),
[email protected]f7022f32014-08-21 16:32:195656 DEFAULT_PRIORITY, &d, NULL));
5657 request->Start();
[email protected]255620da2013-08-19 13:14:295658 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465659
5660 // We should have set parameters from the first header, not the second.
5661 TransportSecurityState* security_state =
5662 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465663 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265664 EXPECT_TRUE(security_state->GetDynamicDomainState(
5665 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465666 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265667 domain_state.sts.upgrade_mode);
5668 EXPECT_FALSE(domain_state.sts.include_subdomains);
5669 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465670}
5671
[email protected]9f972ec2013-04-10 20:24:365672TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:225673 SpawnedTestServer::SSLOptions ssl_options;
5674 SpawnedTestServer https_test_server(
5675 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365676 ssl_options,
5677 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5678 ASSERT_TRUE(https_test_server.Start());
5679
5680 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195681 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365682 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
[email protected]f7022f32014-08-21 16:32:195683 DEFAULT_PRIORITY, &d, NULL));
5684 request->Start();
[email protected]255620da2013-08-19 13:14:295685 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365686
5687 // We should have set parameters from the first header, not the second.
5688 TransportSecurityState* security_state =
5689 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365690 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265691 EXPECT_TRUE(security_state->GetDynamicDomainState(
5692 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365693 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265694 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365695#if defined(OS_ANDROID)
5696 // Android's CertVerifyProc does not (yet) handle pins.
5697#else
5698 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5699#endif
[email protected]9e6968d2014-05-07 21:46:265700 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365701
[email protected]a165f092013-06-12 16:10:055702 // Even though there is an HSTS header asserting includeSubdomains, it is
5703 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265704 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055705 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265706 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365707}
5708
[email protected]37fd55fb2013-06-29 13:13:275709// Tests that when multiple HPKP headers are present, asserting different
5710// policies, that only the first such policy is processed.
5711TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5712 SpawnedTestServer::SSLOptions ssl_options;
5713 SpawnedTestServer https_test_server(
5714 SpawnedTestServer::TYPE_HTTPS,
5715 ssl_options,
5716 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5717 ASSERT_TRUE(https_test_server.Start());
5718
5719 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195720 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275721 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
[email protected]f7022f32014-08-21 16:32:195722 DEFAULT_PRIORITY, &d, NULL));
5723 request->Start();
[email protected]255620da2013-08-19 13:14:295724 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275725
5726 TransportSecurityState* security_state =
5727 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275728 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265729 EXPECT_TRUE(security_state->GetDynamicDomainState(
5730 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275731 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265732 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275733#if defined(OS_ANDROID)
5734 // Android's CertVerifyProc does not (yet) handle pins.
5735#else
5736 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5737#endif
[email protected]9e6968d2014-05-07 21:46:265738 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275739
[email protected]9e6968d2014-05-07 21:46:265740 EXPECT_TRUE(domain_state.sts.include_subdomains);
5741 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275742}
5743
[email protected]316c1e5e2012-09-12 15:17:445744TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5745 ASSERT_TRUE(test_server_.Start());
5746
5747 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195748 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5749 test_server_.GetURL("files/content-type-normalization.html"),
5750 DEFAULT_PRIORITY, &d, NULL));
5751 req->Start();
[email protected]255620da2013-08-19 13:14:295752 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445753
5754 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195755 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445756 EXPECT_EQ("text/html", mime_type);
5757
5758 std::string charset;
[email protected]f7022f32014-08-21 16:32:195759 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445760 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195761 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445762}
5763
[email protected]02494ec2014-05-07 15:05:295764TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345765 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345766 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345767 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025768 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345769
5770 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505771 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345772}
5773
[email protected]02494ec2014-05-07 15:05:295774#if !defined(DISABLE_FILE_SUPPORT)
5775TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5776 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5777 GURL file_url("file:///foo.txt");
5778 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5779 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5780
5781 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505782 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295783}
5784
[email protected]588614c22013-08-16 00:09:025785TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445786 ASSERT_TRUE(test_server_.Start());
5787
5788 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195789 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5790 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY, &d,
5791 NULL));
5792 req->Start();
[email protected]255620da2013-08-19 13:14:295793 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445794
[email protected]f7022f32014-08-21 16:32:195795 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5796 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445797}
[email protected]02494ec2014-05-07 15:05:295798#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445799
[email protected]588614c22013-08-16 00:09:025800TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5801 ASSERT_TRUE(test_server_.Start());
5802
5803 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195804 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5805 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY, &d,
5806 NULL));
5807 req->Start();
[email protected]588614c22013-08-16 00:09:025808 base::MessageLoop::current()->Run();
5809
[email protected]f7022f32014-08-21 16:32:195810 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5811 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025812}
5813
[email protected]316c1e5e2012-09-12 15:17:445814TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5815 ASSERT_TRUE(test_server_.Start());
5816
5817 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195818 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5819 test_server_.GetURL("files/redirect-to-invalid-url.html"),
5820 DEFAULT_PRIORITY, &d, NULL));
5821 req->Start();
[email protected]255620da2013-08-19 13:14:295822 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445823
[email protected]f7022f32014-08-21 16:32:195824 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5825 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445826}
5827
[email protected]e50efea2014-03-24 18:41:005828// Make sure redirects are cached, despite not reading their bodies.
5829TEST_F(URLRequestTestHTTP, CacheRedirect) {
5830 ASSERT_TRUE(test_server_.Start());
5831 GURL redirect_url =
5832 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5833
5834 {
5835 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195836 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5837 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5838 req->Start();
[email protected]e50efea2014-03-24 18:41:005839 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195840 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005841 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195842 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005843 }
5844
5845 {
5846 TestDelegate d;
5847 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:195848 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5849 redirect_url, DEFAULT_PRIORITY, &d, NULL));
5850 req->Start();
[email protected]e50efea2014-03-24 18:41:005851 base::RunLoop().Run();
5852
5853 EXPECT_EQ(1, d.received_redirect_count());
5854 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195855 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005856
[email protected]f7022f32014-08-21 16:32:195857 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005858 base::RunLoop().Run();
5859 EXPECT_EQ(1, d.received_redirect_count());
5860 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195861 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5862 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005863 }
5864}
5865
5866// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5867// when the headers are read, since the body won't have been read.
5868TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5869 ASSERT_TRUE(test_server_.Start());
5870 // URL that is normally cached.
5871 GURL initial_url = test_server_.GetURL("cachetime");
5872
5873 {
5874 // Set up the TestNetworkDelegate tp force a redirect.
5875 GURL redirect_to_url = test_server_.GetURL("echo");
5876 default_network_delegate_.set_redirect_on_headers_received_url(
5877 redirect_to_url);
5878
5879 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195880 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5881 initial_url, DEFAULT_PRIORITY, &d, NULL));
5882 req->Start();
[email protected]e50efea2014-03-24 18:41:005883 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195884 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005885 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195886 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005887 }
5888
5889 {
5890 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195891 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5892 initial_url, DEFAULT_PRIORITY, &d, NULL));
5893 req->Start();
[email protected]e50efea2014-03-24 18:41:005894 base::RunLoop().Run();
5895
[email protected]f7022f32014-08-21 16:32:195896 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5897 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005898 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195899 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005900 }
5901}
5902
[email protected]5f714132014-03-26 10:41:165903// Tests that redirection to an unsafe URL is allowed when it has been marked as
5904// safe.
5905TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5906 ASSERT_TRUE(test_server_.Start());
5907
5908 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5909 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5910 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5911
5912 TestDelegate d;
5913 {
[email protected]f7022f32014-08-21 16:32:195914 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5915 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165916
[email protected]f7022f32014-08-21 16:32:195917 r->Start();
[email protected]5f714132014-03-26 10:41:165918 base::RunLoop().Run();
5919
[email protected]f7022f32014-08-21 16:32:195920 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165921
[email protected]f7022f32014-08-21 16:32:195922 EXPECT_EQ(2U, r->url_chain().size());
5923 EXPECT_EQ(OK, r->status().error());
5924 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165925 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5926 }
5927}
5928
5929// Tests that a redirect to a different unsafe URL is blocked, even after adding
5930// some other URL to the whitelist.
5931TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5932 ASSERT_TRUE(test_server_.Start());
5933
5934 GURL unsafe_url("data:text/html,something");
5935 GURL different_unsafe_url("data:text/html,something-else");
5936 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5937 default_network_delegate_.set_allowed_unsafe_redirect_url(
5938 different_unsafe_url);
5939
5940 TestDelegate d;
5941 {
[email protected]f7022f32014-08-21 16:32:195942 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5943 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165944
[email protected]f7022f32014-08-21 16:32:195945 r->Start();
[email protected]5f714132014-03-26 10:41:165946 base::RunLoop().Run();
5947
[email protected]f7022f32014-08-21 16:32:195948 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5949 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165950 }
5951}
5952
[email protected]5f714132014-03-26 10:41:165953// Redirects from an URL with fragment to an unsafe URL with fragment should
5954// be allowed, and the reference fragment of the target URL should be preserved.
5955TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5956 ASSERT_TRUE(test_server_.Start());
5957
5958 GURL original_url(test_server_.GetURL("original#fragment1"));
5959 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5960 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5961
5962 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5963 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5964
5965 TestDelegate d;
5966 {
[email protected]f7022f32014-08-21 16:32:195967 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5968 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165969
[email protected]f7022f32014-08-21 16:32:195970 r->Start();
[email protected]5f714132014-03-26 10:41:165971 base::RunLoop().Run();
5972
[email protected]f7022f32014-08-21 16:32:195973 EXPECT_EQ(2U, r->url_chain().size());
5974 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5975 EXPECT_EQ(OK, r->status().error());
5976 EXPECT_EQ(original_url, r->original_url());
5977 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165978 }
5979}
5980
5981// When a delegate has specified a safe redirect URL, but it does not match the
5982// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145983TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165984 ASSERT_TRUE(test_server_.Start());
5985
5986 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5987 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5988 GURL redirect_url(test_server_.GetURL("target"));
5989 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5990
5991 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5992 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5993
5994 TestDelegate d;
5995 {
[email protected]f7022f32014-08-21 16:32:195996 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
5997 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]5f714132014-03-26 10:41:165998
[email protected]f7022f32014-08-21 16:32:195999 r->Start();
[email protected]5f714132014-03-26 10:41:166000 base::RunLoop().Run();
6001
[email protected]f7022f32014-08-21 16:32:196002 EXPECT_EQ(2U, r->url_chain().size());
6003 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6004 EXPECT_EQ(OK, r->status().error());
6005 EXPECT_EQ(original_url, r->original_url());
6006 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:166007 }
6008}
6009
[email protected]f878230e2014-04-03 15:36:146010// When a delegate has specified a safe redirect URL, assume that the redirect
6011// URL should not be changed. In particular, the reference fragment should not
6012// be modified.
6013TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
6014 ASSERT_TRUE(test_server_.Start());
6015
6016 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6017 GURL redirect_url("data:text/html,expect-no-reference-fragment");
6018
6019 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
6020 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
6021
6022 TestDelegate d;
6023 {
[email protected]f7022f32014-08-21 16:32:196024 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6025 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:146026
[email protected]f7022f32014-08-21 16:32:196027 r->Start();
[email protected]f878230e2014-04-03 15:36:146028 base::RunLoop().Run();
6029
[email protected]f7022f32014-08-21 16:32:196030 EXPECT_EQ(2U, r->url_chain().size());
6031 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6032 EXPECT_EQ(OK, r->status().error());
6033 EXPECT_EQ(original_url, r->original_url());
6034 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146035 }
6036}
6037
6038// When a URLRequestRedirectJob is created, the redirection must be followed and
6039// the reference fragment of the target URL must not be modified.
6040TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
6041 ASSERT_TRUE(test_server_.Start());
6042
6043 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
6044 GURL redirect_url(test_server_.GetURL("echo"));
6045
6046 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196047 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6048 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:146049
6050 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196051 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:146052 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6053 AddTestInterceptor()->set_main_intercept_job(job);
6054
[email protected]f7022f32014-08-21 16:32:196055 r->Start();
[email protected]f878230e2014-04-03 15:36:146056 base::RunLoop().Run();
6057
[email protected]f7022f32014-08-21 16:32:196058 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6059 EXPECT_EQ(OK, r->status().error());
6060 EXPECT_EQ(original_url, r->original_url());
6061 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:146062}
6063
[email protected]316c1e5e2012-09-12 15:17:446064TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
6065 ASSERT_TRUE(test_server_.Start());
6066
6067 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196068 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6069 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6070 req->SetReferrer("http://user:[email protected]/");
6071 req->Start();
[email protected]255620da2013-08-19 13:14:296072 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446073
6074 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
6075}
6076
[email protected]99ecf6e2013-04-10 22:46:136077TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
6078 ASSERT_TRUE(test_server_.Start());
6079
6080 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196081 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6082 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6083 req->SetReferrer("http://foo.com/test#fragment");
6084 req->Start();
[email protected]255620da2013-08-19 13:14:296085 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136086
6087 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
6088}
6089
6090TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
6091 ASSERT_TRUE(test_server_.Start());
6092
6093 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196094 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6095 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
6096 req->SetReferrer("http://foo.com/test#fragment");
6097 req->SetReferrer("");
6098 req->Start();
[email protected]255620da2013-08-19 13:14:296099 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:136100
6101 EXPECT_EQ(std::string("None"), d.data_received());
6102}
6103
[email protected]1826a402014-01-08 15:40:486104// Defer network start and then resume, checking that the request was a success
6105// and bytes were received.
6106TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
6107 ASSERT_TRUE(test_server_.Start());
6108
6109 TestDelegate d;
6110 {
6111 d.set_quit_on_network_start(true);
6112 GURL test_url(test_server_.GetURL("echo"));
[email protected]f7022f32014-08-21 16:32:196113 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6114 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]1826a402014-01-08 15:40:486115
[email protected]f7022f32014-08-21 16:32:196116 req->Start();
[email protected]1826a402014-01-08 15:40:486117 base::RunLoop().Run();
6118
6119 EXPECT_EQ(1, d.received_before_network_start_count());
6120 EXPECT_EQ(0, d.response_started_count());
6121
[email protected]f7022f32014-08-21 16:32:196122 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486123 base::RunLoop().Run();
6124
6125 EXPECT_EQ(1, d.response_started_count());
6126 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196127 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486128 }
6129}
6130
6131// Check that OnBeforeNetworkStart is only called once even if there is a
6132// redirect.
6133TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
6134 ASSERT_TRUE(test_server_.Start());
6135
6136 TestDelegate d;
6137 {
6138 d.set_quit_on_redirect(true);
6139 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:196140 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6141 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d,
6142 NULL));
[email protected]1826a402014-01-08 15:40:486143
[email protected]f7022f32014-08-21 16:32:196144 req->Start();
[email protected]1826a402014-01-08 15:40:486145 base::RunLoop().Run();
6146
6147 EXPECT_EQ(1, d.received_before_network_start_count());
6148 EXPECT_EQ(0, d.response_started_count());
6149 EXPECT_EQ(0, d.received_redirect_count());
6150
[email protected]f7022f32014-08-21 16:32:196151 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:486152 base::RunLoop().Run();
6153
6154 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196155 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:486156 base::RunLoop().Run();
6157
6158 // Check that the redirect's new network transaction does not get propagated
6159 // to a second OnBeforeNetworkStart() notification.
6160 EXPECT_EQ(1, d.received_before_network_start_count());
6161
6162 EXPECT_EQ(1, d.response_started_count());
6163 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196164 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:486165 }
6166}
6167
6168// Cancel the request after learning that the request would use the network.
6169TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
6170 ASSERT_TRUE(test_server_.Start());
6171
6172 TestDelegate d;
6173 {
6174 d.set_quit_on_network_start(true);
6175 GURL test_url(test_server_.GetURL("echo"));
[email protected]f7022f32014-08-21 16:32:196176 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6177 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]1826a402014-01-08 15:40:486178
[email protected]f7022f32014-08-21 16:32:196179 req->Start();
[email protected]1826a402014-01-08 15:40:486180 base::RunLoop().Run();
6181
6182 EXPECT_EQ(1, d.received_before_network_start_count());
6183 EXPECT_EQ(0, d.response_started_count());
6184
[email protected]f7022f32014-08-21 16:32:196185 req->Cancel();
[email protected]1826a402014-01-08 15:40:486186 base::RunLoop().Run();
6187
6188 EXPECT_EQ(1, d.response_started_count());
6189 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:196190 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:486191 }
6192}
6193
[email protected]316c1e5e2012-09-12 15:17:446194TEST_F(URLRequestTestHTTP, CancelRedirect) {
6195 ASSERT_TRUE(test_server_.Start());
6196
6197 TestDelegate d;
6198 {
6199 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:196200 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6201 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6202 NULL));
6203 req->Start();
[email protected]255620da2013-08-19 13:14:296204 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446205
6206 EXPECT_EQ(1, d.response_started_count());
6207 EXPECT_EQ(0, d.bytes_received());
6208 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196209 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446210 }
6211}
6212
6213TEST_F(URLRequestTestHTTP, DeferredRedirect) {
6214 ASSERT_TRUE(test_server_.Start());
6215
6216 TestDelegate d;
6217 {
6218 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:046219 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]f7022f32014-08-21 16:32:196220 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6221 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:046222
[email protected]f7022f32014-08-21 16:32:196223 req->Start();
[email protected]255620da2013-08-19 13:14:296224 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446225
6226 EXPECT_EQ(1, d.received_redirect_count());
6227
[email protected]f7022f32014-08-21 16:32:196228 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296229 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446230
6231 EXPECT_EQ(1, d.response_started_count());
6232 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196233 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446234
[email protected]6cdfd7f2013-02-08 20:40:156235 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:446236 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6237 path = path.Append(FILE_PATH_LITERAL("net"));
6238 path = path.Append(FILE_PATH_LITERAL("data"));
6239 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6240 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6241
6242 std::string contents;
[email protected]82f84b92013-08-30 18:23:506243 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:446244 EXPECT_EQ(contents, d.data_received());
6245 }
6246}
6247
[email protected]79e1fd62013-06-20 06:50:046248TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
6249 ASSERT_TRUE(test_server_.Start());
6250
6251 TestDelegate d;
6252 {
6253 d.set_quit_on_redirect(true);
6254 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
[email protected]f7022f32014-08-21 16:32:196255 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6256 test_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]79e1fd62013-06-20 06:50:046257
6258 EXPECT_FALSE(d.have_full_request_headers());
6259
[email protected]f7022f32014-08-21 16:32:196260 req->Start();
[email protected]255620da2013-08-19 13:14:296261 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046262
6263 EXPECT_EQ(1, d.received_redirect_count());
6264 EXPECT_TRUE(d.have_full_request_headers());
6265 CheckFullRequestHeaders(d.full_request_headers(), test_url);
6266 d.ClearFullRequestHeaders();
6267
[email protected]f7022f32014-08-21 16:32:196268 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:296269 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:046270
6271 GURL target_url(test_server_.GetURL("files/with-headers.html"));
6272 EXPECT_EQ(1, d.response_started_count());
6273 EXPECT_TRUE(d.have_full_request_headers());
6274 CheckFullRequestHeaders(d.full_request_headers(), target_url);
6275 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196276 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:046277
6278 base::FilePath path;
6279 PathService::Get(base::DIR_SOURCE_ROOT, &path);
6280 path = path.Append(FILE_PATH_LITERAL("net"));
6281 path = path.Append(FILE_PATH_LITERAL("data"));
6282 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
6283 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
6284
6285 std::string contents;
[email protected]82f84b92013-08-30 18:23:506286 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:046287 EXPECT_EQ(contents, d.data_received());
6288 }
6289}
6290
[email protected]316c1e5e2012-09-12 15:17:446291TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
6292 ASSERT_TRUE(test_server_.Start());
6293
6294 TestDelegate d;
6295 {
6296 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:196297 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6298 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d,
6299 NULL));
6300 req->Start();
[email protected]255620da2013-08-19 13:14:296301 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446302
6303 EXPECT_EQ(1, d.received_redirect_count());
6304
[email protected]f7022f32014-08-21 16:32:196305 req->Cancel();
[email protected]255620da2013-08-19 13:14:296306 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446307
6308 EXPECT_EQ(1, d.response_started_count());
6309 EXPECT_EQ(0, d.bytes_received());
6310 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:196311 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:446312 }
6313}
6314
6315TEST_F(URLRequestTestHTTP, VaryHeader) {
6316 ASSERT_TRUE(test_server_.Start());
6317
[email protected]3b23a222013-05-15 21:33:256318 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:446319 {
6320 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196321 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6322 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6323 NULL));
[email protected]316c1e5e2012-09-12 15:17:446324 HttpRequestHeaders headers;
6325 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196326 req->SetExtraRequestHeaders(headers);
6327 req->Start();
[email protected]255620da2013-08-19 13:14:296328 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:256329
6330 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196331 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256332 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446333 }
6334
[email protected]3b23a222013-05-15 21:33:256335 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:446336 {
6337 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196338 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6339 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6340 NULL));
[email protected]316c1e5e2012-09-12 15:17:446341 HttpRequestHeaders headers;
6342 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:196343 req->SetExtraRequestHeaders(headers);
6344 req->Start();
[email protected]255620da2013-08-19 13:14:296345 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446346
[email protected]f7022f32014-08-21 16:32:196347 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256348
6349 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196350 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256351 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:446352 }
6353
[email protected]3b23a222013-05-15 21:33:256354 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:446355 {
6356 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196357 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6358 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d,
6359 NULL));
[email protected]316c1e5e2012-09-12 15:17:446360 HttpRequestHeaders headers;
6361 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:196362 req->SetExtraRequestHeaders(headers);
6363 req->Start();
[email protected]255620da2013-08-19 13:14:296364 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446365
[email protected]f7022f32014-08-21 16:32:196366 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:256367
6368 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196369 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256370 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:446371 }
6372}
6373
6374TEST_F(URLRequestTestHTTP, BasicAuth) {
6375 ASSERT_TRUE(test_server_.Start());
6376
6377 // populate the cache
6378 {
6379 TestDelegate d;
6380 d.set_credentials(AuthCredentials(kUser, kSecret));
6381
[email protected]f7022f32014-08-21 16:32:196382 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6383 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6384 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446385
[email protected]255620da2013-08-19 13:14:296386 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446387
6388 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6389 }
6390
6391 // repeat request with end-to-end validation. since auth-basic results in a
6392 // cachable page, we expect this test to result in a 304. in which case, the
6393 // response should be fetched from the cache.
6394 {
6395 TestDelegate d;
6396 d.set_credentials(AuthCredentials(kUser, kSecret));
6397
[email protected]f7022f32014-08-21 16:32:196398 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6399 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6400 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6401 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446402
[email protected]255620da2013-08-19 13:14:296403 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446404
6405 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6406
6407 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196408 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446409 }
6410}
6411
6412// Check that Set-Cookie headers in 401 responses are respected.
6413// http://crbug.com/6450
6414TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6415 ASSERT_TRUE(test_server_.Start());
6416
6417 GURL url_requiring_auth =
6418 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6419
6420 // Request a page that will give a 401 containing a Set-Cookie header.
6421 // Verify that when the transaction is restarted, it includes the new cookie.
6422 {
[email protected]ceefd7fd2012-11-29 00:36:246423 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446424 TestURLRequestContext context(true);
6425 context.set_network_delegate(&network_delegate);
6426 context.Init();
6427
6428 TestDelegate d;
6429 d.set_credentials(AuthCredentials(kUser, kSecret));
6430
[email protected]f7022f32014-08-21 16:32:196431 scoped_ptr<URLRequest> r(context.CreateRequest(
6432 url_requiring_auth, DEFAULT_PRIORITY, &d, NULL));
6433 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446434
[email protected]255620da2013-08-19 13:14:296435 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446436
6437 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6438
6439 // Make sure we sent the cookie in the restarted transaction.
6440 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6441 != std::string::npos);
6442 }
6443
6444 // Same test as above, except this time the restart is initiated earlier
6445 // (without user intervention since identity is embedded in the URL).
6446 {
[email protected]ceefd7fd2012-11-29 00:36:246447 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446448 TestURLRequestContext context(true);
6449 context.set_network_delegate(&network_delegate);
6450 context.Init();
6451
6452 TestDelegate d;
6453
6454 GURL::Replacements replacements;
6455 std::string username("user2");
6456 std::string password("secret");
6457 replacements.SetUsernameStr(username);
6458 replacements.SetPasswordStr(password);
6459 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6460
[email protected]f7022f32014-08-21 16:32:196461 scoped_ptr<URLRequest> r(context.CreateRequest(
6462 url_with_identity, DEFAULT_PRIORITY, &d, NULL));
6463 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446464
[email protected]255620da2013-08-19 13:14:296465 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446466
6467 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6468
6469 // Make sure we sent the cookie in the restarted transaction.
6470 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6471 != std::string::npos);
6472 }
6473}
6474
[email protected]58e32bb2013-01-21 18:23:256475// Tests that load timing works as expected with auth and the cache.
6476TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6477 ASSERT_TRUE(test_server_.Start());
6478
6479 // populate the cache
6480 {
6481 TestDelegate d;
6482 d.set_credentials(AuthCredentials(kUser, kSecret));
6483
[email protected]f7022f32014-08-21 16:32:196484 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6485 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6486 r->Start();
[email protected]58e32bb2013-01-21 18:23:256487
[email protected]255620da2013-08-19 13:14:296488 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256489
6490 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6491
6492 LoadTimingInfo load_timing_info_before_auth;
6493 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6494 &load_timing_info_before_auth));
6495 TestLoadTimingNotReused(load_timing_info_before_auth,
6496 CONNECT_TIMING_HAS_DNS_TIMES);
6497
6498 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196499 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256500 // The test server does not support keep alive sockets, so the second
6501 // request with auth should use a new socket.
6502 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6503 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6504 load_timing_info.socket_log_id);
6505 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6506 load_timing_info.connect_timing.connect_start);
6507 }
6508
[email protected]3b23a222013-05-15 21:33:256509 // Repeat request with end-to-end validation. Since auth-basic results in a
6510 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256511 // response should be fetched from the cache.
6512 {
6513 TestDelegate d;
6514 d.set_credentials(AuthCredentials(kUser, kSecret));
6515
[email protected]f7022f32014-08-21 16:32:196516 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6517 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, NULL));
6518 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6519 r->Start();
[email protected]58e32bb2013-01-21 18:23:256520
[email protected]255620da2013-08-19 13:14:296521 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256522
6523 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6524
6525 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196526 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256527
[email protected]3b23a222013-05-15 21:33:256528 // Since there was a request that went over the wire, the load timing
6529 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256530 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196531 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256532 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256533 }
6534}
6535
[email protected]316c1e5e2012-09-12 15:17:446536// In this test, we do a POST which the server will 302 redirect.
6537// The subsequent transaction should use GET, and should not send the
6538// Content-Type header.
6539// http://code.google.com/p/chromium/issues/detail?id=843
6540TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6541 ASSERT_TRUE(test_server_.Start());
6542
6543 const char kData[] = "hello world";
6544
6545 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196546 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6547 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d,
6548 NULL));
6549 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076550 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446551
6552 // Set headers (some of which are specific to the POST).
6553 HttpRequestHeaders headers;
6554 headers.AddHeadersFromString(
6555 "Content-Type: multipart/form-data; "
6556 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6557 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6558 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6559 "Accept-Language: en-US,en\r\n"
6560 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6561 "Content-Length: 11\r\n"
6562 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196563 req->SetExtraRequestHeaders(headers);
6564 req->Start();
[email protected]255620da2013-08-19 13:14:296565 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446566
6567 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196568 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446569 EXPECT_EQ("text/html", mime_type);
6570
6571 const std::string& data = d.data_received();
6572
6573 // Check that the post-specific headers were stripped:
6574 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6575 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6576 EXPECT_FALSE(ContainsString(data, "Origin:"));
6577
6578 // These extra request headers should not have been stripped.
6579 EXPECT_TRUE(ContainsString(data, "Accept:"));
6580 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6581 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6582}
6583
6584// The following tests check that we handle mutating the request method for
6585// HTTP redirects as expected.
6586// See http://crbug.com/56373 and http://crbug.com/102130.
6587
6588TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6589 ASSERT_TRUE(test_server_.Start());
6590
6591 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6592
6593 HTTPRedirectMethodTest(url, "POST", "GET", true);
6594 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6595 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6596}
6597
6598TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6599 ASSERT_TRUE(test_server_.Start());
6600
6601 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6602
6603 HTTPRedirectMethodTest(url, "POST", "GET", true);
6604 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6605 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6606}
6607
6608TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6609 ASSERT_TRUE(test_server_.Start());
6610
6611 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6612
6613 HTTPRedirectMethodTest(url, "POST", "GET", true);
6614 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6615 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6616}
6617
6618TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6619 ASSERT_TRUE(test_server_.Start());
6620
6621 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6622
6623 HTTPRedirectMethodTest(url, "POST", "POST", true);
6624 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6625 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6626}
6627
[email protected]0a17aab32014-04-24 03:32:376628TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6629 ASSERT_TRUE(test_server_.Start());
6630
6631 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6632
6633 HTTPRedirectMethodTest(url, "POST", "POST", true);
6634 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6635 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6636}
6637
6638// Make sure that 308 responses without bodies are not treated as redirects.
6639// Certain legacy apis that pre-date the response code expect this behavior
6640// (Like Google Drive).
6641TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6642 ASSERT_TRUE(test_server_.Start());
6643
6644 TestDelegate d;
6645 const GURL url = test_server_.GetURL("files/308-without-location-header");
6646
[email protected]f7022f32014-08-21 16:32:196647 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
6648 url, DEFAULT_PRIORITY, &d, NULL));
[email protected]0a17aab32014-04-24 03:32:376649
[email protected]f7022f32014-08-21 16:32:196650 request->Start();
[email protected]0a17aab32014-04-24 03:32:376651 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196652 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6653 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376654 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196655 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376656 EXPECT_EQ("This is not a redirect.", d.data_received());
6657}
6658
[email protected]f878230e2014-04-03 15:36:146659TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6660 ASSERT_TRUE(test_server_.Start());
6661
6662 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6663 GURL expected_url(test_server_.GetURL("echo#fragment"));
6664
6665 TestDelegate d;
6666 {
[email protected]f7022f32014-08-21 16:32:196667 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6668 original_url, DEFAULT_PRIORITY, &d, NULL));
[email protected]f878230e2014-04-03 15:36:146669
[email protected]f7022f32014-08-21 16:32:196670 r->Start();
[email protected]f878230e2014-04-03 15:36:146671 base::RunLoop().Run();
6672
[email protected]f7022f32014-08-21 16:32:196673 EXPECT_EQ(2U, r->url_chain().size());
6674 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6675 EXPECT_EQ(OK, r->status().error());
6676 EXPECT_EQ(original_url, r->original_url());
6677 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146678 }
6679}
6680
[email protected]cba24642014-08-15 20:49:596681TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6682 ASSERT_TRUE(test_server_.Start());
6683
6684 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6685 GURL first_party_url("http://example.com");
6686
6687 TestDelegate d;
6688 {
[email protected]f7022f32014-08-21 16:32:196689 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6690 url, DEFAULT_PRIORITY, &d, NULL));
6691 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596692
[email protected]f7022f32014-08-21 16:32:196693 r->Start();
[email protected]cba24642014-08-15 20:49:596694 base::RunLoop().Run();
6695
[email protected]f7022f32014-08-21 16:32:196696 EXPECT_EQ(2U, r->url_chain().size());
6697 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6698 EXPECT_EQ(OK, r->status().error());
6699 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596700 }
6701}
6702
6703TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6704 ASSERT_TRUE(test_server_.Start());
6705
6706 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6707 GURL original_first_party_url("http://example.com");
6708 GURL expected_first_party_url(test_server_.GetURL("echo"));
6709
6710 TestDelegate d;
6711 {
[email protected]f7022f32014-08-21 16:32:196712 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
6713 url, DEFAULT_PRIORITY, &d, NULL));
6714 r->set_first_party_for_cookies(original_first_party_url);
6715 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596716 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6717
[email protected]f7022f32014-08-21 16:32:196718 r->Start();
[email protected]cba24642014-08-15 20:49:596719 base::RunLoop().Run();
6720
[email protected]f7022f32014-08-21 16:32:196721 EXPECT_EQ(2U, r->url_chain().size());
6722 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6723 EXPECT_EQ(OK, r->status().error());
6724 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596725 }
6726}
6727
[email protected]316c1e5e2012-09-12 15:17:446728TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6729 ASSERT_TRUE(test_server_.Start());
6730
6731 const char kData[] = "hello world";
6732
6733 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196734 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6735 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6736 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076737 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446738 HttpRequestHeaders headers;
6739 headers.SetHeader(HttpRequestHeaders::kContentLength,
6740 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196741 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446742
6743 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196744 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096745 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446746 AddTestInterceptor()->set_main_intercept_job(job);
6747
[email protected]f7022f32014-08-21 16:32:196748 req->Start();
[email protected]255620da2013-08-19 13:14:296749 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196750 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446751}
6752
6753TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6754 ASSERT_TRUE(test_server_.Start());
6755
6756 const char kData[] = "hello world";
6757
6758 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196759 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6760 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6761 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076762 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446763 HttpRequestHeaders headers;
6764 headers.SetHeader(HttpRequestHeaders::kContentLength,
6765 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196766 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446767
6768 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196769 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096770 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6771 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446772 AddTestInterceptor()->set_main_intercept_job(job);
6773
[email protected]f7022f32014-08-21 16:32:196774 req->Start();
[email protected]255620da2013-08-19 13:14:296775 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196776 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446777 EXPECT_EQ(kData, d.data_received());
6778}
6779
6780// Check that default A-L header is sent.
6781TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6782 ASSERT_TRUE(test_server_.Start());
6783
[email protected]8790210c2013-12-02 05:29:536784 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246785 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446786 TestURLRequestContext context(true);
6787 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436788 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446789 context.Init();
6790
6791 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196792 scoped_ptr<URLRequest> req(context.CreateRequest(
6793 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6794 NULL));
6795 req->Start();
[email protected]255620da2013-08-19 13:14:296796 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446797 EXPECT_EQ("en", d.data_received());
6798}
6799
6800// Check that an empty A-L header is not sent. http://crbug.com/77365.
6801TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6802 ASSERT_TRUE(test_server_.Start());
6803
[email protected]8790210c2013-12-02 05:29:536804 std::string empty_string; // Avoid most vexing parse on line below.
6805 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246806 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446807 TestURLRequestContext context(true);
6808 context.set_network_delegate(&network_delegate);
6809 context.Init();
6810 // We override the language after initialization because empty entries
6811 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436812 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446813
6814 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196815 scoped_ptr<URLRequest> req(context.CreateRequest(
6816 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6817 NULL));
6818 req->Start();
[email protected]255620da2013-08-19 13:14:296819 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446820 EXPECT_EQ("None", d.data_received());
6821}
6822
6823// Check that if request overrides the A-L header, the default is not appended.
6824// See http://crbug.com/20894
6825TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6826 ASSERT_TRUE(test_server_.Start());
6827
6828 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196829 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6830 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d,
6831 NULL));
[email protected]316c1e5e2012-09-12 15:17:446832 HttpRequestHeaders headers;
6833 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196834 req->SetExtraRequestHeaders(headers);
6835 req->Start();
[email protected]255620da2013-08-19 13:14:296836 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446837 EXPECT_EQ(std::string("ru"), d.data_received());
6838}
6839
6840// Check that default A-E header is sent.
6841TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6842 ASSERT_TRUE(test_server_.Start());
6843
6844 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196845 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6846 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6847 NULL));
[email protected]316c1e5e2012-09-12 15:17:446848 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196849 req->SetExtraRequestHeaders(headers);
6850 req->Start();
[email protected]255620da2013-08-19 13:14:296851 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446852 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6853}
6854
6855// Check that if request overrides the A-E header, the default is not appended.
6856// See http://crbug.com/47381
6857TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6858 ASSERT_TRUE(test_server_.Start());
6859
6860 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196861 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6862 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d,
6863 NULL));
[email protected]316c1e5e2012-09-12 15:17:446864 HttpRequestHeaders headers;
6865 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196866 req->SetExtraRequestHeaders(headers);
6867 req->Start();
[email protected]255620da2013-08-19 13:14:296868 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446869 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6870 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6871}
6872
[email protected]84f05432013-03-15 01:00:126873// Check that setting the A-C header sends the proper header.
6874TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446875 ASSERT_TRUE(test_server_.Start());
6876
6877 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196878 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6879 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d,
6880 NULL));
[email protected]316c1e5e2012-09-12 15:17:446881 HttpRequestHeaders headers;
6882 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196883 req->SetExtraRequestHeaders(headers);
6884 req->Start();
[email protected]255620da2013-08-19 13:14:296885 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446886 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6887}
6888
6889// Check that default User-Agent header is sent.
6890TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6891 ASSERT_TRUE(test_server_.Start());
6892
6893 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196894 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6895 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6896 NULL));
6897 req->Start();
[email protected]255620da2013-08-19 13:14:296898 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196899 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376900 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446901}
6902
6903// Check that if request overrides the User-Agent header,
6904// the default is not appended.
6905TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6906 ASSERT_TRUE(test_server_.Start());
6907
6908 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196909 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6910 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d,
6911 NULL));
[email protected]316c1e5e2012-09-12 15:17:446912 HttpRequestHeaders headers;
6913 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196914 req->SetExtraRequestHeaders(headers);
6915 req->Start();
[email protected]255620da2013-08-19 13:14:296916 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356917 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446918}
6919
[email protected]ee4c30d2012-11-07 15:08:436920// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6921// User-Agent header to be sent but does not send the Accept-Language and
6922// Accept-Charset headers.
6923TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6924 ASSERT_TRUE(test_server_.Start());
6925
[email protected]ceefd7fd2012-11-29 00:36:246926 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436927 TestURLRequestContext context(true);
6928 context.set_network_delegate(&network_delegate);
6929 context.Init();
6930 // We override the HttpUserAgentSettings after initialization because empty
6931 // entries get overridden by Init().
6932 context.set_http_user_agent_settings(NULL);
6933
6934 struct {
6935 const char* request;
6936 const char* expected_response;
6937 } tests[] = { { "echoheader?Accept-Language", "None" },
6938 { "echoheader?Accept-Charset", "None" },
6939 { "echoheader?User-Agent", "" } };
6940
viettrungluue4a8b882014-10-16 06:17:386941 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436942 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196943 scoped_ptr<URLRequest> req(context.CreateRequest(
6944 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, NULL));
6945 req->Start();
[email protected]255620da2013-08-19 13:14:296946 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436947 EXPECT_EQ(tests[i].expected_response, d.data_received())
6948 << " Request = \"" << tests[i].request << "\"";
6949 }
6950}
6951
[email protected]5033ab82013-03-22 20:17:466952// Make sure that URLRequest passes on its priority updates to
6953// newly-created jobs after the first one.
6954TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6955 ASSERT_TRUE(test_server_.Start());
6956
6957 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196958 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
6959 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
6960 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466961
6962 scoped_refptr<URLRequestRedirectJob> redirect_job =
6963 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196964 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096965 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506966 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466967
[email protected]f7022f32014-08-21 16:32:196968 req->SetPriority(LOW);
6969 req->Start();
6970 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466971
6972 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196973 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506974 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466975
6976 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296977 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466978 EXPECT_EQ(LOW, job->priority());
6979}
6980
[email protected]80abdad2014-03-15 00:20:546981// Check that creating a network request while entering/exiting suspend mode
6982// fails as it should. This is the only case where an HttpTransactionFactory
6983// does not return an HttpTransaction.
6984TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6985 // Create a new HttpNetworkLayer that thinks it's suspended.
6986 HttpNetworkSession::Params params;
6987 params.host_resolver = default_context_.host_resolver();
6988 params.cert_verifier = default_context_.cert_verifier();
6989 params.transport_security_state = default_context_.transport_security_state();
6990 params.proxy_service = default_context_.proxy_service();
6991 params.ssl_config_service = default_context_.ssl_config_service();
6992 params.http_auth_handler_factory =
6993 default_context_.http_auth_handler_factory();
6994 params.network_delegate = &default_network_delegate_;
6995 params.http_server_properties = default_context_.http_server_properties();
6996 scoped_ptr<HttpNetworkLayer> network_layer(
6997 new HttpNetworkLayer(new HttpNetworkSession(params)));
6998 network_layer->OnSuspend();
6999
7000 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
7001 HttpCache::DefaultBackend::InMemory(0));
7002
7003 TestURLRequestContext context(true);
7004 context.set_http_transaction_factory(&http_cache);
7005 context.Init();
7006
7007 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197008 scoped_ptr<URLRequest> req(context.CreateRequest(
7009 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7010 req->Start();
[email protected]80abdad2014-03-15 00:20:547011 base::RunLoop().Run();
7012
7013 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197014 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7015 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547016}
7017
7018// Check that creating a network request while entering/exiting suspend mode
7019// fails as it should in the case there is no cache. This is the only case
7020// where an HttpTransactionFactory does not return an HttpTransaction.
7021TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
7022 // Create a new HttpNetworkLayer that thinks it's suspended.
7023 HttpNetworkSession::Params params;
7024 params.host_resolver = default_context_.host_resolver();
7025 params.cert_verifier = default_context_.cert_verifier();
7026 params.transport_security_state = default_context_.transport_security_state();
7027 params.proxy_service = default_context_.proxy_service();
7028 params.ssl_config_service = default_context_.ssl_config_service();
7029 params.http_auth_handler_factory =
7030 default_context_.http_auth_handler_factory();
7031 params.network_delegate = &default_network_delegate_;
7032 params.http_server_properties = default_context_.http_server_properties();
7033 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
7034 network_layer.OnSuspend();
7035
7036 TestURLRequestContext context(true);
7037 context.set_http_transaction_factory(&network_layer);
7038 context.Init();
7039
7040 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197041 scoped_ptr<URLRequest> req(context.CreateRequest(
7042 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d, NULL));
7043 req->Start();
[email protected]80abdad2014-03-15 00:20:547044 base::RunLoop().Run();
7045
7046 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:197047 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
7048 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:547049}
7050
bengr1bf8e942014-11-07 01:36:507051class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
7052 public:
7053 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
7054 // ideally remove the dependency on URLRequestTestJob, and maybe move these
7055 // tests into the factory tests.
7056 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
7057 }
7058
7059 void SetUpFactory() override {
7060 interceptor_ = new MockURLRequestInterceptor();
7061 job_factory_.reset(new URLRequestInterceptingJobFactory(
7062 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
7063 }
7064
7065 MockURLRequestInterceptor* interceptor() const {
7066 return interceptor_;
7067 }
7068
7069 private:
7070 MockURLRequestInterceptor* interceptor_;
7071};
7072
7073TEST_F(URLRequestInterceptorTestHTTP,
7074 NetworkDelegateNotificationOnRedirectIntercept) {
7075 interceptor()->set_intercept_redirect(true);
7076 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
7077 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
7078
7079 ASSERT_TRUE(test_server()->Start());
7080
7081 TestDelegate d;
7082 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7083 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY,
7084 &d, nullptr));
7085 req->Start();
7086 base::RunLoop().Run();
7087
7088 EXPECT_TRUE(interceptor()->did_intercept_redirect());
7089 // Check we got one good response
7090 EXPECT_TRUE(req->status().is_success());
7091 if (req->status().is_success())
7092 EXPECT_EQ(200, req->response_headers()->response_code());
7093
7094 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7095 EXPECT_EQ(1, d.response_started_count());
7096 EXPECT_EQ(0, d.received_redirect_count());
7097
7098 EXPECT_EQ(1, default_network_delegate()->created_requests());
7099 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7100 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
7101}
7102
7103TEST_F(URLRequestInterceptorTestHTTP,
7104 NetworkDelegateNotificationOnErrorIntercept) {
7105 // Intercept that error and respond with an OK response.
7106 interceptor()->set_intercept_final_response(true);
7107 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
7108 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
7109 default_network_delegate()->set_can_be_intercepted_on_error(true);
7110
7111 ASSERT_TRUE(test_server()->Start());
7112
7113 TestDelegate d;
7114 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7115 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
7116 &d, nullptr));
7117 req->set_method("GET");
7118 req->Start();
7119 base::RunLoop().Run();
7120
7121 EXPECT_TRUE(interceptor()->did_intercept_final());
7122
7123 // Check we received one good response.
7124 EXPECT_TRUE(req->status().is_success());
7125 if (req->status().is_success())
7126 EXPECT_EQ(200, req->response_headers()->response_code());
7127 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
7128 EXPECT_EQ(1, d.response_started_count());
7129 EXPECT_EQ(0, d.received_redirect_count());
7130
7131 EXPECT_EQ(1, default_network_delegate()->created_requests());
7132 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
7133 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
7134}
7135
7136TEST_F(URLRequestInterceptorTestHTTP,
7137 NetworkDelegateNotificationOnResponseIntercept) {
7138 // Intercept that error and respond with an OK response.
7139 interceptor()->set_intercept_final_response(true);
7140
7141 // Intercept with a real URLRequestHttpJob.
7142 interceptor()->set_use_url_request_http_job(true);
7143
7144 ASSERT_TRUE(test_server()->Start());
7145
7146 TestDelegate d;
7147 scoped_ptr<URLRequest> req(default_context().CreateRequest(
7148 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY,
7149 &d, nullptr));
7150 req->set_method("GET");
7151 req->Start();
7152 base::RunLoop().Run();
7153
7154 EXPECT_TRUE(interceptor()->did_intercept_final());
7155
7156 // Check we received one good response.
7157 EXPECT_TRUE(req->status().is_success());
7158 if (req->status().is_success())
7159 EXPECT_EQ(200, req->response_headers()->response_code());
7160 EXPECT_EQ("hello", d.data_received());
7161 EXPECT_EQ(1, d.response_started_count());
7162 EXPECT_EQ(0, d.received_redirect_count());
7163
7164 EXPECT_EQ(1, default_network_delegate()->created_requests());
7165 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
7166 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
7167}
7168
[email protected]73e0bba2009-02-19 22:57:097169class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507170 public:
[email protected]ef2bf422012-05-11 03:27:097171 HTTPSRequestTest() : default_context_(true) {
7172 default_context_.set_network_delegate(&default_network_delegate_);
7173 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507174 }
dcheng67be2b1f2014-10-27 21:47:297175 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507176
7177 protected:
[email protected]ceefd7fd2012-11-29 00:36:247178 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097179 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467180};
7181
[email protected]c044616e2013-02-20 02:01:267182TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227183 SpawnedTestServer test_server(
7184 SpawnedTestServer::TYPE_HTTPS,
7185 SpawnedTestServer::kLocalhost,
7186 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117187 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467188
[email protected]ea224582008-12-07 20:25:467189 TestDelegate d;
7190 {
[email protected]f7022f32014-08-21 16:32:197191 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7192 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
7193 r->Start();
7194 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467195
[email protected]255620da2013-08-19 13:14:297196 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467197
7198 EXPECT_EQ(1, d.response_started_count());
7199 EXPECT_FALSE(d.received_data_before_response());
7200 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197201 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197202 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197203 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197204 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197205 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467206 }
[email protected]ea224582008-12-07 20:25:467207}
7208
[email protected]5774ada2010-07-15 06:30:547209TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227210 SpawnedTestServer::SSLOptions ssl_options(
7211 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7212 SpawnedTestServer test_server(
7213 SpawnedTestServer::TYPE_HTTPS,
7214 ssl_options,
7215 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117216 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337217
7218 bool err_allowed = true;
7219 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7220 TestDelegate d;
7221 {
7222 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197223 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7224 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]bacff652009-03-31 17:50:337225
[email protected]f7022f32014-08-21 16:32:197226 r->Start();
7227 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337228
[email protected]255620da2013-08-19 13:14:297229 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337230
7231 EXPECT_EQ(1, d.response_started_count());
7232 EXPECT_FALSE(d.received_data_before_response());
7233 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177234 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337235 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197236 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177237 } else {
[email protected]bacff652009-03-31 17:50:337238 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177239 }
[email protected]bacff652009-03-31 17:50:337240 }
7241 }
7242}
7243
[email protected]5774ada2010-07-15 06:30:547244TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227245 SpawnedTestServer::SSLOptions ssl_options(
7246 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7247 SpawnedTestServer test_server(
7248 SpawnedTestServer::TYPE_HTTPS,
7249 ssl_options,
7250 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117251 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337252
7253 // Iterate from false to true, just so that we do the opposite of the
7254 // previous test in order to increase test coverage.
7255 bool err_allowed = false;
7256 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7257 TestDelegate d;
7258 {
7259 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197260 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7261 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]bacff652009-03-31 17:50:337262
[email protected]f7022f32014-08-21 16:32:197263 r->Start();
7264 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337265
[email protected]255620da2013-08-19 13:14:297266 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337267
7268 EXPECT_EQ(1, d.response_started_count());
7269 EXPECT_FALSE(d.received_data_before_response());
7270 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177271 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337272 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197273 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177274 } else {
[email protected]bacff652009-03-31 17:50:337275 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177276 }
[email protected]bacff652009-03-31 17:50:337277 }
7278 }
7279}
[email protected]73e0bba2009-02-19 22:57:097280
[email protected]316c1e5e2012-09-12 15:17:447281// This tests that a load of www.google.com with a certificate error sets
7282// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7283// the interstitial to be fatal.
7284TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227285 SpawnedTestServer::SSLOptions ssl_options(
7286 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7287 SpawnedTestServer test_server(
7288 SpawnedTestServer::TYPE_HTTPS,
7289 ssl_options,
7290 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447291 ASSERT_TRUE(test_server.Start());
7292
7293 // We require that the URL be www.google.com in order to pick up the
7294 // preloaded HSTS entries in the TransportSecurityState. This means that we
7295 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247296 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447297
7298 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247299 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447300 TestURLRequestContext context(true);
7301 context.set_network_delegate(&network_delegate);
7302 context.set_host_resolver(&host_resolver);
7303 TransportSecurityState transport_security_state;
7304 context.set_transport_security_state(&transport_security_state);
7305 context.Init();
7306
7307 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197308 scoped_ptr<URLRequest> r(context.CreateRequest(
7309 GURL(base::StringPrintf("https://www.google.com:%d",
7310 test_server.host_port_pair().port())),
7311 DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447312
[email protected]f7022f32014-08-21 16:32:197313 r->Start();
7314 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447315
[email protected]255620da2013-08-19 13:14:297316 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447317
7318 EXPECT_EQ(1, d.response_started_count());
7319 EXPECT_FALSE(d.received_data_before_response());
7320 EXPECT_TRUE(d.have_certificate_errors());
7321 EXPECT_TRUE(d.certificate_errors_are_fatal());
7322}
7323
7324// This tests that cached HTTPS page loads do not cause any updates to the
7325// TransportSecurityState.
7326TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7327 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7328 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227329 SpawnedTestServer::SSLOptions ssl_options(
7330 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7331 SpawnedTestServer test_server(
7332 SpawnedTestServer::TYPE_HTTPS,
7333 ssl_options,
7334 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447335 ASSERT_TRUE(test_server.Start());
7336
[email protected]9e6968d2014-05-07 21:46:267337 // We require that the URL be www.google.com in order to pick up the static
7338 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7339 // that we have to use a MockHostResolver in order to direct www.google.com to
7340 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447341
7342 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247343 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447344 TestURLRequestContext context(true);
7345 context.set_network_delegate(&network_delegate);
7346 context.set_host_resolver(&host_resolver);
7347 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267348
7349 TransportSecurityState::DomainState static_domain_state;
7350 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127351 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447352 context.set_transport_security_state(&transport_security_state);
7353 context.Init();
7354
[email protected]9e6968d2014-05-07 21:46:267355 TransportSecurityState::DomainState dynamic_domain_state;
7356 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7357 "www.google.com", &dynamic_domain_state));
7358
[email protected]316c1e5e2012-09-12 15:17:447359 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197360 scoped_ptr<URLRequest> r(context.CreateRequest(
7361 GURL(base::StringPrintf("https://www.google.com:%d",
7362 test_server.host_port_pair().port())),
7363 DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447364
[email protected]f7022f32014-08-21 16:32:197365 r->Start();
7366 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447367
[email protected]255620da2013-08-19 13:14:297368 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447369
7370 EXPECT_EQ(1, d.response_started_count());
7371 EXPECT_FALSE(d.received_data_before_response());
7372 EXPECT_TRUE(d.have_certificate_errors());
7373 EXPECT_TRUE(d.certificate_errors_are_fatal());
7374
[email protected]9e6968d2014-05-07 21:46:267375 // Get a fresh copy of the states, and check that they haven't changed.
7376 TransportSecurityState::DomainState new_static_domain_state;
7377 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127378 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267379 TransportSecurityState::DomainState new_dynamic_domain_state;
7380 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7381 "www.google.com", &new_dynamic_domain_state));
7382
7383 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7384 static_domain_state.sts.upgrade_mode);
7385 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7386 static_domain_state.sts.include_subdomains);
7387 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7388 static_domain_state.pkp.include_subdomains);
7389 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7390 static_domain_state.pkp.spki_hashes));
7391 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7392 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447393}
7394
[email protected]8ccc69f2012-11-28 19:52:147395// Make sure HSTS preserves a POST request's method and body.
7396TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7397 static const char kData[] = "hello world";
7398
[email protected]ce7d0cbc2013-05-03 18:57:227399 SpawnedTestServer::SSLOptions ssl_options(
7400 SpawnedTestServer::SSLOptions::CERT_OK);
7401 SpawnedTestServer test_server(
7402 SpawnedTestServer::TYPE_HTTPS,
7403 ssl_options,
7404 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147405 ASSERT_TRUE(test_server.Start());
7406
7407
7408 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7409 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227410 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7411 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147412 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147413
7414 // Force https for www.somewhere.com.
7415 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207416 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7417 bool include_subdomains = false;
7418 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7419 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147420
7421 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7422
7423 TestURLRequestContext context(true);
7424 context.set_host_resolver(&host_resolver);
7425 context.set_transport_security_state(&transport_security_state);
7426 context.set_network_delegate(&network_delegate);
7427 context.Init();
7428
7429 TestDelegate d;
7430 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7431 // cause a certificate error. Ignore the error.
7432 d.set_allow_certificate_errors(true);
7433
[email protected]f7022f32014-08-21 16:32:197434 scoped_ptr<URLRequest> req(context.CreateRequest(
7435 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
7436 test_server.host_port_pair().port())),
7437 DEFAULT_PRIORITY, &d, NULL));
7438 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077439 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147440
[email protected]f7022f32014-08-21 16:32:197441 req->Start();
[email protected]255620da2013-08-19 13:14:297442 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147443
[email protected]f7022f32014-08-21 16:32:197444 EXPECT_EQ("https", req->url().scheme());
7445 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147446 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407447
7448 LoadTimingInfo load_timing_info;
7449 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7450 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7451 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147452}
7453
rob4e0be1f2014-09-11 23:40:227454// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7455TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7456 static const char kOriginHeaderValue[] = "http://www.example.com";
7457
7458 SpawnedTestServer::SSLOptions ssl_options(
7459 SpawnedTestServer::SSLOptions::CERT_OK);
7460 SpawnedTestServer test_server(
7461 SpawnedTestServer::TYPE_HTTPS,
7462 ssl_options,
7463 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7464 ASSERT_TRUE(test_server.Start());
7465
7466 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7467 // address, so a MockHostResolver is needed to redirect example.net to the
7468 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7469 MockHostResolver host_resolver;
7470
7471 TransportSecurityState transport_security_state;
7472 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7473 bool include_subdomains = false;
7474 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7475
7476 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7477
7478 MockCertVerifier cert_verifier;
7479 cert_verifier.set_default_result(OK);
7480
7481 TestURLRequestContext context(true);
7482 context.set_host_resolver(&host_resolver);
7483 context.set_transport_security_state(&transport_security_state);
7484 context.set_network_delegate(&network_delegate);
7485 context.set_cert_verifier(&cert_verifier);
7486 context.Init();
7487
7488 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7489 test_server.host_port_pair().port()));
7490 url::Replacements<char> replacements;
7491 const char kNewScheme[] = "https";
7492 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7493 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7494
7495 TestDelegate d;
7496 // Quit on redirect to allow response header inspection upon redirect.
7497 d.set_quit_on_redirect(true);
7498
7499 scoped_ptr<URLRequest> req(context.CreateRequest(hsts_http_url,
7500 DEFAULT_PRIORITY, &d, NULL));
7501 // Set Origin header to simulate a cross-origin request.
7502 HttpRequestHeaders request_headers;
7503 request_headers.SetHeader("Origin", kOriginHeaderValue);
7504 req->SetExtraRequestHeaders(request_headers);
7505
7506 req->Start();
7507 base::RunLoop().Run();
7508
7509 EXPECT_EQ(1, d.received_redirect_count());
7510
7511 const HttpResponseHeaders* headers = req->response_headers();
7512 std::string redirect_location;
7513 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7514 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7515
7516 std::string received_cors_header;
7517 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7518 &received_cors_header));
7519 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7520}
7521
[email protected]316c1e5e2012-09-12 15:17:447522namespace {
7523
7524class SSLClientAuthTestDelegate : public TestDelegate {
7525 public:
7526 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7527 }
dchengb03027d2014-10-21 12:00:207528 void OnCertificateRequested(URLRequest* request,
7529 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447530 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347531 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447532 }
7533 int on_certificate_requested_count() {
7534 return on_certificate_requested_count_;
7535 }
7536 private:
7537 int on_certificate_requested_count_;
7538};
7539
7540} // namespace
7541
7542// TODO(davidben): Test the rest of the code. Specifically,
7543// - Filtering which certificates to select.
7544// - Sending a certificate back.
7545// - Getting a certificate request in an SSL renegotiation sending the
7546// HTTP request.
7547TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227548 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447549 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227550 SpawnedTestServer test_server(
7551 SpawnedTestServer::TYPE_HTTPS,
7552 ssl_options,
7553 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447554 ASSERT_TRUE(test_server.Start());
7555
7556 SSLClientAuthTestDelegate d;
7557 {
[email protected]f7022f32014-08-21 16:32:197558 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7559 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447560
[email protected]f7022f32014-08-21 16:32:197561 r->Start();
7562 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447563
[email protected]255620da2013-08-19 13:14:297564 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447565
7566 EXPECT_EQ(1, d.on_certificate_requested_count());
7567 EXPECT_FALSE(d.received_data_before_response());
7568 EXPECT_EQ(0, d.bytes_received());
7569
7570 // Send no certificate.
7571 // TODO(davidben): Get temporary client cert import (with keys) working on
7572 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197573 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447574
[email protected]255620da2013-08-19 13:14:297575 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447576
7577 EXPECT_EQ(1, d.response_started_count());
7578 EXPECT_FALSE(d.received_data_before_response());
7579 EXPECT_NE(0, d.bytes_received());
7580 }
7581}
7582
7583TEST_F(HTTPSRequestTest, ResumeTest) {
7584 // Test that we attempt a session resume when making two connections to the
7585 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227586 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447587 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227588 SpawnedTestServer test_server(
7589 SpawnedTestServer::TYPE_HTTPS,
7590 ssl_options,
7591 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447592 ASSERT_TRUE(test_server.Start());
7593
7594 SSLClientSocket::ClearSessionCache();
7595
7596 {
7597 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197598 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7599 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447600
[email protected]f7022f32014-08-21 16:32:197601 r->Start();
7602 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447603
[email protected]255620da2013-08-19 13:14:297604 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447605
7606 EXPECT_EQ(1, d.response_started_count());
7607 }
7608
7609 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7610 CloseAllConnections();
7611
7612 {
7613 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197614 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7615 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447616
[email protected]f7022f32014-08-21 16:32:197617 r->Start();
7618 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447619
[email protected]255620da2013-08-19 13:14:297620 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447621
7622 // The response will look like;
7623 // insert abc
7624 // lookup abc
7625 // insert xyz
7626 //
7627 // With a newline at the end which makes the split think that there are
7628 // four lines.
7629
7630 EXPECT_EQ(1, d.response_started_count());
7631 std::vector<std::string> lines;
7632 base::SplitString(d.data_received(), '\n', &lines);
7633 ASSERT_EQ(4u, lines.size()) << d.data_received();
7634
7635 std::string session_id;
7636
7637 for (size_t i = 0; i < 2; i++) {
7638 std::vector<std::string> parts;
7639 base::SplitString(lines[i], '\t', &parts);
7640 ASSERT_EQ(2u, parts.size());
7641 if (i == 0) {
7642 EXPECT_EQ("insert", parts[0]);
7643 session_id = parts[1];
7644 } else {
7645 EXPECT_EQ("lookup", parts[0]);
7646 EXPECT_EQ(session_id, parts[1]);
7647 }
7648 }
7649 }
7650}
7651
Adam Langley32352ad2014-10-14 22:31:007652// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7653// the result of fetching "ssl-session-cache" from the test server, indicates
7654// that exactly two different sessions were inserted, with no lookups etc.
7655static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7656 std::vector<std::string> lines;
7657 base::SplitString(session_info, '\n', &lines);
7658 ASSERT_EQ(3u, lines.size()) << session_info;
7659
7660 std::string session_id;
7661 for (size_t i = 0; i < 2; i++) {
7662 std::vector<std::string> parts;
7663 base::SplitString(lines[i], '\t', &parts);
7664 ASSERT_EQ(2u, parts.size());
7665 EXPECT_EQ("insert", parts[0]);
7666 if (i == 0) {
7667 session_id = parts[1];
7668 } else {
7669 EXPECT_NE(session_id, parts[1]);
7670 }
7671 }
7672}
7673
[email protected]316c1e5e2012-09-12 15:17:447674TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7675 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7676 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227677 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447678 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227679 SpawnedTestServer test_server(
7680 SpawnedTestServer::TYPE_HTTPS,
7681 ssl_options,
7682 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447683 ASSERT_TRUE(test_server.Start());
7684
7685 SSLClientSocket::ClearSessionCache();
7686
7687 {
7688 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197689 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7690 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447691
[email protected]f7022f32014-08-21 16:32:197692 r->Start();
7693 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447694
[email protected]255620da2013-08-19 13:14:297695 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447696
7697 EXPECT_EQ(1, d.response_started_count());
7698 }
7699
7700 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7701 HttpNetworkSession::Params params;
7702 params.host_resolver = default_context_.host_resolver();
7703 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117704 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447705 params.proxy_service = default_context_.proxy_service();
7706 params.ssl_config_service = default_context_.ssl_config_service();
7707 params.http_auth_handler_factory =
7708 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417709 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447710 params.http_server_properties = default_context_.http_server_properties();
7711 params.ssl_session_cache_shard = "alternate";
7712
[email protected]cba24642014-08-15 20:49:597713 scoped_ptr<HttpCache> cache(new HttpCache(
7714 new HttpNetworkSession(params),
7715 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447716
7717 default_context_.set_http_transaction_factory(cache.get());
7718
7719 {
7720 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197721 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7722 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]316c1e5e2012-09-12 15:17:447723
[email protected]f7022f32014-08-21 16:32:197724 r->Start();
7725 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447726
[email protected]255620da2013-08-19 13:14:297727 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447728
7729 // The response will look like;
7730 // insert abc
7731 // insert xyz
7732 //
7733 // With a newline at the end which makes the split think that there are
7734 // three lines.
7735
7736 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007737 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447738 }
7739}
7740
davidben8ecc3072014-09-03 23:19:097741#if defined(OS_WIN)
7742
7743namespace {
7744
7745bool IsECDSACipherSuite(uint16_t cipher_suite) {
7746 const char* key_exchange;
7747 const char* cipher;
7748 const char* mac;
7749 bool is_aead;
7750 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7751 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7752}
7753
7754} // namespace
7755
7756// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7757// verified.
davidben9399c952014-10-07 04:09:117758TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097759 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7760 LOG(INFO) << "Skipping test on this version.";
7761 return;
7762 }
7763
7764 SpawnedTestServer test_server(
7765 SpawnedTestServer::TYPE_HTTPS,
7766 SpawnedTestServer::kLocalhost,
7767 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7768 ASSERT_TRUE(test_server.Start());
7769
7770 TestDelegate d;
7771 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
7772 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d, NULL));
7773 r->Start();
7774 EXPECT_TRUE(r->is_pending());
7775
7776 base::RunLoop().Run();
7777
7778 EXPECT_EQ(1, d.response_started_count());
7779 std::vector<std::string> lines;
7780 base::SplitString(d.data_received(), '\n', &lines);
7781
7782 for (size_t i = 0; i < lines.size(); i++) {
7783 int cipher_suite;
7784 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7785 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7786 << "ClientHello advertised " << cipher_suite;
7787 }
7788}
7789
7790#endif // OS_WIN
7791
Adam Langley32352ad2014-10-14 22:31:007792class TestSSLConfigService : public SSLConfigService {
7793 public:
7794 TestSSLConfigService(bool ev_enabled,
7795 bool online_rev_checking,
7796 bool rev_checking_required_local_anchors)
7797 : ev_enabled_(ev_enabled),
7798 online_rev_checking_(online_rev_checking),
7799 rev_checking_required_local_anchors_(
7800 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027801 min_version_(kDefaultSSLVersionMin),
7802 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7803
7804 void set_min_version(uint16 version) {
7805 min_version_ = version;
7806 }
Adam Langley32352ad2014-10-14 22:31:007807
7808 void set_fallback_min_version(uint16 version) {
7809 fallback_min_version_ = version;
7810 }
7811
7812 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207813 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007814 *config = SSLConfig();
7815 config->rev_checking_enabled = online_rev_checking_;
7816 config->verify_ev_cert = ev_enabled_;
7817 config->rev_checking_required_local_anchors =
7818 rev_checking_required_local_anchors_;
7819 if (fallback_min_version_) {
7820 config->version_fallback_min = fallback_min_version_;
7821 }
Adam Langleyac6f24b42014-10-31 20:24:027822 if (min_version_) {
7823 config->version_min = min_version_;
7824 }
Adam Langley32352ad2014-10-14 22:31:007825 }
7826
7827 protected:
dchengb03027d2014-10-21 12:00:207828 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007829
7830 private:
7831 const bool ev_enabled_;
7832 const bool online_rev_checking_;
7833 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027834 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007835 uint16 fallback_min_version_;
7836};
7837
7838class FallbackTestURLRequestContext : public TestURLRequestContext {
7839 public:
7840 explicit FallbackTestURLRequestContext(bool delay_initialization)
7841 : TestURLRequestContext(delay_initialization) {}
7842
7843 void set_fallback_min_version(uint16 version) {
7844 TestSSLConfigService *ssl_config_service =
7845 new TestSSLConfigService(true /* check for EV */,
7846 false /* online revocation checking */,
7847 false /* require rev. checking for local
7848 anchors */);
Adam Langleyac6f24b42014-10-31 20:24:027849 ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
Adam Langley32352ad2014-10-14 22:31:007850 ssl_config_service->set_fallback_min_version(version);
7851 set_ssl_config_service(ssl_config_service);
7852 }
7853};
7854
[email protected]48d2b7c52014-06-27 01:16:557855class HTTPSFallbackTest : public testing::Test {
7856 public:
Adam Langley32352ad2014-10-14 22:31:007857 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297858 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557859
7860 protected:
7861 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7862 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:007863 context_.Init();
7864 delegate_.set_allow_certificate_errors(true);
7865
[email protected]48d2b7c52014-06-27 01:16:557866 SpawnedTestServer test_server(
7867 SpawnedTestServer::TYPE_HTTPS,
7868 ssl_options,
7869 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7870 ASSERT_TRUE(test_server.Start());
7871
[email protected]f7022f32014-08-21 16:32:197872 request_ = context_.CreateRequest(
7873 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate_, NULL);
[email protected]48d2b7c52014-06-27 01:16:557874 request_->Start();
7875
7876 base::RunLoop().Run();
7877 }
7878
Adam Langley32352ad2014-10-14 22:31:007879 void set_fallback_min_version(uint16 version) {
7880 context_.set_fallback_min_version(version);
7881 }
7882
[email protected]48d2b7c52014-06-27 01:16:557883 void ExpectConnection(int version) {
7884 EXPECT_EQ(1, delegate_.response_started_count());
7885 EXPECT_NE(0, delegate_.bytes_received());
7886 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7887 request_->ssl_info().connection_status));
7888 EXPECT_TRUE(request_->ssl_info().connection_status &
7889 SSL_CONNECTION_VERSION_FALLBACK);
7890 }
7891
7892 void ExpectFailure(int error) {
7893 EXPECT_EQ(1, delegate_.response_started_count());
7894 EXPECT_FALSE(request_->status().is_success());
7895 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7896 EXPECT_EQ(error, request_->status().error());
7897 }
7898
7899 private:
7900 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:007901 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:557902 scoped_ptr<URLRequest> request_;
7903};
7904
7905// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7906// than necessary.
7907TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7908 SpawnedTestServer::SSLOptions ssl_options(
7909 SpawnedTestServer::SSLOptions::CERT_OK);
7910 ssl_options.tls_intolerant =
7911 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7912
7913 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7914 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7915}
7916
7917// This test is disabled on Android because the remote test server doesn't cause
7918// a TCP reset.
7919#if !defined(OS_ANDROID)
7920// Tests fallback to TLS 1.0 on connection reset.
7921TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7922 SpawnedTestServer::SSLOptions ssl_options(
7923 SpawnedTestServer::SSLOptions::CERT_OK);
7924 ssl_options.tls_intolerant =
7925 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7926 ssl_options.tls_intolerance_type =
7927 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7928
7929 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7930 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7931}
7932#endif // !OS_ANDROID
7933
[email protected]12833302014-07-02 01:57:317934// Tests that we don't fallback on handshake failure with servers that implement
7935// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:557936TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:557937 SpawnedTestServer::SSLOptions ssl_options(
7938 SpawnedTestServer::SSLOptions::CERT_OK);
7939 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7940 // a version fallback.
7941 ssl_options.tls_intolerant =
7942 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7943 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7944 // connections are rejected.
7945 ssl_options.fallback_scsv_enabled = true;
7946
7947 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7948
7949 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7950 // intolerance. If the fallback SCSV is processed when the original error
7951 // that caused the fallback should be returned, which should be
7952 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7953 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7954}
7955
[email protected]12833302014-07-02 01:57:317956// Tests that we don't fallback on connection closed with servers that implement
7957// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:317958TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:317959 SpawnedTestServer::SSLOptions ssl_options(
7960 SpawnedTestServer::SSLOptions::CERT_OK);
7961 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7962 // a version fallback.
7963 ssl_options.tls_intolerant =
7964 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7965 ssl_options.tls_intolerance_type =
7966 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7967 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7968 // connections are rejected.
7969 ssl_options.fallback_scsv_enabled = true;
7970
7971 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7972
7973 // The original error should be replayed on rejected fallback.
7974 ExpectFailure(ERR_CONNECTION_CLOSED);
7975}
7976
Adam Langley32352ad2014-10-14 22:31:007977// Tests that the SSLv3 fallback doesn't happen by default.
[email protected]48d2b7c52014-06-27 01:16:557978TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7979 SpawnedTestServer::SSLOptions ssl_options(
7980 SpawnedTestServer::SSLOptions::CERT_OK);
7981 ssl_options.tls_intolerant =
7982 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7983
7984 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:027985 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:007986}
7987
7988// Tests that the SSLv3 fallback works when explicitly enabled.
7989TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7990 SpawnedTestServer::SSLOptions ssl_options(
7991 SpawnedTestServer::SSLOptions::CERT_OK);
7992 ssl_options.tls_intolerant =
7993 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7994 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7995
7996 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:557997 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7998}
7999
Adam Langley32352ad2014-10-14 22:31:008000// Tests that the SSLv3 fallback triggers on closed connections when explicitly
8001// enabled.
[email protected]48d2b7c52014-06-27 01:16:558002TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
8003 SpawnedTestServer::SSLOptions ssl_options(
8004 SpawnedTestServer::SSLOptions::CERT_OK);
8005 ssl_options.tls_intolerant =
8006 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8007 ssl_options.tls_intolerance_type =
8008 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
Adam Langley32352ad2014-10-14 22:31:008009 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
[email protected]48d2b7c52014-06-27 01:16:558010
8011 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8012 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
8013}
8014
Adam Langley32352ad2014-10-14 22:31:008015// Test that SSLv3 fallback probe connections don't cause sessions to be cached.
8016TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
8017 SpawnedTestServer::SSLOptions ssl_options(
8018 SpawnedTestServer::SSLOptions::CERT_OK);
8019 ssl_options.tls_intolerant =
8020 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8021 ssl_options.tls_intolerance_type =
8022 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
8023 ssl_options.record_resume = true;
8024
8025 SpawnedTestServer test_server(
8026 SpawnedTestServer::TYPE_HTTPS,
8027 ssl_options,
8028 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8029 ASSERT_TRUE(test_server.Start());
8030
8031 SSLClientSocket::ClearSessionCache();
8032
8033 // Make a connection that does a probe fallback to SSLv3 but fails because
8034 // SSLv3 fallback is disabled. We don't wish a session for this connection to
8035 // be inserted locally.
8036 {
8037 TestDelegate delegate;
8038 FallbackTestURLRequestContext context(true);
8039
Adam Langleyac6f24b42014-10-31 20:24:028040 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:008041 context.Init();
8042 scoped_ptr<URLRequest> request(context.CreateRequest(
8043 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate, NULL));
8044 request->Start();
8045
8046 base::RunLoop().Run();
8047
8048 EXPECT_EQ(1, delegate.response_started_count());
8049 EXPECT_FALSE(request->status().is_success());
8050 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
8051 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
8052 request->status().error());
8053 }
8054
8055 // Now allow SSLv3 connections and request the session cache log.
8056 {
8057 TestDelegate delegate;
8058 FallbackTestURLRequestContext context(true);
8059 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
8060
8061 context.Init();
8062 scoped_ptr<URLRequest> request(
8063 context.CreateRequest(test_server.GetURL("ssl-session-cache"),
8064 DEFAULT_PRIORITY,
8065 &delegate,
8066 NULL));
8067 request->Start();
8068
8069 base::RunLoop().Run();
8070
8071 EXPECT_EQ(1, delegate.response_started_count());
8072 EXPECT_NE(0, delegate.bytes_received());
8073 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
8074 request->ssl_info().connection_status));
8075 EXPECT_TRUE(request->ssl_info().connection_status &
8076 SSL_CONNECTION_VERSION_FALLBACK);
8077
8078 std::vector<std::string> lines;
8079 // If no sessions were cached then the server should have seen two sessions
8080 // inserted with no lookups.
8081 AssertTwoDistinctSessionsInserted(delegate.data_received());
8082 }
8083}
8084
[email protected]48d2b7c52014-06-27 01:16:558085// This test is disabled on Android because the remote test server doesn't cause
[email protected]5aea79182014-07-14 20:43:418086// a TCP reset.
8087#if !defined(OS_ANDROID)
[email protected]48d2b7c52014-06-27 01:16:558088// Tests that a reset connection does not fallback down to SSL3.
8089TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
8090 SpawnedTestServer::SSLOptions ssl_options(
8091 SpawnedTestServer::SSLOptions::CERT_OK);
8092 ssl_options.tls_intolerant =
8093 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
8094 ssl_options.tls_intolerance_type =
8095 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
8096
8097 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
8098 ExpectFailure(ERR_CONNECTION_RESET);
8099}
[email protected]5aea79182014-07-14 20:43:418100#endif // !OS_ANDROID
[email protected]48d2b7c52014-06-27 01:16:558101
[email protected]a8fed1742013-12-27 02:14:248102class HTTPSSessionTest : public testing::Test {
8103 public:
8104 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:598105 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248106
8107 default_context_.set_network_delegate(&default_network_delegate_);
8108 default_context_.set_cert_verifier(&cert_verifier_);
8109 default_context_.Init();
8110 }
dcheng67be2b1f2014-10-27 21:47:298111 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:248112
8113 protected:
8114 MockCertVerifier cert_verifier_;
8115 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
8116 TestURLRequestContext default_context_;
8117};
8118
8119// Tests that session resumption is not attempted if an invalid certificate
8120// is presented.
8121TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
8122 SpawnedTestServer::SSLOptions ssl_options;
8123 ssl_options.record_resume = true;
8124 SpawnedTestServer test_server(
8125 SpawnedTestServer::TYPE_HTTPS,
8126 ssl_options,
8127 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8128 ASSERT_TRUE(test_server.Start());
8129
8130 SSLClientSocket::ClearSessionCache();
8131
8132 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598133 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248134 {
8135 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198136 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8137 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]a8fed1742013-12-27 02:14:248138
[email protected]f7022f32014-08-21 16:32:198139 r->Start();
8140 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248141
8142 base::RunLoop().Run();
8143
8144 EXPECT_EQ(1, d.response_started_count());
8145 }
8146
8147 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8148 CloseAllConnections();
8149
8150 // Now change the certificate to be acceptable (so that the response is
8151 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598152 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248153 {
8154 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198155 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8156 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d, NULL));
[email protected]a8fed1742013-12-27 02:14:248157
[email protected]f7022f32014-08-21 16:32:198158 r->Start();
8159 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248160
8161 base::RunLoop().Run();
8162
8163 // The response will look like;
8164 // insert abc
8165 // insert xyz
8166 //
8167 // With a newline at the end which makes the split think that there are
8168 // three lines.
8169 //
8170 // If a session was presented (eg: a bug), then the response would look
8171 // like;
8172 // insert abc
8173 // lookup abc
8174 // insert xyz
8175
8176 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008177 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248178 }
8179}
8180
[email protected]dffe8242012-03-20 15:14:278181// This the fingerprint of the "Testing CA" certificate used by the testserver.
8182// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268183static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278184 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8185 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8186
[email protected]51523f52013-07-31 21:57:288187// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8188// testserver.
8189static const SHA256HashValue kOCSPTestCertSPKI = { {
8190 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8191 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8192 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8193 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8194} };
8195
[email protected]dffe8242012-03-20 15:14:278196// This is the policy OID contained in the certificates that testserver
8197// generates.
8198static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8199
8200class HTTPSOCSPTest : public HTTPSRequestTest {
8201 public:
8202 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098203 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088204 ev_test_policy_(
8205 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8206 kOCSPTestCertFingerprint,
8207 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028208 }
8209
dcheng67be2b1f2014-10-27 21:47:298210 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098211 SetupContext(&context_);
8212 context_.Init();
[email protected]dffe8242012-03-20 15:14:278213
[email protected]cba24642014-08-15 20:49:598214 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208215 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428216 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508217 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278218
[email protected]a592c0432012-12-01 18:10:298219#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098220 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278221 EnsureNSSHttpIOInit();
8222#endif
8223 }
8224
[email protected]ce7d0cbc2013-05-03 18:57:228225 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278226 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538227 // We always overwrite out_cert_status.
8228 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228229 SpawnedTestServer test_server(
8230 SpawnedTestServer::TYPE_HTTPS,
8231 ssl_options,
8232 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278233 ASSERT_TRUE(test_server.Start());
8234
8235 TestDelegate d;
8236 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198237 scoped_ptr<URLRequest> r(context_.CreateRequest(
8238 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
8239 r->Start();
[email protected]dffe8242012-03-20 15:14:278240
[email protected]255620da2013-08-19 13:14:298241 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278242
8243 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198244 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278245 }
8246
dcheng67be2b1f2014-10-27 21:47:298247 ~HTTPSOCSPTest() override {
[email protected]a592c0432012-12-01 18:10:298248#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278249 ShutdownNSSHttpIO();
8250#endif
8251 }
8252
[email protected]a13234c2012-03-20 21:45:028253 protected:
8254 // SetupContext configures the URLRequestContext that will be used for making
8255 // connetions to testserver. This can be overridden in test subclasses for
8256 // different behaviour.
8257 virtual void SetupContext(URLRequestContext* context) {
8258 context->set_ssl_config_service(
8259 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208260 true /* online revocation checking */,
8261 false /* require rev. checking for local
8262 anchors */));
[email protected]a13234c2012-03-20 21:45:028263 }
8264
[email protected]dffe8242012-03-20 15:14:278265 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098266 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088267 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278268};
8269
[email protected]a13234c2012-03-20 21:45:028270static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018271#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028272 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8273 // have that ability on other platforms.
8274 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8275#else
8276 return 0;
8277#endif
8278}
8279
[email protected]3a86a712013-07-30 07:16:208280// SystemSupportsHardFailRevocationChecking returns true iff the current
8281// operating system supports revocation checking and can distinguish between
8282// situations where a given certificate lacks any revocation information (eg:
8283// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8284// revocation information cannot be obtained (eg: the CRL was unreachable).
8285// If it does not, then tests which rely on 'hard fail' behaviour should be
8286// skipped.
8287static bool SystemSupportsHardFailRevocationChecking() {
8288#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8289 return true;
8290#else
8291 return false;
8292#endif
8293}
8294
[email protected]a13234c2012-03-20 21:45:028295// SystemUsesChromiumEVMetadata returns true iff the current operating system
8296// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8297// several tests are effected because our testing EV certificate won't be
8298// recognised as EV.
8299static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328300#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578301 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8302 return false;
[email protected]e1b2d732014-03-28 16:20:328303#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8304 // On OS X and Android, we use the system to tell us whether a certificate is
8305 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018306 return false;
8307#else
8308 return true;
8309#endif
8310}
8311
[email protected]b6f2de32012-08-17 04:35:088312static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:578313#if defined(USE_OPENSSL)
8314 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8315 return false;
8316#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028317 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8318#elif defined(OS_ANDROID)
8319 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8320 return false;
8321#else
8322 return true;
8323#endif
8324}
8325
[email protected]dffe8242012-03-20 15:14:278326TEST_F(HTTPSOCSPTest, Valid) {
8327 if (!SystemSupportsOCSP()) {
8328 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8329 return;
8330 }
8331
[email protected]ce7d0cbc2013-05-03 18:57:228332 SpawnedTestServer::SSLOptions ssl_options(
8333 SpawnedTestServer::SSLOptions::CERT_AUTO);
8334 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278335
[email protected]924e9f92012-12-16 22:00:538336 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128337 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278338
8339 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8340
[email protected]a13234c2012-03-20 21:45:028341 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8342 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278343
8344 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8345}
8346
8347TEST_F(HTTPSOCSPTest, Revoked) {
8348 if (!SystemSupportsOCSP()) {
8349 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8350 return;
8351 }
8352
[email protected]ce7d0cbc2013-05-03 18:57:228353 SpawnedTestServer::SSLOptions ssl_options(
8354 SpawnedTestServer::SSLOptions::CERT_AUTO);
8355 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278356
8357 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128358 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278359
[email protected]a592c0432012-12-01 18:10:298360#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278361 // Doesn't pass on OS X yet for reasons that need to be investigated.
8362 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8363#endif
8364 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8365 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8366}
8367
8368TEST_F(HTTPSOCSPTest, Invalid) {
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]dffe8242012-03-20 15:14:278377
[email protected]924e9f92012-12-16 22:00:538378 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128379 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278380
[email protected]a13234c2012-03-20 21:45:028381 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278382 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278383
8384 // Without a positive OCSP response, we shouldn't show the EV status.
8385 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8386 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8387}
[email protected]a13234c2012-03-20 21:45:028388
[email protected]3a86a712013-07-30 07:16:208389class HTTPSHardFailTest : public HTTPSOCSPTest {
8390 protected:
dchengb03027d2014-10-21 12:00:208391 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208392 context->set_ssl_config_service(
8393 new TestSSLConfigService(false /* check for EV */,
8394 false /* online revocation checking */,
8395 true /* require rev. checking for local
8396 anchors */));
8397 }
8398};
8399
8400
8401TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8402 if (!SystemSupportsOCSP()) {
8403 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8404 return;
8405 }
8406
8407 if (!SystemSupportsHardFailRevocationChecking()) {
8408 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8409 << "revocation checking";
8410 return;
8411 }
8412
8413 SpawnedTestServer::SSLOptions ssl_options(
8414 SpawnedTestServer::SSLOptions::CERT_AUTO);
8415 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8416
8417 CertStatus cert_status;
8418 DoConnection(ssl_options, &cert_status);
8419
8420 EXPECT_EQ(CERT_STATUS_REVOKED,
8421 cert_status & CERT_STATUS_REVOKED);
8422
8423 // Without a positive OCSP response, we shouldn't show the EV status.
8424 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8425}
8426
[email protected]a13234c2012-03-20 21:45:028427class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8428 protected:
dchengb03027d2014-10-21 12:00:208429 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028430 context->set_ssl_config_service(
8431 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208432 false /* online revocation checking */,
8433 false /* require rev. checking for local
8434 anchors */));
[email protected]a13234c2012-03-20 21:45:028435 }
8436};
8437
8438TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8439 if (!SystemSupportsOCSP()) {
8440 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8441 return;
8442 }
8443
[email protected]ce7d0cbc2013-05-03 18:57:228444 SpawnedTestServer::SSLOptions ssl_options(
8445 SpawnedTestServer::SSLOptions::CERT_AUTO);
8446 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028447 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8448
[email protected]924e9f92012-12-16 22:00:538449 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128450 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028451
8452 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8453 cert_status & CERT_STATUS_ALL_ERRORS);
8454
8455 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088456 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8457 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028458}
8459
[email protected]be0fff62013-08-29 23:37:488460TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8461 if (!SystemSupportsOCSP()) {
8462 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8463 return;
8464 }
8465
8466 SpawnedTestServer::SSLOptions ssl_options(
8467 SpawnedTestServer::SSLOptions::CERT_AUTO);
8468 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8469 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8470
8471 CertStatus cert_status;
8472 DoConnection(ssl_options, &cert_status);
8473
8474 // Currently only works for Windows. When using NSS or OS X, it's not
8475 // possible to determine whether the check failed because of actual
8476 // revocation or because there was an OCSP failure.
8477#if defined(OS_WIN)
8478 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8479#else
8480 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8481#endif
8482
8483 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8484 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8485 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8486}
8487
[email protected]a13234c2012-03-20 21:45:028488TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8489 if (!SystemSupportsOCSP()) {
8490 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8491 return;
8492 }
8493
[email protected]ce7d0cbc2013-05-03 18:57:228494 SpawnedTestServer::SSLOptions ssl_options(
8495 SpawnedTestServer::SSLOptions::CERT_AUTO);
8496 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028497 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8498
8499 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128500 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028501
8502 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8503
8504 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8505 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088506 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8507 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028508}
8509
8510TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8511 if (!SystemSupportsOCSP()) {
8512 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8513 return;
8514 }
8515
[email protected]ce7d0cbc2013-05-03 18:57:228516 SpawnedTestServer::SSLOptions ssl_options(
8517 SpawnedTestServer::SSLOptions::CERT_AUTO);
8518 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028519 SSLConfigService::SetCRLSet(
8520 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8521
8522 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128523 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028524
8525 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8526 cert_status & CERT_STATUS_ALL_ERRORS);
8527
8528 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088529 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8530 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028531}
8532
[email protected]51523f52013-07-31 21:57:288533TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8534 if (!SystemSupportsOCSP()) {
8535 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8536 return;
8537 }
8538
8539 SpawnedTestServer::SSLOptions ssl_options(
8540 SpawnedTestServer::SSLOptions::CERT_AUTO);
8541 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8542 SSLConfigService::SetCRLSet(
8543 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8544 false, &kOCSPTestCertSPKI, "")));
8545
8546 CertStatus cert_status;
8547 DoConnection(ssl_options, &cert_status);
8548
8549 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8550 // revocation check for EV.
8551 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8552 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8553 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8554 EXPECT_FALSE(
8555 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8556}
8557
8558TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8559 if (!SystemSupportsOCSP()) {
8560 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8561 return;
8562 }
8563
[email protected]ce7d0cbc2013-05-03 18:57:228564 SpawnedTestServer::SSLOptions ssl_options(
8565 SpawnedTestServer::SSLOptions::CERT_AUTO);
8566 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028567 SSLConfigService::SetCRLSet(
8568 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8569
[email protected]51523f52013-07-31 21:57:288570 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128571 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028572
[email protected]51523f52013-07-31 21:57:288573 // Even with a fresh CRLSet, we should still do online revocation checks when
8574 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8575 // test.
8576 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8577 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028578
[email protected]51523f52013-07-31 21:57:288579 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028580 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288581 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028582}
8583
[email protected]b6f2de32012-08-17 04:35:088584TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8585 // Test that when EV verification is requested, but online revocation
8586 // checking is disabled, and the leaf certificate is not in fact EV, that
8587 // no revocation checking actually happens.
8588 if (!SystemSupportsOCSP()) {
8589 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8590 return;
8591 }
8592
8593 // Unmark the certificate's OID as EV, which should disable revocation
8594 // checking (as per the user preference)
8595 ev_test_policy_.reset();
8596
[email protected]ce7d0cbc2013-05-03 18:57:228597 SpawnedTestServer::SSLOptions ssl_options(
8598 SpawnedTestServer::SSLOptions::CERT_AUTO);
8599 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088600 SSLConfigService::SetCRLSet(
8601 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8602
8603 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128604 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088605
8606 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8607
8608 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8609 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8610}
8611
[email protected]a13234c2012-03-20 21:45:028612class HTTPSCRLSetTest : public HTTPSOCSPTest {
8613 protected:
dchengb03027d2014-10-21 12:00:208614 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028615 context->set_ssl_config_service(
8616 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208617 false /* online revocation checking */,
8618 false /* require rev. checking for local
8619 anchors */));
[email protected]a13234c2012-03-20 21:45:028620 }
8621};
8622
8623TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228624 SpawnedTestServer::SSLOptions ssl_options(
8625 SpawnedTestServer::SSLOptions::CERT_AUTO);
8626 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028627 SSLConfigService::SetCRLSet(
8628 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8629
[email protected]924e9f92012-12-16 22:00:538630 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128631 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028632
8633 // If we're not trying EV verification then, even if the CRLSet has expired,
8634 // we don't fall back to online revocation checks.
8635 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8636 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8637 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8638}
[email protected]51523f52013-07-31 21:57:288639
8640TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308641#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288642 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8643 return;
8644#endif
8645
8646 SpawnedTestServer::SSLOptions ssl_options(
8647 SpawnedTestServer::SSLOptions::CERT_AUTO);
8648 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8649 ssl_options.cert_serial = 10;
8650 SSLConfigService::SetCRLSet(
8651 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8652 false, &kOCSPTestCertSPKI, "\x0a")));
8653
8654 CertStatus cert_status = 0;
8655 DoConnection(ssl_options, &cert_status);
8656
8657 // If the certificate is recorded as revoked in the CRLSet, that should be
8658 // reflected without online revocation checking.
8659 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8660 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8661 EXPECT_FALSE(
8662 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8663}
[email protected]316c1e5e2012-09-12 15:17:448664#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278665
[email protected]316c1e5e2012-09-12 15:17:448666#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318667class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118668 public:
[email protected]d9fca99a2012-02-24 16:16:208669 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228670 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158671 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118672 }
8673
[email protected]b89ca032009-08-31 21:41:318674 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228675 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318676};
8677
[email protected]d2a133182012-08-05 16:44:088678// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098679TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088680 ASSERT_TRUE(test_server_.Start());
8681
[email protected]9d5730b2012-08-24 17:42:498682 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348683 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088684
8685 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088686 job_factory.SetProtocolHandler(
8687 "ftp",
[email protected]e0f35c92013-05-08 16:04:348688 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088689 default_context_.set_job_factory(&job_factory);
8690
8691 TestDelegate d;
8692 {
[email protected]f7022f32014-08-21 16:32:198693 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8694 url, DEFAULT_PRIORITY, &d, NULL));
8695 r->Start();
8696 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088697
[email protected]255620da2013-08-19 13:14:298698 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088699
[email protected]f7022f32014-08-21 16:32:198700 EXPECT_FALSE(r->is_pending());
8701 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8702 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088703 }
8704}
8705
[email protected]5accf7332009-11-24 03:41:388706// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128707TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118708 ASSERT_TRUE(test_server_.Start());
8709
[email protected]a25e90e2009-09-09 17:05:378710 TestDelegate d;
8711 {
[email protected]f7022f32014-08-21 16:32:198712 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8713 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, NULL));
8714 r->Start();
8715 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378716
[email protected]255620da2013-08-19 13:14:298717 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378718
[email protected]f7022f32014-08-21 16:32:198719 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378720 EXPECT_EQ(1, d.response_started_count());
8721 EXPECT_FALSE(d.received_data_before_response());
8722 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198723 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198724 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198725 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198726 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378727 }
8728}
8729
[email protected]7df70012010-02-04 00:09:558730// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128731TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118732 ASSERT_TRUE(test_server_.Start());
8733
[email protected]6cdfd7f2013-02-08 20:40:158734 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278735 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028736 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278737 TestDelegate d;
8738 {
[email protected]f7022f32014-08-21 16:32:198739 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8740 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d, NULL));
8741 r->Start();
8742 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278743
[email protected]255620da2013-08-19 13:14:298744 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278745
8746 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498747 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278748
[email protected]f7022f32014-08-21 16:32:198749 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278750 EXPECT_EQ(1, d.response_started_count());
8751 EXPECT_FALSE(d.received_data_before_response());
8752 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198753 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198754 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198755 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198756 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278757 }
8758}
8759
[email protected]e9ecbd12009-12-20 18:44:408760// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128761TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118762 ASSERT_TRUE(test_server_.Start());
8763
[email protected]6cdfd7f2013-02-08 20:40:158764 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278765 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028766 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278767 TestDelegate d;
8768 {
[email protected]f7022f32014-08-21 16:32:198769 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118770 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]f7022f32014-08-21 16:32:198771 DEFAULT_PRIORITY, &d, NULL));
8772 r->Start();
8773 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278774
[email protected]255620da2013-08-19 13:14:298775 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278776
8777 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498778 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278779
[email protected]f7022f32014-08-21 16:32:198780 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198781 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198782 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198783 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198784 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278785 EXPECT_EQ(1, d.response_started_count());
8786 EXPECT_FALSE(d.received_data_before_response());
8787 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258788
8789 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198790 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258791 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278792 }
8793}
8794
[email protected]49abd652010-08-05 05:04:538795// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128796TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118797 ASSERT_TRUE(test_server_.Start());
8798
[email protected]6cdfd7f2013-02-08 20:40:158799 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278800 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028801 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278802 TestDelegate d;
8803 {
[email protected]f7022f32014-08-21 16:32:198804 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8805 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8806 "wrong_password"),
8807 DEFAULT_PRIORITY, &d, NULL));
8808 r->Start();
8809 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278810
[email protected]255620da2013-08-19 13:14:298811 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278812
8813 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498814 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278815
[email protected]f7022f32014-08-21 16:32:198816 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278817 EXPECT_EQ(1, d.response_started_count());
8818 EXPECT_FALSE(d.received_data_before_response());
8819 EXPECT_EQ(d.bytes_received(), 0);
8820 }
8821}
8822
[email protected]cde4e80d2009-10-16 19:58:158823// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128824TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118825 ASSERT_TRUE(test_server_.Start());
8826
[email protected]6cdfd7f2013-02-08 20:40:158827 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588828 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8829 app_path = app_path.AppendASCII("LICENSE");
8830 TestDelegate d;
8831 // Set correct login credentials. The delegate will be asked for them when
8832 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588833 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588834 {
[email protected]f7022f32014-08-21 16:32:198835 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8836 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8837 "wrong_password"),
8838 DEFAULT_PRIORITY, &d, NULL));
8839 r->Start();
8840 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588841
[email protected]255620da2013-08-19 13:14:298842 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588843
8844 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498845 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588846
[email protected]f7022f32014-08-21 16:32:198847 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588848 EXPECT_EQ(1, d.response_started_count());
8849 EXPECT_FALSE(d.received_data_before_response());
8850 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8851 }
8852}
8853
[email protected]49abd652010-08-05 05:04:538854// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128855TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:118856 ASSERT_TRUE(test_server_.Start());
8857
[email protected]6cdfd7f2013-02-08 20:40:158858 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278859 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028860 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278861 TestDelegate d;
8862 {
[email protected]f7022f32014-08-21 16:32:198863 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8864 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8865 "chrome"),
8866 DEFAULT_PRIORITY, &d, NULL));
8867 r->Start();
8868 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278869
[email protected]255620da2013-08-19 13:14:298870 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278871
8872 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498873 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278874
[email protected]f7022f32014-08-21 16:32:198875 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278876 EXPECT_EQ(1, d.response_started_count());
8877 EXPECT_FALSE(d.received_data_before_response());
8878 EXPECT_EQ(d.bytes_received(), 0);
8879 }
8880}
[email protected]8b8a197d2009-08-26 15:57:588881
[email protected]cde4e80d2009-10-16 19:58:158882// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128883TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:118884 ASSERT_TRUE(test_server_.Start());
8885
[email protected]6cdfd7f2013-02-08 20:40:158886 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588887 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8888 app_path = app_path.AppendASCII("LICENSE");
8889 TestDelegate d;
8890 // Set correct login credentials. The delegate will be asked for them when
8891 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588892 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588893 {
[email protected]f7022f32014-08-21 16:32:198894 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8895 test_server_.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8896 "chrome"),
8897 DEFAULT_PRIORITY, &d, NULL));
8898 r->Start();
8899 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588900
[email protected]255620da2013-08-19 13:14:298901 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588902
8903 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498904 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588905
[email protected]f7022f32014-08-21 16:32:198906 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588907 EXPECT_EQ(1, d.response_started_count());
8908 EXPECT_FALSE(d.received_data_before_response());
8909 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8910 }
8911}
[email protected]60a3df52009-09-22 16:13:248912
[email protected]cde4e80d2009-10-16 19:58:158913// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128914TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:118915 ASSERT_TRUE(test_server_.Start());
8916
[email protected]6cdfd7f2013-02-08 20:40:158917 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248918 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8919 app_path = app_path.AppendASCII("LICENSE");
8920
8921 scoped_ptr<TestDelegate> d(new TestDelegate);
8922 {
8923 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:198924 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:198925 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]f7022f32014-08-21 16:32:198926 DEFAULT_PRIORITY, d.get(), NULL));
8927 r->Start();
8928 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248929
[email protected]255620da2013-08-19 13:14:298930 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248931
8932 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498933 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248934
[email protected]f7022f32014-08-21 16:32:198935 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248936 EXPECT_EQ(1, d->response_started_count());
8937 EXPECT_FALSE(d->received_data_before_response());
8938 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8939 }
8940
8941 d.reset(new TestDelegate);
8942 {
8943 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:198944 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8945 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
8946 r->Start();
8947 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248948
[email protected]255620da2013-08-19 13:14:298949 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248950
8951 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498952 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248953
[email protected]f7022f32014-08-21 16:32:198954 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248955 EXPECT_EQ(1, d->response_started_count());
8956 EXPECT_FALSE(d->received_data_before_response());
8957 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8958 }
8959}
8960
[email protected]cde4e80d2009-10-16 19:58:158961// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128962TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:118963 ASSERT_TRUE(test_server_.Start());
8964
[email protected]6cdfd7f2013-02-08 20:40:158965 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248966 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8967 app_path = app_path.AppendASCII("LICENSE");
8968
8969 scoped_ptr<TestDelegate> d(new TestDelegate);
8970 // Set correct login credentials. The delegate will be asked for them when
8971 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588972 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:248973 {
[email protected]f7022f32014-08-21 16:32:198974 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8975 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8976 "wrong_password"),
8977 DEFAULT_PRIORITY, d.get(), NULL));
8978 r->Start();
8979 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248980
[email protected]255620da2013-08-19 13:14:298981 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248982
8983 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498984 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248985
[email protected]f7022f32014-08-21 16:32:198986 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248987 EXPECT_EQ(1, d->response_started_count());
8988 EXPECT_FALSE(d->received_data_before_response());
8989 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8990 }
8991
8992 // Use a new delegate without explicit credentials. The cached ones should be
8993 // used.
8994 d.reset(new TestDelegate);
8995 {
8996 // Don't pass wrong credentials in the URL, they would override valid cached
8997 // ones.
[email protected]f7022f32014-08-21 16:32:198998 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8999 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get(), NULL));
9000 r->Start();
9001 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249002
[email protected]255620da2013-08-19 13:14:299003 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:249004
9005 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:499006 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:249007
[email protected]f7022f32014-08-21 16:32:199008 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:249009 EXPECT_EQ(1, d->response_started_count());
9010 EXPECT_FALSE(d->received_data_before_response());
9011 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
9012 }
9013}
[email protected]316c1e5e2012-09-12 15:17:449014#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:519015
9016} // namespace net