blob: ebf033d41eb614b317db71179316a753fad37b54 [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>
initial.commit586acc5fe2008-07-26 22:42:5213
[email protected]aad63572011-05-24 20:14:3914#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3815#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5816#include "base/compiler_specific.h"
thestigd8df0332014-09-04 06:33:2917#include "base/files/file_util.h"
[email protected]3ca8b362013-11-11 22:18:0718#include "base/files/scoped_temp_dir.h"
[email protected]34b2b002009-11-20 06:53:2819#include "base/format_macros.h"
mmenke19378d22014-09-09 04:12:5920#include "base/memory/scoped_ptr.h"
[email protected]084262c2011-12-01 21:12:4721#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2222#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2923#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5224#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2925#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5026#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5527#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2228#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2229#include "base/strings/string_util.h"
30#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0531#include "base/strings/utf_string_conversions.h"
[email protected]58e32bb2013-01-21 18:23:2532#include "net/base/capturing_net_log.h"
mmenkecbc2b712014-10-09 20:29:0733#include "net/base/chunked_upload_data_stream.h"
34#include "net/base/elements_upload_data_stream.h"
initial.commit586acc5fe2008-07-26 22:42:5235#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2536#include "net/base/load_timing_info.h"
37#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0638#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5339#include "net/base/net_log.h"
40#include "net/base/net_log_unittest.h"
initial.commit586acc5fe2008-07-26 22:42:5241#include "net/base/net_module.h"
42#include "net/base/net_util.h"
[email protected]2ca01e52013-10-31 22:05:1943#include "net/base/request_priority.h"
[email protected]42fdb452012-11-01 12:44:4044#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2845#include "net/base/upload_bytes_element_reader.h"
46#include "net/base/upload_data_stream.h"
47#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1148#include "net/cert/ev_root_ca_metadata.h"
[email protected]a8fed1742013-12-27 02:14:2449#include "net/cert/mock_cert_verifier.h"
[email protected]6e7845ae2013-03-29 21:48:1150#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0651#include "net/cookies/cookie_monster.h"
52#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5253#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5354#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4255#include "net/ftp/ftp_network_layer.h"
[email protected]b7572ea2013-11-26 20:16:3856#include "net/http/http_byte_range.h"
initial.commit586acc5fe2008-07-26 22:42:5257#include "net/http/http_cache.h"
58#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1959#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2560#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2161#include "net/http/http_response_headers.h"
[email protected]e50efea2014-03-24 18:41:0062#include "net/http/http_util.h"
[email protected]dffe8242012-03-20 15:14:2763#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2764#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1965#include "net/socket/ssl_client_socket.h"
davidben8ecc3072014-09-03 23:19:0966#include "net/ssl/ssl_cipher_suite_names.h"
[email protected]536fd0b2013-03-14 17:41:5767#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1168#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2169#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3470#include "net/url_request/data_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4371#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5272#include "net/url_request/url_request.h"
[email protected]bcb84f8b2009-08-31 16:20:1473#include "net/url_request/url_request_http_job.h"
bengr1bf8e942014-11-07 01:36:5074#include "net/url_request/url_request_intercepting_job_factory.h"
75#include "net/url_request/url_request_interceptor.h"
[email protected]9d5730b2012-08-24 17:42:4976#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5177#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4778#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4479#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5280#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1581#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5282
[email protected]02494ec2014-05-07 15:05:2983#if !defined(DISABLE_FILE_SUPPORT)
[email protected]5ecf7cb282014-05-11 01:49:5584#include "net/base/filename_util.h"
[email protected]02494ec2014-05-07 15:05:2985#include "net/url_request/file_protocol_handler.h"
86#include "net/url_request/url_request_file_dir_job.h"
87#endif
88
89#if !defined(DISABLE_FTP_SUPPORT)
90#include "net/url_request/ftp_protocol_handler.h"
91#endif
92
[email protected]dffe8242012-03-20 15:14:2793#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4894#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5695#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2796#include "base/win/windows_version.h"
97#endif
98
[email protected]ad65a3e2013-12-25 18:18:0199using base::ASCIIToUTF16;
[email protected]e1acf6f2008-10-27 20:43:33100using base::Time;
halton.huoe4e45742014-12-08 07:55:46101using std::string;
[email protected]e1acf6f2008-10-27 20:43:33102
[email protected]7461a402011-03-24 23:19:51103namespace net {
104
initial.commit586acc5fe2008-07-26 22:42:52105namespace {
106
[email protected]42cba2fb2013-03-29 19:58:57107const base::string16 kChrome(ASCIIToUTF16("chrome"));
108const base::string16 kSecret(ASCIIToUTF16("secret"));
109const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:44110
[email protected]2bba3252013-04-08 19:50:59111// Tests load timing information in the case a fresh connection was used, with
112// no proxy.
[email protected]cba24642014-08-15 20:49:59113void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
[email protected]58e32bb2013-01-21 18:23:25114 int connect_timing_flags) {
115 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59116 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25117
118 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
119 EXPECT_FALSE(load_timing_info.request_start.is_null());
120
121 EXPECT_LE(load_timing_info.request_start,
122 load_timing_info.connect_timing.connect_start);
123 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
124 connect_timing_flags);
125 EXPECT_LE(load_timing_info.connect_timing.connect_end,
126 load_timing_info.send_start);
127 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
128 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
129
[email protected]58e32bb2013-01-21 18:23:25130 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
131 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
132}
133
[email protected]2bba3252013-04-08 19:50:59134// Same as above, but with proxy times.
135void TestLoadTimingNotReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59136 const LoadTimingInfo& load_timing_info,
[email protected]2bba3252013-04-08 19:50:59137 int connect_timing_flags) {
138 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59139 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59140
141 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
142 EXPECT_FALSE(load_timing_info.request_start.is_null());
143
144 EXPECT_LE(load_timing_info.request_start,
145 load_timing_info.proxy_resolve_start);
146 EXPECT_LE(load_timing_info.proxy_resolve_start,
147 load_timing_info.proxy_resolve_end);
148 EXPECT_LE(load_timing_info.proxy_resolve_end,
149 load_timing_info.connect_timing.connect_start);
150 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
151 connect_timing_flags);
152 EXPECT_LE(load_timing_info.connect_timing.connect_end,
153 load_timing_info.send_start);
154 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
155 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
156}
157
158// Same as above, but with a reused socket and proxy times.
159void TestLoadTimingReusedWithProxy(
[email protected]cba24642014-08-15 20:49:59160 const LoadTimingInfo& load_timing_info) {
[email protected]2bba3252013-04-08 19:50:59161 EXPECT_TRUE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59162 EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]2bba3252013-04-08 19:50:59163
164 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
165 EXPECT_FALSE(load_timing_info.request_start.is_null());
166
167 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
168
169 EXPECT_LE(load_timing_info.request_start,
170 load_timing_info.proxy_resolve_start);
171 EXPECT_LE(load_timing_info.proxy_resolve_start,
172 load_timing_info.proxy_resolve_end);
173 EXPECT_LE(load_timing_info.proxy_resolve_end,
174 load_timing_info.send_start);
175 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
176 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
177}
178
[email protected]3b23a222013-05-15 21:33:25179// Tests load timing information in the case of a cache hit, when no cache
180// validation request was sent over the wire.
[email protected]e3a85452013-11-14 01:46:17181base::StringPiece TestNetResourceProvider(int key) {
182 return "header";
183}
184
185void FillBuffer(char* buffer, size_t len) {
186 static bool called = false;
187 if (!called) {
188 called = true;
189 int seed = static_cast<int>(Time::Now().ToInternalValue());
190 srand(seed);
191 }
192
193 for (size_t i = 0; i < len; i++) {
194 buffer[i] = static_cast<char>(rand());
195 if (!buffer[i])
196 buffer[i] = 'g';
197 }
198}
199
200#if !defined(OS_IOS)
[email protected]3b23a222013-05-15 21:33:25201void TestLoadTimingCacheHitNoNetwork(
[email protected]cba24642014-08-15 20:49:59202 const LoadTimingInfo& load_timing_info) {
[email protected]3b23a222013-05-15 21:33:25203 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59204 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]3b23a222013-05-15 21:33:25205
206 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
207 EXPECT_FALSE(load_timing_info.request_start.is_null());
208
209 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
210 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
211 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
212 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
213
214 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
215 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
216}
217
218// Tests load timing in the case that there is no HTTP response. This can be
219// used to test in the case of errors or non-HTTP requests.
220void TestLoadTimingNoHttpResponse(
[email protected]cba24642014-08-15 20:49:59221 const LoadTimingInfo& load_timing_info) {
[email protected]58e32bb2013-01-21 18:23:25222 EXPECT_FALSE(load_timing_info.socket_reused);
[email protected]cba24642014-08-15 20:49:59223 EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
[email protected]58e32bb2013-01-21 18:23:25224
225 // Only the request times should be non-null.
226 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
227 EXPECT_FALSE(load_timing_info.request_start.is_null());
228
229 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
230
231 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
232 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
233 EXPECT_TRUE(load_timing_info.send_start.is_null());
234 EXPECT_TRUE(load_timing_info.send_end.is_null());
235 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
236}
237
[email protected]71c64f62008-11-15 04:36:51238// Do a case-insensitive search through |haystack| for |needle|.
239bool ContainsString(const std::string& haystack, const char* needle) {
240 std::string::const_iterator it =
241 std::search(haystack.begin(),
242 haystack.end(),
243 needle,
244 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35245 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51246 return it != haystack.end();
247}
248
mmenkecbc2b712014-10-09 20:29:07249scoped_ptr<UploadDataStream> CreateSimpleUploadData(const char* data) {
[email protected]f288ef02012-12-15 20:28:28250 scoped_ptr<UploadElementReader> reader(
251 new UploadBytesElementReader(data, strlen(data)));
mmenkecbc2b712014-10-09 20:29:07252 return ElementsUploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23253}
254
[email protected]96adadb2010-08-28 01:16:17255// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51256void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]96adadb2010-08-28 01:16:17257 // -1 means unknown. 0 means no encryption.
258 EXPECT_GT(ssl_info.security_bits, 0);
259
260 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
pkasting6b68a162014-12-01 22:10:29261 uint16 cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17262 ssl_info.connection_status);
pkasting6b68a162014-12-01 22:10:29263 EXPECT_NE(0U, cipher_suite);
[email protected]96adadb2010-08-28 01:16:17264}
265
[email protected]79e1fd62013-06-20 06:50:04266void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
267 const GURL& host_url) {
268 std::string sent_value;
269
270 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
271 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
272
273 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
274 EXPECT_EQ("keep-alive", sent_value);
275}
276
[email protected]ede03212012-09-07 12:52:26277bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27278 size_t size = a.size();
279
280 if (size != b.size())
281 return false;
282
283 for (size_t i = 0; i < size; ++i) {
284 if (!a[i].Equals(b[i]))
285 return false;
286 }
287
288 return true;
289}
[email protected]e3a85452013-11-14 01:46:17290#endif // !defined(OS_IOS)
[email protected]69d7ff442012-02-13 22:41:27291
[email protected]dc5a5cf2012-09-26 02:49:30292// A network delegate that allows the user to choose a subset of request stages
293// to block in. When blocking, the delegate can do one of the following:
294// * synchronously return a pre-specified error code, or
295// * asynchronously return that value via an automatically called callback,
296// or
297// * block and wait for the user to do a callback.
298// Additionally, the user may also specify a redirect URL -- then each request
299// with the current URL different from the redirect target will be redirected
300// to that target, in the on-before-URL-request stage, independent of whether
301// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12302class BlockingNetworkDelegate : public TestNetworkDelegate {
303 public:
[email protected]dc5a5cf2012-09-26 02:49:30304 // Stages in which the delegate can block.
305 enum Stage {
[email protected]9045b8822012-01-13 20:35:35306 NOT_BLOCKED = 0,
307 ON_BEFORE_URL_REQUEST = 1 << 0,
308 ON_BEFORE_SEND_HEADERS = 1 << 1,
309 ON_HEADERS_RECEIVED = 1 << 2,
310 ON_AUTH_REQUIRED = 1 << 3
311 };
312
[email protected]dc5a5cf2012-09-26 02:49:30313 // Behavior during blocked stages. During other stages, just
[email protected]cba24642014-08-15 20:49:59314 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
[email protected]dc5a5cf2012-09-26 02:49:30315 enum BlockMode {
316 SYNCHRONOUS, // No callback, returns specified return values.
317 AUTO_CALLBACK, // |this| posts a task to run the callback using the
318 // specified return codes.
319 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
320 // |auth_retval_| are ignored. In every blocking stage the
321 // message loop is quit.
322 };
323
324 // Creates a delegate which does not block at all.
325 explicit BlockingNetworkDelegate(BlockMode block_mode);
326
327 // For users to trigger a callback returning |response|.
328 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
329 // Only call if |block_mode_| == USER_CALLBACK.
330 void DoCallback(int response);
331 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
332
333 // Setters.
334 void set_retval(int retval) {
335 ASSERT_NE(USER_CALLBACK, block_mode_);
336 ASSERT_NE(ERR_IO_PENDING, retval);
337 ASSERT_NE(OK, retval);
338 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35339 }
340
[email protected]dc5a5cf2012-09-26 02:49:30341 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
342 // |auth_credentials_| will be passed with the response.
343 void set_auth_retval(AuthRequiredResponse auth_retval) {
344 ASSERT_NE(USER_CALLBACK, block_mode_);
345 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
346 auth_retval_ = auth_retval;
347 }
348 void set_auth_credentials(const AuthCredentials& auth_credentials) {
349 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35350 }
351
[email protected]dc5a5cf2012-09-26 02:49:30352 void set_redirect_url(const GURL& url) {
353 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35354 }
355
[email protected]dc5a5cf2012-09-26 02:49:30356 void set_block_on(int block_on) {
357 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35358 }
359
[email protected]dc5a5cf2012-09-26 02:49:30360 // Allows the user to check in which state did we block.
361 Stage stage_blocked_for_callback() const {
362 EXPECT_EQ(USER_CALLBACK, block_mode_);
363 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35364 }
365
366 private:
[email protected]dc5a5cf2012-09-26 02:49:30367 void RunCallback(int response, const CompletionCallback& callback);
368 void RunAuthCallback(AuthRequiredResponse response,
369 const AuthCallback& callback);
370
[email protected]9045b8822012-01-13 20:35:35371 // TestNetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:20372 int OnBeforeURLRequest(URLRequest* request,
373 const CompletionCallback& callback,
374 GURL* new_url) override;
[email protected]9045b8822012-01-13 20:35:35375
dchengb03027d2014-10-21 12:00:20376 int OnBeforeSendHeaders(URLRequest* request,
377 const CompletionCallback& callback,
378 HttpRequestHeaders* headers) override;
[email protected]9045b8822012-01-13 20:35:35379
dchengb03027d2014-10-21 12:00:20380 int OnHeadersReceived(
[email protected]9045b8822012-01-13 20:35:35381 URLRequest* request,
382 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32383 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16384 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:13385 GURL* allowed_unsafe_redirect_url) override;
[email protected]9045b8822012-01-13 20:35:35386
dchengb03027d2014-10-21 12:00:20387 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]9045b8822012-01-13 20:35:35388 URLRequest* request,
389 const AuthChallengeInfo& auth_info,
390 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:13391 AuthCredentials* credentials) override;
[email protected]9045b8822012-01-13 20:35:35392
[email protected]dc5a5cf2012-09-26 02:49:30393 // Resets the callbacks and |stage_blocked_for_callback_|.
394 void Reset();
[email protected]9045b8822012-01-13 20:35:35395
[email protected]dc5a5cf2012-09-26 02:49:30396 // Checks whether we should block in |stage|. If yes, returns an error code
397 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
398 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
399
400 // Configuration parameters, can be adjusted by public methods:
401 const BlockMode block_mode_;
402
403 // Values returned on blocking stages when mode is SYNCHRONOUS or
404 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
405 int retval_; // To be returned in non-auth stages.
406 AuthRequiredResponse auth_retval_;
407
[email protected]5f714132014-03-26 10:41:16408 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
[email protected]dc5a5cf2012-09-26 02:49:30409 int block_on_; // Bit mask: in which stages to block.
410
411 // |auth_credentials_| will be copied to |*target_auth_credential_| on
412 // callback.
413 AuthCredentials auth_credentials_;
414 AuthCredentials* target_auth_credentials_;
415
416 // Internal variables, not set by not the user:
417 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
418 // USER_CALLBACK).
419 Stage stage_blocked_for_callback_;
420
421 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35422 CompletionCallback callback_;
423 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30424
425 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
426
427 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35428};
429
[email protected]dc5a5cf2012-09-26 02:49:30430BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
431 : block_mode_(block_mode),
432 retval_(OK),
433 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
434 block_on_(0),
435 target_auth_credentials_(NULL),
436 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32437 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30438}
439
440void BlockingNetworkDelegate::DoCallback(int response) {
441 ASSERT_EQ(USER_CALLBACK, block_mode_);
442 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
443 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
444 CompletionCallback callback = callback_;
445 Reset();
446 RunCallback(response, callback);
447}
448
449void BlockingNetworkDelegate::DoAuthCallback(
450 NetworkDelegate::AuthRequiredResponse response) {
451 ASSERT_EQ(USER_CALLBACK, block_mode_);
452 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
453 AuthCallback auth_callback = auth_callback_;
454 Reset();
455 RunAuthCallback(response, auth_callback);
456}
457
458void BlockingNetworkDelegate::RunCallback(int response,
459 const CompletionCallback& callback) {
460 callback.Run(response);
461}
462
463void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
464 const AuthCallback& callback) {
465 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
466 ASSERT_TRUE(target_auth_credentials_ != NULL);
467 *target_auth_credentials_ = auth_credentials_;
468 }
469 callback.Run(response);
470}
471
472int BlockingNetworkDelegate::OnBeforeURLRequest(
473 URLRequest* request,
474 const CompletionCallback& callback,
475 GURL* new_url) {
476 if (redirect_url_ == request->url())
477 return OK; // We've already seen this request and redirected elsewhere.
478
479 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
480
481 if (!redirect_url_.is_empty())
482 *new_url = redirect_url_;
483
484 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
485}
486
487int BlockingNetworkDelegate::OnBeforeSendHeaders(
488 URLRequest* request,
489 const CompletionCallback& callback,
490 HttpRequestHeaders* headers) {
491 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
492
493 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
494}
495
496int BlockingNetworkDelegate::OnHeadersReceived(
497 URLRequest* request,
498 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32499 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:16500 scoped_refptr<HttpResponseHeaders>* override_response_headers,
501 GURL* allowed_unsafe_redirect_url) {
502 TestNetworkDelegate::OnHeadersReceived(request,
503 callback,
504 original_response_headers,
505 override_response_headers,
506 allowed_unsafe_redirect_url);
[email protected]dc5a5cf2012-09-26 02:49:30507
508 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
509}
510
511NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
512 URLRequest* request,
513 const AuthChallengeInfo& auth_info,
514 const AuthCallback& callback,
515 AuthCredentials* credentials) {
516 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
517 credentials);
518 // Check that the user has provided callback for the previous blocked stage.
519 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
520
521 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
522 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
523 }
524
525 target_auth_credentials_ = credentials;
526
527 switch (block_mode_) {
528 case SYNCHRONOUS:
529 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
530 *target_auth_credentials_ = auth_credentials_;
531 return auth_retval_;
532
533 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34534 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30535 FROM_HERE,
536 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
537 weak_factory_.GetWeakPtr(), auth_retval_, callback));
538 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
539
540 case USER_CALLBACK:
541 auth_callback_ = callback;
542 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34543 base::MessageLoop::current()->PostTask(FROM_HERE,
544 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30545 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
546 }
547 NOTREACHED();
548 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
549}
550
551void BlockingNetworkDelegate::Reset() {
552 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
553 stage_blocked_for_callback_ = NOT_BLOCKED;
554 callback_.Reset();
555 auth_callback_.Reset();
556}
557
558int BlockingNetworkDelegate::MaybeBlockStage(
559 BlockingNetworkDelegate::Stage stage,
560 const CompletionCallback& callback) {
561 // Check that the user has provided callback for the previous blocked stage.
562 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
563
564 if ((block_on_ & stage) == 0) {
565 return OK;
566 }
567
568 switch (block_mode_) {
569 case SYNCHRONOUS:
570 EXPECT_NE(OK, retval_);
571 return retval_;
572
573 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34574 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30575 FROM_HERE,
576 base::Bind(&BlockingNetworkDelegate::RunCallback,
577 weak_factory_.GetWeakPtr(), retval_, callback));
578 return ERR_IO_PENDING;
579
580 case USER_CALLBACK:
581 callback_ = callback;
582 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34583 base::MessageLoop::current()->PostTask(FROM_HERE,
584 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30585 return ERR_IO_PENDING;
586 }
587 NOTREACHED();
588 return 0;
589}
590
[email protected]d5a4dd62012-05-23 01:41:04591class TestURLRequestContextWithProxy : public TestURLRequestContext {
592 public:
593 // Does not own |delegate|.
594 TestURLRequestContextWithProxy(const std::string& proxy,
595 NetworkDelegate* delegate)
596 : TestURLRequestContext(true) {
597 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
598 set_network_delegate(delegate);
599 Init();
600 }
dchengb03027d2014-10-21 12:00:20601 ~TestURLRequestContextWithProxy() override {}
[email protected]d5a4dd62012-05-23 01:41:04602};
603
604} // namespace
605
[email protected]a592c0432012-12-01 18:10:29606// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48607class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00608 public:
[email protected]ef2bf422012-05-11 03:27:09609 URLRequestTest() : default_context_(true) {
610 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25611 default_context_.set_net_log(&net_log_);
bengr1bf8e942014-11-07 01:36:50612 job_factory_impl_ = new URLRequestJobFactoryImpl();
613 job_factory_.reset(job_factory_impl_);
[email protected]87a09a92011-07-14 15:50:50614 }
bengr1bf8e942014-11-07 01:36:50615
dcheng67be2b1f2014-10-27 21:47:29616 ~URLRequestTest() override {
[email protected]e4034ad2013-09-20 08:36:18617 // URLRequestJobs may post clean-up tasks on destruction.
618 base::RunLoop().RunUntilIdle();
619 }
[email protected]87a09a92011-07-14 15:50:50620
dcheng2339883c2014-12-23 00:23:05621 void SetUp() override {
bengr1bf8e942014-11-07 01:36:50622 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(
davidben151423e2015-03-23 18:48:36665 GURL("about:blank"), DEFAULT_PRIORITY, &d));
[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(
davidben151423e2015-03-23 18:48:36689 "data:image/png;base64,"
690 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUB"
691 "BjG3w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQ"
692 "xIEVxitD5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI"
693 "5MpCVdW0gO7tvNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKz"
694 "Mx1+fg9bAgK6zHq9cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7Ck"
695 "IMDxQpF7r/MWq12UctI1dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0"
696 "WYUqt57yWf2McHTObYPbVD+ZwbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2H"
697 "QQcm43XwmtoYM6vVKleh0uoWvnzW3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nk"
698 "DFHF9ZS+uYVjRUasMeHUmyLYtcklTvzWGFZnNOXczThvpKIzjcahSqIzkvDLayDq6"
699 "D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTbxXX1T5xsV9tm9r4TQwHLiZw/pdDZJ"
700 "ea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5MrVvMzNaI3+ERHfrFzPKQukrQ"
701 "GI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gVMd6q5c8GdosynKmSeRuGz"
702 "pjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq/uxxZKzNiZFGD0wRC"
703 "3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7FUx1qLnV7MGF40"
704 "smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufBJbsysjjW4"
705 "kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJMnlm2O"
706 "34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfmm"
707 "oRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV"
708 "5EnhORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
709 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44710
[email protected]f7022f32014-08-21 16:32:19711 r->Start();
712 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44713
[email protected]255620da2013-08-19 13:14:29714 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44715
[email protected]f7022f32014-08-21 16:32:19716 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44717 EXPECT_FALSE(d.received_data_before_response());
718 EXPECT_EQ(d.bytes_received(), 911);
[email protected]f7022f32014-08-21 16:32:19719 EXPECT_EQ("", r->GetSocketAddress().host());
720 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04721
722 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19723 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44724 }
725}
726
[email protected]5ecf7cb282014-05-11 01:49:55727#if !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:44728TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15729 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44730 PathService::Get(base::FILE_EXE, &app_path);
731 GURL app_url = FilePathToFileURL(app_path);
732
733 TestDelegate d;
734 {
davidben151423e2015-03-23 18:48:36735 scoped_ptr<URLRequest> r(
736 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44737
[email protected]f7022f32014-08-21 16:32:19738 r->Start();
739 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44740
[email protected]255620da2013-08-19 13:14:29741 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44742
743 int64 file_size = -1;
[email protected]56285702013-12-04 18:22:49744 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44745
[email protected]f7022f32014-08-21 16:32:19746 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44747 EXPECT_EQ(1, d.response_started_count());
748 EXPECT_FALSE(d.received_data_before_response());
749 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]f7022f32014-08-21 16:32:19750 EXPECT_EQ("", r->GetSocketAddress().host());
751 EXPECT_EQ(0, r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04752
753 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:19754 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44755 }
756}
757
[email protected]ba40bb762012-12-17 07:11:04758TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15759 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04760 PathService::Get(base::FILE_EXE, &app_path);
761 GURL app_url = FilePathToFileURL(app_path);
762
763 TestDelegate d;
764 {
davidben151423e2015-03-23 18:48:36765 scoped_ptr<URLRequest> r(
766 default_context_.CreateRequest(app_url, DEFAULT_PRIORITY, &d));
[email protected]ba40bb762012-12-17 07:11:04767
[email protected]f7022f32014-08-21 16:32:19768 r->Start();
769 EXPECT_TRUE(r->is_pending());
770 r->Cancel();
[email protected]ba40bb762012-12-17 07:11:04771 }
[email protected]79e1fd62013-06-20 06:50:04772 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04773 // destroyed.
[email protected]255620da2013-08-19 13:14:29774 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04775}
776
[email protected]316c1e5e2012-09-12 15:17:44777TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
778 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17779 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44780 FillBuffer(buffer.get(), buffer_size);
781
[email protected]6cdfd7f2013-02-08 20:40:15782 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52783 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44784 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30785 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44786
787 int64 file_size;
[email protected]56285702013-12-04 18:22:49788 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44789
790 const size_t first_byte_position = 500;
791 const size_t last_byte_position = buffer_size - first_byte_position;
792 const size_t content_length = last_byte_position - first_byte_position + 1;
793 std::string partial_buffer_string(buffer.get() + first_byte_position,
794 buffer.get() + last_byte_position + 1);
795
796 TestDelegate d;
797 {
davidben151423e2015-03-23 18:48:36798 scoped_ptr<URLRequest> r(
799 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44800
801 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38802 headers.SetHeader(
803 HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59804 HttpByteRange::Bounded(
[email protected]b7572ea2013-11-26 20:16:38805 first_byte_position, last_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19806 r->SetExtraRequestHeaders(headers);
807 r->Start();
808 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44809
[email protected]255620da2013-08-19 13:14:29810 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19811 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44812 EXPECT_EQ(1, d.response_started_count());
813 EXPECT_FALSE(d.received_data_before_response());
814 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
815 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
816 EXPECT_TRUE(partial_buffer_string == d.data_received());
817 }
818
[email protected]dd3aa792013-07-16 19:10:23819 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44820}
821
822TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
823 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17824 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44825 FillBuffer(buffer.get(), buffer_size);
826
[email protected]6cdfd7f2013-02-08 20:40:15827 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52828 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44829 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30830 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44831
832 int64 file_size;
[email protected]56285702013-12-04 18:22:49833 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44834
835 const size_t first_byte_position = 500;
836 const size_t last_byte_position = buffer_size - 1;
837 const size_t content_length = last_byte_position - first_byte_position + 1;
838 std::string partial_buffer_string(buffer.get() + first_byte_position,
839 buffer.get() + last_byte_position + 1);
840
841 TestDelegate d;
842 {
davidben151423e2015-03-23 18:48:36843 scoped_ptr<URLRequest> r(
844 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44845
846 HttpRequestHeaders headers;
847 headers.SetHeader(HttpRequestHeaders::kRange,
[email protected]cba24642014-08-15 20:49:59848 HttpByteRange::RightUnbounded(
[email protected]b7572ea2013-11-26 20:16:38849 first_byte_position).GetHeaderValue());
[email protected]f7022f32014-08-21 16:32:19850 r->SetExtraRequestHeaders(headers);
851 r->Start();
852 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44853
[email protected]255620da2013-08-19 13:14:29854 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:19855 EXPECT_TRUE(!r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44856 EXPECT_EQ(1, d.response_started_count());
857 EXPECT_FALSE(d.received_data_before_response());
858 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
859 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
860 EXPECT_TRUE(partial_buffer_string == d.data_received());
861 }
862
[email protected]dd3aa792013-07-16 19:10:23863 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44864}
865
866TEST_F(URLRequestTest, FileTestMultipleRanges) {
867 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17868 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44869 FillBuffer(buffer.get(), buffer_size);
870
[email protected]6cdfd7f2013-02-08 20:40:15871 base::FilePath temp_path;
[email protected]03d9afc02013-12-03 17:55:52872 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
[email protected]316c1e5e2012-09-12 15:17:44873 GURL temp_url = FilePathToFileURL(temp_path);
[email protected]e5c2a22e2014-03-06 20:42:30874 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
[email protected]316c1e5e2012-09-12 15:17:44875
876 int64 file_size;
[email protected]56285702013-12-04 18:22:49877 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
[email protected]316c1e5e2012-09-12 15:17:44878
879 TestDelegate d;
880 {
davidben151423e2015-03-23 18:48:36881 scoped_ptr<URLRequest> r(
882 default_context_.CreateRequest(temp_url, DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:44883
884 HttpRequestHeaders headers;
[email protected]b7572ea2013-11-26 20:16:38885 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
[email protected]f7022f32014-08-21 16:32:19886 r->SetExtraRequestHeaders(headers);
887 r->Start();
888 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44889
[email protected]255620da2013-08-19 13:14:29890 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44891 EXPECT_TRUE(d.request_failed());
892 }
893
[email protected]dd3aa792013-07-16 19:10:23894 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44895}
896
[email protected]3ca8b362013-11-11 22:18:07897TEST_F(URLRequestTest, AllowFileURLs) {
898 base::ScopedTempDir temp_dir;
899 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
900 base::FilePath test_file;
[email protected]03d9afc02013-12-03 17:55:52901 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
[email protected]3ca8b362013-11-11 22:18:07902 std::string test_data("monkey");
[email protected]e5c2a22e2014-03-06 20:42:30903 base::WriteFile(test_file, test_data.data(), test_data.size());
[email protected]cba24642014-08-15 20:49:59904 GURL test_file_url = FilePathToFileURL(test_file);
[email protected]3ca8b362013-11-11 22:18:07905
906 {
907 TestDelegate d;
908 TestNetworkDelegate network_delegate;
909 network_delegate.set_can_access_files(true);
910 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36911 scoped_ptr<URLRequest> r(
912 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19913 r->Start();
[email protected]3ca8b362013-11-11 22:18:07914 base::RunLoop().Run();
915 EXPECT_FALSE(d.request_failed());
916 EXPECT_EQ(test_data, d.data_received());
917 }
918
919 {
920 TestDelegate d;
921 TestNetworkDelegate network_delegate;
922 network_delegate.set_can_access_files(false);
923 default_context_.set_network_delegate(&network_delegate);
davidben151423e2015-03-23 18:48:36924 scoped_ptr<URLRequest> r(
925 default_context_.CreateRequest(test_file_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19926 r->Start();
[email protected]3ca8b362013-11-11 22:18:07927 base::RunLoop().Run();
928 EXPECT_TRUE(d.request_failed());
929 EXPECT_EQ("", d.data_received());
930 }
931}
932
[email protected]316c1e5e2012-09-12 15:17:44933
934TEST_F(URLRequestTest, FileDirCancelTest) {
935 // Put in mock resource provider.
936 NetModule::SetResourceProvider(TestNetResourceProvider);
937
938 TestDelegate d;
939 {
[email protected]6cdfd7f2013-02-08 20:40:15940 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44941 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
942 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
943 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
944
[email protected]f7022f32014-08-21 16:32:19945 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36946 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19947 req->Start();
948 EXPECT_TRUE(req->is_pending());
[email protected]316c1e5e2012-09-12 15:17:44949
950 d.set_cancel_in_received_data_pending(true);
951
[email protected]255620da2013-08-19 13:14:29952 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44953 }
954
955 // Take out mock resource provider.
956 NetModule::SetResourceProvider(NULL);
957}
958
[email protected]5f9581402013-10-30 13:08:32959TEST_F(URLRequestTest, FileDirOutputSanity) {
960 // Verify the general sanity of the the output of the file:
961 // directory lister by checking for the output of a known existing
962 // file.
963 const char sentinel_name[] = "filedir-sentinel";
964
965 base::FilePath path;
966 PathService::Get(base::DIR_SOURCE_ROOT, &path);
967 path = path.Append(FILE_PATH_LITERAL("net"));
968 path = path.Append(FILE_PATH_LITERAL("data"));
969 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
970
971 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:19972 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:36973 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:19974 req->Start();
[email protected]5f9581402013-10-30 13:08:32975 base::RunLoop().Run();
976
977 // Generate entry for the sentinel file.
978 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
[email protected]54124ed02014-01-07 10:06:58979 base::File::Info info;
[email protected]9eae4e62013-12-04 20:56:49980 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
[email protected]5f9581402013-10-30 13:08:32981 EXPECT_GT(info.size, 0);
982 std::string sentinel_output = GetDirectoryListingEntry(
983 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
984 std::string(sentinel_name),
985 false /* is_dir */,
986 info.size,
987 info.last_modified);
988
989 ASSERT_LT(0, d.bytes_received());
990 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:19991 ASSERT_TRUE(req->status().is_success());
[email protected]5f9581402013-10-30 13:08:32992 // Check for the entry generated for the "sentinel" file.
993 const std::string& data = d.data_received();
994 ASSERT_NE(data.find(sentinel_output), std::string::npos);
995}
996
[email protected]316c1e5e2012-09-12 15:17:44997TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
998 // There is an implicit redirect when loading a file path that matches a
999 // directory and does not end with a slash. Ensure that following such
1000 // redirects does not crash. See http://crbug.com/18686.
1001
[email protected]6cdfd7f2013-02-08 20:40:151002 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:441003 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1004 path = path.Append(FILE_PATH_LITERAL("net"));
1005 path = path.Append(FILE_PATH_LITERAL("data"));
1006 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1007
1008 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:191009 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361010 FilePathToFileURL(path), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191011 req->Start();
[email protected]255620da2013-08-19 13:14:291012 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441013
1014 ASSERT_EQ(1, d.received_redirect_count());
1015 ASSERT_LT(0, d.bytes_received());
1016 ASSERT_FALSE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:191017 ASSERT_TRUE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441018}
1019
1020#if defined(OS_WIN)
1021// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1022TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1023 TestDelegate d;
davidben151423e2015-03-23 18:48:361024 scoped_ptr<URLRequest> req(
1025 default_context_.CreateRequest(GURL("file:///"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:191026 req->Start();
[email protected]255620da2013-08-19 13:14:291027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441028
1029 ASSERT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:191030 ASSERT_FALSE(req->status().is_success());
[email protected]316c1e5e2012-09-12 15:17:441031}
[email protected]5ecf7cb282014-05-11 01:49:551032#endif // defined(OS_WIN)
1033
1034#endif // !defined(DISABLE_FILE_SUPPORT)
1035
1036TEST_F(URLRequestTest, InvalidUrlTest) {
1037 TestDelegate d;
1038 {
[email protected]f7022f32014-08-21 16:32:191039 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361040 GURL("invalid url"), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551041
[email protected]f7022f32014-08-21 16:32:191042 r->Start();
1043 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551044
1045 base::RunLoop().Run();
1046 EXPECT_TRUE(d.request_failed());
1047 }
1048}
1049
jochen0e3b3a62014-09-16 18:31:231050TEST_F(URLRequestTest, InvalidReferrerTest) {
1051 TestURLRequestContext context;
1052 TestNetworkDelegate network_delegate;
1053 network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1054 context.set_network_delegate(&network_delegate);
1055 TestDelegate d;
davidben151423e2015-03-23 18:48:361056 scoped_ptr<URLRequest> req(
1057 context.CreateRequest(GURL("http://localhost/"), DEFAULT_PRIORITY, &d));
jochen0e3b3a62014-09-16 18:31:231058 req->SetReferrer("https://somewhere.com/");
1059
1060 req->Start();
1061 base::RunLoop().Run();
1062 EXPECT_TRUE(d.request_failed());
1063}
1064
[email protected]5ecf7cb282014-05-11 01:49:551065#if defined(OS_WIN)
1066TEST_F(URLRequestTest, ResolveShortcutTest) {
1067 base::FilePath app_path;
1068 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1069 app_path = app_path.AppendASCII("net");
1070 app_path = app_path.AppendASCII("data");
1071 app_path = app_path.AppendASCII("url_request_unittest");
1072 app_path = app_path.AppendASCII("with-headers.html");
1073
1074 std::wstring lnk_path = app_path.value() + L".lnk";
1075
1076 base::win::ScopedCOMInitializer com_initializer;
1077
1078 // Temporarily create a shortcut for test
1079 {
1080 base::win::ScopedComPtr<IShellLink> shell;
1081 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1082 CLSCTX_INPROC_SERVER)));
1083 base::win::ScopedComPtr<IPersistFile> persist;
1084 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1085 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1086 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1087 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1088 }
1089
1090 TestDelegate d;
1091 {
[email protected]f7022f32014-08-21 16:32:191092 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:361093 FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d));
[email protected]5ecf7cb282014-05-11 01:49:551094
[email protected]f7022f32014-08-21 16:32:191095 r->Start();
1096 EXPECT_TRUE(r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551097
1098 base::RunLoop().Run();
1099
1100 WIN32_FILE_ATTRIBUTE_DATA data;
1101 GetFileAttributesEx(app_path.value().c_str(),
1102 GetFileExInfoStandard, &data);
1103 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1104 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1105 FILE_ATTRIBUTE_NORMAL, NULL);
1106 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1107 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1108 DWORD read_size;
1109 BOOL result;
1110 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1111 &read_size, NULL);
1112 std::string content(buffer.get(), read_size);
1113 CloseHandle(file);
1114
[email protected]f7022f32014-08-21 16:32:191115 EXPECT_TRUE(!r->is_pending());
[email protected]5ecf7cb282014-05-11 01:49:551116 EXPECT_EQ(1, d.received_redirect_count());
1117 EXPECT_EQ(content, d.data_received());
1118 }
1119
1120 // Clean the shortcut
1121 DeleteFile(lnk_path.c_str());
1122}
1123#endif // defined(OS_WIN)
[email protected]316c1e5e2012-09-12 15:17:441124
1125// Custom URLRequestJobs for use with interceptor tests
1126class RestartTestJob : public URLRequestTestJob {
1127 public:
1128 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1129 : URLRequestTestJob(request, network_delegate, true) {}
1130 protected:
dchengb03027d2014-10-21 12:00:201131 void StartAsync() override { this->NotifyRestartRequired(); }
[email protected]316c1e5e2012-09-12 15:17:441132 private:
dchengb03027d2014-10-21 12:00:201133 ~RestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441134};
1135
1136class CancelTestJob : public URLRequestTestJob {
1137 public:
1138 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1139 : URLRequestTestJob(request, network_delegate, true) {}
1140 protected:
dchengb03027d2014-10-21 12:00:201141 void StartAsync() override { request_->Cancel(); }
[email protected]316c1e5e2012-09-12 15:17:441142 private:
dchengb03027d2014-10-21 12:00:201143 ~CancelTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441144};
1145
1146class CancelThenRestartTestJob : public URLRequestTestJob {
1147 public:
1148 explicit CancelThenRestartTestJob(URLRequest* request,
1149 NetworkDelegate* network_delegate)
1150 : URLRequestTestJob(request, network_delegate, true) {
1151 }
1152 protected:
dchengb03027d2014-10-21 12:00:201153 void StartAsync() override {
[email protected]316c1e5e2012-09-12 15:17:441154 request_->Cancel();
1155 this->NotifyRestartRequired();
1156 }
1157 private:
dchengb03027d2014-10-21 12:00:201158 ~CancelThenRestartTestJob() override {}
[email protected]316c1e5e2012-09-12 15:17:441159};
1160
bengr1bf8e942014-11-07 01:36:501161// An Interceptor for use with interceptor tests.
1162class MockURLRequestInterceptor : public URLRequestInterceptor {
1163 public:
1164 // Static getters for canned response header and data strings.
1165 static std::string ok_data() {
1166 return URLRequestTestJob::test_data_1();
1167 }
1168
1169 static std::string ok_headers() {
1170 return URLRequestTestJob::test_headers();
1171 }
1172
1173 static std::string redirect_data() {
1174 return std::string();
1175 }
1176
1177 static std::string redirect_headers() {
1178 return URLRequestTestJob::test_redirect_headers();
1179 }
1180
1181 static std::string error_data() {
1182 return std::string("ohhh nooooo mr. bill!");
1183 }
1184
1185 static std::string error_headers() {
1186 return URLRequestTestJob::test_error_headers();
1187 }
1188
1189 MockURLRequestInterceptor()
1190 : intercept_main_request_(false), restart_main_request_(false),
1191 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1192 simulate_main_network_error_(false),
1193 intercept_redirect_(false), cancel_redirect_request_(false),
1194 intercept_final_response_(false), cancel_final_request_(false),
1195 use_url_request_http_job_(false),
1196 did_intercept_main_(false), did_restart_main_(false),
1197 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1198 did_simulate_error_main_(false),
1199 did_intercept_redirect_(false), did_cancel_redirect_(false),
1200 did_intercept_final_(false), did_cancel_final_(false) {
1201 }
1202
1203 ~MockURLRequestInterceptor() override {
1204 }
1205
1206 // URLRequestInterceptor implementation:
1207 URLRequestJob* MaybeInterceptRequest(
1208 URLRequest* request,
1209 NetworkDelegate* network_delegate) const override {
1210 if (restart_main_request_) {
1211 restart_main_request_ = false;
1212 did_restart_main_ = true;
1213 return new RestartTestJob(request, network_delegate);
1214 }
1215 if (cancel_main_request_) {
1216 cancel_main_request_ = false;
1217 did_cancel_main_ = true;
1218 return new CancelTestJob(request, network_delegate);
1219 }
1220 if (cancel_then_restart_main_request_) {
1221 cancel_then_restart_main_request_ = false;
1222 did_cancel_then_restart_main_ = true;
1223 return new CancelThenRestartTestJob(request, network_delegate);
1224 }
1225 if (simulate_main_network_error_) {
1226 simulate_main_network_error_ = false;
1227 did_simulate_error_main_ = true;
1228 if (use_url_request_http_job_) {
1229 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1230 }
1231 // This job will result in error since the requested URL is not one of the
1232 // URLs supported by these tests.
1233 return new URLRequestTestJob(request, network_delegate, true);
1234 }
1235 if (!intercept_main_request_)
1236 return nullptr;
1237 intercept_main_request_ = false;
1238 did_intercept_main_ = true;
1239 URLRequestTestJob* job = new URLRequestTestJob(request,
1240 network_delegate,
1241 main_headers_,
1242 main_data_,
1243 true);
1244 job->set_load_timing_info(main_request_load_timing_info_);
1245 return job;
1246 }
1247
1248 URLRequestJob* MaybeInterceptRedirect(URLRequest* request,
1249 NetworkDelegate* network_delegate,
1250 const GURL& location) const override {
1251 if (cancel_redirect_request_) {
1252 cancel_redirect_request_ = false;
1253 did_cancel_redirect_ = true;
1254 return new CancelTestJob(request, network_delegate);
1255 }
1256 if (!intercept_redirect_)
1257 return nullptr;
1258 intercept_redirect_ = false;
1259 did_intercept_redirect_ = true;
1260 if (use_url_request_http_job_) {
1261 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1262 }
1263 return new URLRequestTestJob(request,
1264 network_delegate,
1265 redirect_headers_,
1266 redirect_data_,
1267 true);
1268 }
1269
1270 URLRequestJob* MaybeInterceptResponse(
1271 URLRequest* request,
1272 NetworkDelegate* network_delegate) const override {
1273 if (cancel_final_request_) {
1274 cancel_final_request_ = false;
1275 did_cancel_final_ = true;
1276 return new CancelTestJob(request, network_delegate);
1277 }
1278 if (!intercept_final_response_)
1279 return nullptr;
1280 intercept_final_response_ = false;
1281 did_intercept_final_ = true;
1282 if (use_url_request_http_job_) {
1283 return URLRequestHttpJob::Factory(request, network_delegate, "http");
1284 }
1285 return new URLRequestTestJob(request,
1286 network_delegate,
1287 final_headers_,
1288 final_data_,
1289 true);
1290 }
1291
1292 void set_intercept_main_request(bool intercept_main_request) {
1293 intercept_main_request_ = intercept_main_request;
1294 }
1295
1296 void set_main_headers(const std::string& main_headers) {
1297 main_headers_ = main_headers;
1298 }
1299
1300 void set_main_data(const std::string& main_data) {
1301 main_data_ = main_data;
1302 }
1303
1304 void set_main_request_load_timing_info(
1305 const LoadTimingInfo& main_request_load_timing_info) {
1306 main_request_load_timing_info_ = main_request_load_timing_info;
1307 }
1308
1309 void set_restart_main_request(bool restart_main_request) {
1310 restart_main_request_ = restart_main_request;
1311 }
1312
1313 void set_cancel_main_request(bool cancel_main_request) {
1314 cancel_main_request_ = cancel_main_request;
1315 }
1316
1317 void set_cancel_then_restart_main_request(
1318 bool cancel_then_restart_main_request) {
1319 cancel_then_restart_main_request_ = cancel_then_restart_main_request;
1320 }
1321
1322 void set_simulate_main_network_error(bool simulate_main_network_error) {
1323 simulate_main_network_error_ = simulate_main_network_error;
1324 }
1325
1326 void set_intercept_redirect(bool intercept_redirect) {
1327 intercept_redirect_ = intercept_redirect;
1328 }
1329
1330 void set_redirect_headers(const std::string& redirect_headers) {
1331 redirect_headers_ = redirect_headers;
1332 }
1333
1334 void set_redirect_data(const std::string& redirect_data) {
1335 redirect_data_ = redirect_data;
1336 }
1337
1338 void set_cancel_redirect_request(bool cancel_redirect_request) {
1339 cancel_redirect_request_ = cancel_redirect_request;
1340 }
1341
1342 void set_intercept_final_response(bool intercept_final_response) {
1343 intercept_final_response_ = intercept_final_response;
1344 }
1345
1346 void set_final_headers(const std::string& final_headers) {
1347 final_headers_ = final_headers;
1348 }
1349
1350 void set_final_data(const std::string& final_data) {
1351 final_data_ = final_data;
1352 }
1353
1354 void set_cancel_final_request(bool cancel_final_request) {
1355 cancel_final_request_ = cancel_final_request;
1356 }
1357
1358 void set_use_url_request_http_job(bool use_url_request_http_job) {
1359 use_url_request_http_job_ = use_url_request_http_job;
1360 }
1361
1362 bool did_intercept_main() const {
1363 return did_intercept_main_;
1364 }
1365
1366 bool did_restart_main() const {
1367 return did_restart_main_;
1368 }
1369
1370 bool did_cancel_main() const {
1371 return did_cancel_main_;
1372 }
1373
1374 bool did_cancel_then_restart_main() const {
1375 return did_cancel_then_restart_main_;
1376 }
1377
1378 bool did_simulate_error_main() const {
1379 return did_simulate_error_main_;
1380 }
1381
1382 bool did_intercept_redirect() const {
1383 return did_intercept_redirect_;
1384 }
1385
1386 bool did_cancel_redirect() const {
1387 return did_cancel_redirect_;
1388 }
1389
1390 bool did_intercept_final() const {
1391 return did_intercept_final_;
1392 }
1393
1394 bool did_cancel_final() const {
1395 return did_cancel_final_;
1396 }
1397
1398 private:
1399 // Indicate whether to intercept the main request, and if so specify the
1400 // response to return and the LoadTimingInfo to use.
1401 mutable bool intercept_main_request_;
1402 mutable std::string main_headers_;
1403 mutable std::string main_data_;
1404 mutable LoadTimingInfo main_request_load_timing_info_;
1405
1406 // These indicate actions that can be taken within MaybeInterceptRequest.
1407 mutable bool restart_main_request_;
1408 mutable bool cancel_main_request_;
1409 mutable bool cancel_then_restart_main_request_;
1410 mutable bool simulate_main_network_error_;
1411
1412 // Indicate whether to intercept redirects, and if so specify the response to
1413 // return.
1414 mutable bool intercept_redirect_;
1415 mutable std::string redirect_headers_;
1416 mutable std::string redirect_data_;
1417
1418 // Cancel the request within MaybeInterceptRedirect.
1419 mutable bool cancel_redirect_request_;
1420
1421 // Indicate whether to intercept the final response, and if so specify the
1422 // response to return.
1423 mutable bool intercept_final_response_;
1424 mutable std::string final_headers_;
1425 mutable std::string final_data_;
1426
1427 // Cancel the final request within MaybeInterceptResponse.
1428 mutable bool cancel_final_request_;
1429
1430 // Instruct the interceptor to use a real URLRequestHTTPJob.
1431 mutable bool use_url_request_http_job_;
1432
1433 // These indicate if the interceptor did something or not.
1434 mutable bool did_intercept_main_;
1435 mutable bool did_restart_main_;
1436 mutable bool did_cancel_main_;
1437 mutable bool did_cancel_then_restart_main_;
1438 mutable bool did_simulate_error_main_;
1439 mutable bool did_intercept_redirect_;
1440 mutable bool did_cancel_redirect_;
1441 mutable bool did_intercept_final_;
1442 mutable bool did_cancel_final_;
1443};
1444
1445// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
1446class URLRequestInterceptorTest : public URLRequestTest {
1447 public:
1448 URLRequestInterceptorTest() : URLRequestTest(), interceptor_(NULL) {
1449 }
1450
1451 ~URLRequestInterceptorTest() override {
1452 // URLRequestJobs may post clean-up tasks on destruction.
1453 base::RunLoop().RunUntilIdle();
1454 }
1455
1456 void SetUpFactory() override {
1457 interceptor_ = new MockURLRequestInterceptor();
1458 job_factory_.reset(new URLRequestInterceptingJobFactory(
1459 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
1460 }
1461
1462 MockURLRequestInterceptor* interceptor() const {
1463 return interceptor_;
1464 }
1465
1466 private:
1467 MockURLRequestInterceptor* interceptor_;
1468};
1469
1470TEST_F(URLRequestInterceptorTest, Intercept) {
1471 // Intercept the main request and respond with a simple response.
1472 interceptor()->set_intercept_main_request(true);
1473 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1474 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
[email protected]2bba3252013-04-08 19:50:591475 TestDelegate d;
bengr1bf8e942014-11-07 01:36:501476 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361477 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501478 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1479 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1480 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1481 req->SetUserData(nullptr, user_data0);
1482 req->SetUserData(&user_data1, user_data1);
1483 req->SetUserData(&user_data2, user_data2);
1484 req->set_method("GET");
[email protected]f7022f32014-08-21 16:32:191485 req->Start();
[email protected]255620da2013-08-19 13:14:291486 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591487
bengr1bf8e942014-11-07 01:36:501488 // Make sure we can retrieve our specific user data.
1489 EXPECT_EQ(user_data0, req->GetUserData(nullptr));
1490 EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1491 EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
[email protected]2bba3252013-04-08 19:50:591492
bengr1bf8e942014-11-07 01:36:501493 // Check that we got one good response.
1494 EXPECT_TRUE(req->status().is_success());
1495 EXPECT_EQ(200, req->response_headers()->response_code());
1496 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1497 EXPECT_EQ(1, d.response_started_count());
1498 EXPECT_EQ(0, d.received_redirect_count());
1499}
[email protected]2bba3252013-04-08 19:50:591500
bengr1bf8e942014-11-07 01:36:501501TEST_F(URLRequestInterceptorTest, InterceptRedirect) {
1502 // Intercept the main request and respond with a redirect.
1503 interceptor()->set_intercept_main_request(true);
1504 interceptor()->set_main_headers(
1505 MockURLRequestInterceptor::redirect_headers());
1506 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1507
1508 // Intercept that redirect and respond with a final OK response.
1509 interceptor()->set_intercept_redirect(true);
1510 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
1511 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
1512
1513 TestDelegate d;
1514 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361515 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501516 req->set_method("GET");
1517 req->Start();
1518 base::RunLoop().Run();
1519
1520 // Check that the interceptor got called as expected.
1521 EXPECT_TRUE(interceptor()->did_intercept_main());
1522 EXPECT_TRUE(interceptor()->did_intercept_redirect());
1523
1524 // Check that we got one good response.
1525 EXPECT_TRUE(req->status().is_success());
1526 if (req->status().is_success())
1527 EXPECT_EQ(200, req->response_headers()->response_code());
1528
1529 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1530 EXPECT_EQ(1, d.response_started_count());
1531 EXPECT_EQ(0, d.received_redirect_count());
1532}
1533
1534TEST_F(URLRequestInterceptorTest, InterceptServerError) {
1535 // Intercept the main request to generate a server error response.
1536 interceptor()->set_intercept_main_request(true);
1537 interceptor()->set_main_headers(MockURLRequestInterceptor::error_headers());
1538 interceptor()->set_main_data(MockURLRequestInterceptor::error_data());
1539
1540 // Intercept that error and respond with an OK response.
1541 interceptor()->set_intercept_final_response(true);
1542 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1543 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1544
1545 TestDelegate d;
1546 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361547 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501548 req->set_method("GET");
1549 req->Start();
1550 base::RunLoop().Run();
1551
1552 // Check that the interceptor got called as expected.
1553 EXPECT_TRUE(interceptor()->did_intercept_main());
1554 EXPECT_TRUE(interceptor()->did_intercept_final());
1555
1556 // Check that we got one good response.
1557 EXPECT_TRUE(req->status().is_success());
1558 EXPECT_EQ(200, req->response_headers()->response_code());
1559 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1560 EXPECT_EQ(1, d.response_started_count());
1561 EXPECT_EQ(0, d.received_redirect_count());
1562}
1563
1564TEST_F(URLRequestInterceptorTest, InterceptNetworkError) {
1565 // Intercept the main request to simulate a network error.
1566 interceptor()->set_simulate_main_network_error(true);
1567
1568 // Intercept that error and respond with an OK response.
1569 interceptor()->set_intercept_final_response(true);
1570 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1571 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1572
1573 TestDelegate d;
1574 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361575 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501576 req->set_method("GET");
1577 req->Start();
1578 base::RunLoop().Run();
1579
1580 // Check that the interceptor got called as expected.
1581 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1582 EXPECT_TRUE(interceptor()->did_intercept_final());
1583
1584 // Check that we received one good response.
1585 EXPECT_TRUE(req->status().is_success());
1586 EXPECT_EQ(200, req->response_headers()->response_code());
1587 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1588 EXPECT_EQ(1, d.response_started_count());
1589 EXPECT_EQ(0, d.received_redirect_count());
1590}
1591
1592TEST_F(URLRequestInterceptorTest, InterceptRestartRequired) {
1593 // Restart the main request.
1594 interceptor()->set_restart_main_request(true);
1595
1596 // then intercept the new main request and respond with an OK response
1597 interceptor()->set_intercept_main_request(true);
1598 interceptor()->set_main_headers(MockURLRequestInterceptor::ok_headers());
1599 interceptor()->set_main_data(MockURLRequestInterceptor::ok_data());
1600
1601 TestDelegate d;
1602 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361603 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501604 req->set_method("GET");
1605 req->Start();
1606 base::RunLoop().Run();
1607
1608 // Check that the interceptor got called as expected.
1609 EXPECT_TRUE(interceptor()->did_restart_main());
1610 EXPECT_TRUE(interceptor()->did_intercept_main());
1611
1612 // Check that we received one good response.
1613 EXPECT_TRUE(req->status().is_success());
1614 if (req->status().is_success())
1615 EXPECT_EQ(200, req->response_headers()->response_code());
1616
1617 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
1618 EXPECT_EQ(1, d.response_started_count());
1619 EXPECT_EQ(0, d.received_redirect_count());
1620}
1621
1622TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelMain) {
1623 // Intercept the main request and cancel from within the restarted job.
1624 interceptor()->set_cancel_main_request(true);
1625
1626 // Set up to intercept the final response and override it with an OK response.
1627 interceptor()->set_intercept_final_response(true);
1628 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1629 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1630
1631 TestDelegate d;
1632 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361633 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501634 req->set_method("GET");
1635 req->Start();
1636 base::RunLoop().Run();
1637
1638 // Check that the interceptor got called as expected.
1639 EXPECT_TRUE(interceptor()->did_cancel_main());
1640 EXPECT_FALSE(interceptor()->did_intercept_final());
1641
1642 // Check that we see a canceled request.
1643 EXPECT_FALSE(req->status().is_success());
1644 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1645}
1646
1647TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelRedirect) {
1648 // Intercept the main request and respond with a redirect.
1649 interceptor()->set_intercept_main_request(true);
1650 interceptor()->set_main_headers(
1651 MockURLRequestInterceptor::redirect_headers());
1652 interceptor()->set_main_data(MockURLRequestInterceptor::redirect_data());
1653
1654 // Intercept the redirect and cancel from within that job.
1655 interceptor()->set_cancel_redirect_request(true);
1656
1657 // Set up to intercept the final response and override it with an OK response.
1658 interceptor()->set_intercept_final_response(true);
1659 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1660 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
1661
1662 TestDelegate d;
1663 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361664 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501665 req->set_method("GET");
1666 req->Start();
1667 base::RunLoop().Run();
1668
1669 // Check that the interceptor got called as expected.
1670 EXPECT_TRUE(interceptor()->did_intercept_main());
1671 EXPECT_TRUE(interceptor()->did_cancel_redirect());
1672 EXPECT_FALSE(interceptor()->did_intercept_final());
1673
1674 // Check that we see a canceled request.
1675 EXPECT_FALSE(req->status().is_success());
1676 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1677}
1678
1679TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelFinal) {
1680 // Intercept the main request to simulate a network error.
1681 interceptor()->set_simulate_main_network_error(true);
1682
1683 // Set up to intercept final the response and cancel from within that job.
1684 interceptor()->set_cancel_final_request(true);
1685
1686 TestDelegate d;
1687 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361688 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501689 req->set_method("GET");
1690 req->Start();
1691 base::RunLoop().Run();
1692
1693 // Check that the interceptor got called as expected.
1694 EXPECT_TRUE(interceptor()->did_simulate_error_main());
1695 EXPECT_TRUE(interceptor()->did_cancel_final());
1696
1697 // Check that we see a canceled request.
1698 EXPECT_FALSE(req->status().is_success());
1699 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1700}
1701
1702TEST_F(URLRequestInterceptorTest, InterceptRespectsCancelInRestart) {
1703 // Intercept the main request and cancel then restart from within that job.
1704 interceptor()->set_cancel_then_restart_main_request(true);
1705
1706 // Set up to intercept the final response and override it with an OK response.
1707 interceptor()->set_intercept_final_response(true);
bengrb50d631e2014-11-17 22:50:501708 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
1709 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
bengr1bf8e942014-11-07 01:36:501710
1711 TestDelegate d;
1712 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:361713 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501714 req->set_method("GET");
1715 req->Start();
1716 base::RunLoop().Run();
1717
1718 // Check that the interceptor got called as expected.
1719 EXPECT_TRUE(interceptor()->did_cancel_then_restart_main());
1720 EXPECT_FALSE(interceptor()->did_intercept_final());
1721
1722 // Check that we see a canceled request.
1723 EXPECT_FALSE(req->status().is_success());
1724 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]2bba3252013-04-08 19:50:591725}
1726
1727// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1728// reused. |connect_time_flags| is used to indicate if there should be dns
1729// or SSL times, and |used_proxy| is used for proxy times.
1730LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1731 int connect_time_flags,
1732 bool used_proxy) {
1733 LoadTimingInfo load_timing;
1734 load_timing.socket_log_id = 1;
1735
1736 if (used_proxy) {
1737 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1738 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1739 }
1740
1741 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1742 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1743 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1744 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1745 }
1746 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1747 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1748 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1749 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1750 }
1751 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1752
1753 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1754 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1755 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1756 return load_timing;
1757}
1758
1759// Same as above, but in the case of a reused socket.
1760LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1761 bool used_proxy) {
1762 LoadTimingInfo load_timing;
1763 load_timing.socket_log_id = 1;
1764 load_timing.socket_reused = true;
1765
1766 if (used_proxy) {
1767 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1768 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1769 }
1770
1771 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1772 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1773 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1774 return load_timing;
1775}
1776
bengr1bf8e942014-11-07 01:36:501777LoadTimingInfo RunURLRequestInterceptorLoadTimingTest(
1778 const LoadTimingInfo& job_load_timing,
1779 const URLRequestContext& context,
1780 MockURLRequestInterceptor* interceptor) {
1781 interceptor->set_intercept_main_request(true);
1782 interceptor->set_main_request_load_timing_info(job_load_timing);
1783 TestDelegate d;
1784 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:361785 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:501786 req->Start();
1787 base::RunLoop().Run();
1788
1789 LoadTimingInfo resulting_load_timing;
1790 req->GetLoadTimingInfo(&resulting_load_timing);
1791
1792 // None of these should be modified by the URLRequest.
1793 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1794 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1795 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1796 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1797 EXPECT_EQ(job_load_timing.receive_headers_end,
1798 resulting_load_timing.receive_headers_end);
1799
1800 return resulting_load_timing;
1801}
1802
[email protected]2bba3252013-04-08 19:50:591803// Basic test that the intercept + load timing tests work.
bengr1bf8e942014-11-07 01:36:501804TEST_F(URLRequestInterceptorTest, InterceptLoadTiming) {
[email protected]2bba3252013-04-08 19:50:591805 base::TimeTicks now = base::TimeTicks::Now();
1806 LoadTimingInfo job_load_timing =
1807 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1808
[email protected]2ca01e52013-10-31 22:05:191809 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501810 RunURLRequestInterceptorLoadTimingTest(
1811 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591812
1813 // Nothing should have been changed by the URLRequest.
1814 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1815 load_timing_result.proxy_resolve_start);
1816 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1817 load_timing_result.proxy_resolve_end);
1818 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1819 load_timing_result.connect_timing.dns_start);
1820 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1821 load_timing_result.connect_timing.dns_end);
1822 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1823 load_timing_result.connect_timing.connect_start);
1824 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1825 load_timing_result.connect_timing.connect_end);
1826 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1827 load_timing_result.connect_timing.ssl_start);
1828 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1829 load_timing_result.connect_timing.ssl_end);
1830
1831 // Redundant sanity check.
1832 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1833}
1834
1835// Another basic test, with proxy and SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501836TEST_F(URLRequestInterceptorTest, InterceptLoadTimingProxy) {
[email protected]2bba3252013-04-08 19:50:591837 base::TimeTicks now = base::TimeTicks::Now();
1838 LoadTimingInfo job_load_timing =
1839 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1840
[email protected]2ca01e52013-10-31 22:05:191841 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501842 RunURLRequestInterceptorLoadTimingTest(
1843 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591844
1845 // Nothing should have been changed by the URLRequest.
1846 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1847 load_timing_result.proxy_resolve_start);
1848 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1849 load_timing_result.proxy_resolve_end);
1850 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1851 load_timing_result.connect_timing.dns_start);
1852 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1853 load_timing_result.connect_timing.dns_end);
1854 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1855 load_timing_result.connect_timing.connect_start);
1856 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1857 load_timing_result.connect_timing.connect_end);
1858 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1859 load_timing_result.connect_timing.ssl_start);
1860 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1861 load_timing_result.connect_timing.ssl_end);
1862
1863 // Redundant sanity check.
1864 TestLoadTimingNotReusedWithProxy(load_timing_result,
1865 CONNECT_TIMING_HAS_SSL_TIMES);
1866}
1867
1868// Make sure that URLRequest correctly adjusts proxy times when they're before
1869// |request_start|, due to already having a connected socket. This happens in
[email protected]cf4cae32014-05-27 00:39:101870// the case of reusing a SPDY session. The connected socket is not considered
1871// reused in this test (May be a preconnect).
[email protected]2bba3252013-04-08 19:50:591872//
1873// To mix things up from the test above, assumes DNS times but no SSL times.
bengr1bf8e942014-11-07 01:36:501874TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyProxyResolution) {
[email protected]2bba3252013-04-08 19:50:591875 base::TimeTicks now = base::TimeTicks::Now();
1876 LoadTimingInfo job_load_timing =
1877 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1878 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1879 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1880 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1881 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1882 job_load_timing.connect_timing.connect_start =
1883 now - base::TimeDelta::FromDays(2);
1884 job_load_timing.connect_timing.connect_end =
1885 now - base::TimeDelta::FromDays(1);
1886
[email protected]2ca01e52013-10-31 22:05:191887 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501888 RunURLRequestInterceptorLoadTimingTest(
1889 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591890
1891 // Proxy times, connect times, and DNS times should all be replaced with
1892 // request_start.
1893 EXPECT_EQ(load_timing_result.request_start,
1894 load_timing_result.proxy_resolve_start);
1895 EXPECT_EQ(load_timing_result.request_start,
1896 load_timing_result.proxy_resolve_end);
1897 EXPECT_EQ(load_timing_result.request_start,
1898 load_timing_result.connect_timing.dns_start);
1899 EXPECT_EQ(load_timing_result.request_start,
1900 load_timing_result.connect_timing.dns_end);
1901 EXPECT_EQ(load_timing_result.request_start,
1902 load_timing_result.connect_timing.connect_start);
1903 EXPECT_EQ(load_timing_result.request_start,
1904 load_timing_result.connect_timing.connect_end);
1905
1906 // Other times should have been left null.
1907 TestLoadTimingNotReusedWithProxy(load_timing_result,
1908 CONNECT_TIMING_HAS_DNS_TIMES);
1909}
1910
1911// Same as above, but in the reused case.
bengr1bf8e942014-11-07 01:36:501912TEST_F(URLRequestInterceptorTest,
1913 InterceptLoadTimingEarlyProxyResolutionReused) {
[email protected]2bba3252013-04-08 19:50:591914 base::TimeTicks now = base::TimeTicks::Now();
1915 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1916 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1917 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1918
[email protected]2ca01e52013-10-31 22:05:191919 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501920 RunURLRequestInterceptorLoadTimingTest(
1921 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591922
1923 // Proxy times and connect times should all be replaced with request_start.
1924 EXPECT_EQ(load_timing_result.request_start,
1925 load_timing_result.proxy_resolve_start);
1926 EXPECT_EQ(load_timing_result.request_start,
1927 load_timing_result.proxy_resolve_end);
1928
1929 // Other times should have been left null.
1930 TestLoadTimingReusedWithProxy(load_timing_result);
1931}
1932
1933// Make sure that URLRequest correctly adjusts connect times when they're before
1934// |request_start|, due to reusing a connected socket. The connected socket is
1935// not considered reused in this test (May be a preconnect).
1936//
1937// To mix things up, the request has SSL times, but no DNS times.
bengr1bf8e942014-11-07 01:36:501938TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnect) {
[email protected]2bba3252013-04-08 19:50:591939 base::TimeTicks now = base::TimeTicks::Now();
1940 LoadTimingInfo job_load_timing =
1941 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1942 job_load_timing.connect_timing.connect_start =
1943 now - base::TimeDelta::FromDays(1);
1944 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1945 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1946 job_load_timing.connect_timing.connect_end =
1947 now - base::TimeDelta::FromDays(4);
1948
[email protected]2ca01e52013-10-31 22:05:191949 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501950 RunURLRequestInterceptorLoadTimingTest(
1951 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591952
1953 // Connect times, and SSL times should be replaced with request_start.
1954 EXPECT_EQ(load_timing_result.request_start,
1955 load_timing_result.connect_timing.connect_start);
1956 EXPECT_EQ(load_timing_result.request_start,
1957 load_timing_result.connect_timing.ssl_start);
1958 EXPECT_EQ(load_timing_result.request_start,
1959 load_timing_result.connect_timing.ssl_end);
1960 EXPECT_EQ(load_timing_result.request_start,
1961 load_timing_result.connect_timing.connect_end);
1962
1963 // Other times should have been left null.
1964 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1965}
1966
1967// Make sure that URLRequest correctly adjusts connect times when they're before
1968// |request_start|, due to reusing a connected socket in the case that there
1969// are also proxy times. The connected socket is not considered reused in this
1970// test (May be a preconnect).
1971//
1972// In this test, there are no SSL or DNS times.
bengr1bf8e942014-11-07 01:36:501973TEST_F(URLRequestInterceptorTest, InterceptLoadTimingEarlyConnectWithProxy) {
[email protected]2bba3252013-04-08 19:50:591974 base::TimeTicks now = base::TimeTicks::Now();
1975 LoadTimingInfo job_load_timing =
1976 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1977 job_load_timing.connect_timing.connect_start =
1978 now - base::TimeDelta::FromDays(1);
1979 job_load_timing.connect_timing.connect_end =
1980 now - base::TimeDelta::FromDays(2);
1981
[email protected]2ca01e52013-10-31 22:05:191982 LoadTimingInfo load_timing_result =
bengr1bf8e942014-11-07 01:36:501983 RunURLRequestInterceptorLoadTimingTest(
1984 job_load_timing, default_context(), interceptor());
[email protected]2bba3252013-04-08 19:50:591985
1986 // Connect times should be replaced with proxy_resolve_end.
1987 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1988 load_timing_result.connect_timing.connect_start);
1989 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1990 load_timing_result.connect_timing.connect_end);
1991
1992 // Other times should have been left null.
1993 TestLoadTimingNotReusedWithProxy(load_timing_result,
1994 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1995}
1996
[email protected]316c1e5e2012-09-12 15:17:441997// Check that two different URL requests have different identifiers.
1998TEST_F(URLRequestTest, Identifiers) {
1999 TestDelegate d;
2000 TestURLRequestContext context;
davidben151423e2015-03-23 18:48:362001 scoped_ptr<URLRequest> req(
2002 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
2003 scoped_ptr<URLRequest> other_req(
2004 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442005
mmenke19378d22014-09-09 04:12:592006 ASSERT_NE(req->identifier(), other_req->identifier());
[email protected]316c1e5e2012-09-12 15:17:442007}
2008
2009// Check that a failure to connect to the proxy is reported to the network
2010// delegate.
2011TEST_F(URLRequestTest, NetworkDelegateProxyError) {
2012 MockHostResolver host_resolver;
2013 host_resolver.rules()->AddSimulatedFailure("*");
2014
[email protected]ceefd7fd2012-11-29 00:36:242015 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:442016 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
2017
2018 TestDelegate d;
davidben151423e2015-03-23 18:48:362019 scoped_ptr<URLRequest> req(
2020 context.CreateRequest(GURL("http://example.com"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192021 req->set_method("GET");
[email protected]316c1e5e2012-09-12 15:17:442022
[email protected]f7022f32014-08-21 16:32:192023 req->Start();
[email protected]255620da2013-08-19 13:14:292024 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442025
2026 // Check we see a failed request.
[email protected]f7022f32014-08-21 16:32:192027 EXPECT_FALSE(req->status().is_success());
[email protected]d8fc4722014-06-13 13:17:152028 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192029 EXPECT_TRUE(req->proxy_server().IsEmpty());
2030 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
2031 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:442032
2033 EXPECT_EQ(1, network_delegate.error_count());
2034 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
2035 EXPECT_EQ(1, network_delegate.completed_requests());
2036}
2037
[email protected]cba24642014-08-15 20:49:592038// Make sure that NetworkDelegate::NotifyCompleted is called if
[email protected]316c1e5e2012-09-12 15:17:442039// content is empty.
2040TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
2041 TestDelegate d;
davidben151423e2015-03-23 18:48:362042 scoped_ptr<URLRequest> req(
2043 default_context_.CreateRequest(GURL("data:,"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192044 req->Start();
[email protected]255620da2013-08-19 13:14:292045 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442046 EXPECT_EQ("", d.data_received());
2047 EXPECT_EQ(1, default_network_delegate_.completed_requests());
2048}
2049
[email protected]5033ab82013-03-22 20:17:462050// Make sure that SetPriority actually sets the URLRequest's priority
2051// correctly, both before and after start.
2052TEST_F(URLRequestTest, SetPriorityBasic) {
2053 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192054 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362055 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192056 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462057
[email protected]f7022f32014-08-21 16:32:192058 req->SetPriority(LOW);
2059 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462060
[email protected]f7022f32014-08-21 16:32:192061 req->Start();
2062 EXPECT_EQ(LOW, req->priority());
[email protected]5033ab82013-03-22 20:17:462063
[email protected]f7022f32014-08-21 16:32:192064 req->SetPriority(MEDIUM);
2065 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462066}
2067
2068// Make sure that URLRequest calls SetPriority on a job before calling
2069// Start on it.
2070TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
2071 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192072 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362073 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192074 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:462075
2076 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192077 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502078 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462079 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
2080
[email protected]f7022f32014-08-21 16:32:192081 req->SetPriority(LOW);
[email protected]5033ab82013-03-22 20:17:462082
[email protected]f7022f32014-08-21 16:32:192083 req->Start();
[email protected]5033ab82013-03-22 20:17:462084 EXPECT_EQ(LOW, job->priority());
2085}
2086
2087// Make sure that URLRequest passes on its priority updates to its
2088// job.
2089TEST_F(URLRequestTest, SetJobPriority) {
2090 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192091 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362092 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d));
[email protected]5033ab82013-03-22 20:17:462093
2094 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192095 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:502096 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:462097
[email protected]f7022f32014-08-21 16:32:192098 req->SetPriority(LOW);
2099 req->Start();
[email protected]5033ab82013-03-22 20:17:462100 EXPECT_EQ(LOW, job->priority());
2101
[email protected]f7022f32014-08-21 16:32:192102 req->SetPriority(MEDIUM);
2103 EXPECT_EQ(MEDIUM, req->priority());
[email protected]5033ab82013-03-22 20:17:462104 EXPECT_EQ(MEDIUM, job->priority());
2105}
2106
[email protected]bb1c4662013-11-14 00:00:072107// Setting the IGNORE_LIMITS load flag should be okay if the priority
2108// is MAXIMUM_PRIORITY.
2109TEST_F(URLRequestTest, PriorityIgnoreLimits) {
2110 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192111 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362112 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192113 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072114
2115 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:192116 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]bb1c4662013-11-14 00:00:072117 AddTestInterceptor()->set_main_intercept_job(job.get());
2118
[email protected]f7022f32014-08-21 16:32:192119 req->SetLoadFlags(LOAD_IGNORE_LIMITS);
2120 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072121
[email protected]f7022f32014-08-21 16:32:192122 req->SetPriority(MAXIMUM_PRIORITY);
2123 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072124
[email protected]f7022f32014-08-21 16:32:192125 req->Start();
2126 EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
[email protected]bb1c4662013-11-14 00:00:072127 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
2128}
2129
[email protected]ce7d0cbc2013-05-03 18:57:222130// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:442131#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:222132// A subclass of SpawnedTestServer that uses a statically-configured hostname.
2133// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:442134// http://crbug.com/114369
[email protected]cd6f2522014-01-16 18:27:352135// TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
[email protected]ce7d0cbc2013-05-03 18:57:222136class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:442137 public:
[email protected]6cdfd7f2013-02-08 20:40:152138 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:222139 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2140 ScopedCustomUrlRequestTestHttpHost::value(),
2141 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:442142 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:222143 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
2144 ScopedCustomUrlRequestTestHttpHost::value(),
2145 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:442146};
2147
[email protected]f2f31b32013-01-16 23:24:092148TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:442149 LocalHttpTestServer test_server;
2150 ASSERT_TRUE(test_server.Start());
2151
2152 TestURLRequestContext context;
2153 scoped_refptr<DelayedCookieMonster> delayed_cm =
2154 new DelayedCookieMonster();
2155 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:502156 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:442157
2158 // Set up a cookie.
2159 {
2160 TestNetworkDelegate network_delegate;
2161 context.set_network_delegate(&network_delegate);
2162 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192163 scoped_ptr<URLRequest> req(context.CreateRequest(
2164 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362165 &d));
[email protected]f7022f32014-08-21 16:32:192166 req->Start();
[email protected]255620da2013-08-19 13:14:292167 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442168 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2169 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2170 EXPECT_EQ(1, network_delegate.set_cookie_count());
2171 }
2172
2173 // Verify that the cookie is set.
2174 {
2175 TestNetworkDelegate network_delegate;
2176 context.set_network_delegate(&network_delegate);
2177 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192178 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:362179 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192180 req->Start();
[email protected]255620da2013-08-19 13:14:292181 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442182
2183 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2184 != std::string::npos);
2185 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2186 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2187 }
2188}
2189
[email protected]f2f31b32013-01-16 23:24:092190TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:442191 LocalHttpTestServer test_server;
2192 ASSERT_TRUE(test_server.Start());
2193
2194 // Set up a cookie.
2195 {
2196 TestNetworkDelegate network_delegate;
2197 default_context_.set_network_delegate(&network_delegate);
2198 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192199 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2200 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362201 &d));
[email protected]f7022f32014-08-21 16:32:192202 req->Start();
[email protected]255620da2013-08-19 13:14:292203 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442204 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2205 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2206 }
2207
2208 // Verify that the cookie is set.
2209 {
2210 TestNetworkDelegate network_delegate;
2211 default_context_.set_network_delegate(&network_delegate);
2212 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192213 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362214 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192215 req->Start();
[email protected]255620da2013-08-19 13:14:292216 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442217
2218 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2219 != std::string::npos);
2220 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2221 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2222 }
2223
2224 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2225 {
2226 TestNetworkDelegate network_delegate;
2227 default_context_.set_network_delegate(&network_delegate);
2228 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192229 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362230 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192231 req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2232 req->Start();
[email protected]255620da2013-08-19 13:14:292233 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442234
2235 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2236 == std::string::npos);
2237
2238 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2239 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2240 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2241 }
2242}
2243
2244TEST_F(URLRequestTest, DoNotSaveCookies) {
2245 LocalHttpTestServer test_server;
2246 ASSERT_TRUE(test_server.Start());
2247
2248 // Set up a cookie.
2249 {
2250 TestNetworkDelegate network_delegate;
2251 default_context_.set_network_delegate(&network_delegate);
2252 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192253 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2254 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362255 &d));
[email protected]f7022f32014-08-21 16:32:192256 req->Start();
[email protected]255620da2013-08-19 13:14:292257 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442258
2259 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2260 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2261 EXPECT_EQ(1, network_delegate.set_cookie_count());
2262 }
2263
2264 // Try to set-up another cookie and update the previous cookie.
2265 {
2266 TestNetworkDelegate network_delegate;
2267 default_context_.set_network_delegate(&network_delegate);
2268 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192269 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442270 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362271 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192272 req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2273 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442274
[email protected]255620da2013-08-19 13:14:292275 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442276
2277 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2280 EXPECT_EQ(0, network_delegate.set_cookie_count());
2281 }
2282
2283 // Verify the cookies weren't saved or updated.
2284 {
2285 TestNetworkDelegate network_delegate;
2286 default_context_.set_network_delegate(&network_delegate);
2287 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192288 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362289 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192290 req->Start();
[email protected]255620da2013-08-19 13:14:292291 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442292
2293 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2294 == std::string::npos);
2295 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2296 != std::string::npos);
2297
2298 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2299 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2300 EXPECT_EQ(0, network_delegate.set_cookie_count());
2301 }
2302}
2303
2304TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2305 LocalHttpTestServer test_server;
2306 ASSERT_TRUE(test_server.Start());
2307
2308 // Set up a cookie.
2309 {
2310 TestNetworkDelegate network_delegate;
2311 default_context_.set_network_delegate(&network_delegate);
2312 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192313 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2314 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362315 &d));
[email protected]f7022f32014-08-21 16:32:192316 req->Start();
[email protected]255620da2013-08-19 13:14:292317 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442318
2319 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2320 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2321 }
2322
2323 // Verify that the cookie is set.
2324 {
2325 TestNetworkDelegate network_delegate;
2326 default_context_.set_network_delegate(&network_delegate);
2327 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192328 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362329 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192330 req->Start();
[email protected]255620da2013-08-19 13:14:292331 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442332
2333 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2334 != std::string::npos);
2335
2336 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2337 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2338 }
2339
2340 // Verify that the cookie isn't sent.
2341 {
2342 TestNetworkDelegate network_delegate;
2343 default_context_.set_network_delegate(&network_delegate);
2344 TestDelegate d;
2345 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192346 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362347 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192348 req->Start();
[email protected]255620da2013-08-19 13:14:292349 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442350
2351 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2352 == std::string::npos);
2353
[email protected]22e045f2013-09-20 03:54:032354 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442355 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2356 }
2357}
2358
2359TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2360 LocalHttpTestServer test_server;
2361 ASSERT_TRUE(test_server.Start());
2362
2363 // Set up a cookie.
2364 {
2365 TestNetworkDelegate network_delegate;
2366 default_context_.set_network_delegate(&network_delegate);
2367 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192368 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2369 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362370 &d));
[email protected]f7022f32014-08-21 16:32:192371 req->Start();
[email protected]255620da2013-08-19 13:14:292372 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442373
2374 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2375 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2376 }
2377
2378 // Try to set-up another cookie and update the previous cookie.
2379 {
2380 TestNetworkDelegate network_delegate;
2381 default_context_.set_network_delegate(&network_delegate);
2382 TestDelegate d;
2383 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192384 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442385 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362386 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192387 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442388
[email protected]255620da2013-08-19 13:14:292389 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442390
2391 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2392 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2393 }
2394
2395 // Verify the cookies weren't saved or updated.
2396 {
2397 TestNetworkDelegate network_delegate;
2398 default_context_.set_network_delegate(&network_delegate);
2399 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192400 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362401 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192402 req->Start();
[email protected]255620da2013-08-19 13:14:292403 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442404
2405 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2406 == std::string::npos);
2407 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2408 != std::string::npos);
2409
2410 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2411 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2412 }
2413}
2414
2415TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2416 LocalHttpTestServer test_server;
2417 ASSERT_TRUE(test_server.Start());
2418
2419 // Set up an empty cookie.
2420 {
2421 TestNetworkDelegate network_delegate;
2422 default_context_.set_network_delegate(&network_delegate);
2423 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192424 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362425 test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192426 req->Start();
[email protected]255620da2013-08-19 13:14:292427 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442428
2429 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2430 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2431 EXPECT_EQ(0, network_delegate.set_cookie_count());
2432 }
2433}
2434
2435TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2436 LocalHttpTestServer test_server;
2437 ASSERT_TRUE(test_server.Start());
2438
2439 // Set up a cookie.
2440 {
2441 TestNetworkDelegate network_delegate;
2442 default_context_.set_network_delegate(&network_delegate);
2443 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192444 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2445 test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362446 &d));
[email protected]f7022f32014-08-21 16:32:192447 req->Start();
[email protected]255620da2013-08-19 13:14:292448 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442449
2450 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2451 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2452 }
2453
2454 // Verify that the cookie is set.
2455 {
2456 TestNetworkDelegate network_delegate;
2457 default_context_.set_network_delegate(&network_delegate);
2458 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192459 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362460 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192461 req->Start();
[email protected]255620da2013-08-19 13:14:292462 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442463
2464 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2465 != std::string::npos);
2466
2467 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2468 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2469 }
2470
2471 // Verify that the cookie isn't sent.
2472 {
2473 TestNetworkDelegate network_delegate;
2474 default_context_.set_network_delegate(&network_delegate);
2475 TestDelegate d;
2476 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
[email protected]f7022f32014-08-21 16:32:192477 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362478 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192479 req->Start();
[email protected]255620da2013-08-19 13:14:292480 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442481
2482 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2483 == std::string::npos);
2484
[email protected]22e045f2013-09-20 03:54:032485 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442486 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2487 }
2488}
2489
2490TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2491 LocalHttpTestServer test_server;
2492 ASSERT_TRUE(test_server.Start());
2493
2494 // Set up a cookie.
2495 {
2496 TestNetworkDelegate network_delegate;
2497 default_context_.set_network_delegate(&network_delegate);
2498 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192499 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2500 test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:362501 &d));
[email protected]f7022f32014-08-21 16:32:192502 req->Start();
[email protected]255620da2013-08-19 13:14:292503 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442504
2505 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2506 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2507 }
2508
2509 // Try to set-up another cookie and update the previous cookie.
2510 {
2511 TestNetworkDelegate network_delegate;
2512 default_context_.set_network_delegate(&network_delegate);
2513 TestDelegate d;
2514 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
[email protected]f7022f32014-08-21 16:32:192515 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]316c1e5e2012-09-12 15:17:442516 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
davidben151423e2015-03-23 18:48:362517 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192518 req->Start();
[email protected]316c1e5e2012-09-12 15:17:442519
[email protected]255620da2013-08-19 13:14:292520 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442521
2522 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2523 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2524 }
2525
2526 // Verify the cookies weren't saved or updated.
2527 {
2528 TestNetworkDelegate network_delegate;
2529 default_context_.set_network_delegate(&network_delegate);
2530 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192531 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362532 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192533 req->Start();
[email protected]255620da2013-08-19 13:14:292534 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442535
2536 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2537 == std::string::npos);
2538 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2539 != std::string::npos);
2540
2541 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2542 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2543 }
2544}
2545
mkwst3f3daac2015-02-26 20:15:262546TEST_F(URLRequestTest, FirstPartyOnlyCookiesEnabled) {
2547 LocalHttpTestServer test_server;
2548 ASSERT_TRUE(test_server.Start());
2549
2550 // Set up a 'First-Party-Only' cookie (on '127.0.0.1', as that's where
2551 // LocalHttpTestServer points).
2552 {
2553 TestNetworkDelegate network_delegate;
mkwst3f3daac2015-02-26 20:15:262554 default_context_.set_network_delegate(&network_delegate);
2555
2556 TestDelegate d;
2557 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2558 test_server.GetURL(
2559 "set-cookie?FirstPartyCookieToSet=1;First-Party-Only"),
davidben151423e2015-03-23 18:48:362560 DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262561 req->Start();
2562 base::RunLoop().Run();
2563 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2564 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2565 EXPECT_EQ(1, network_delegate.set_cookie_count());
2566 }
2567
2568 // Verify that the cookie is sent for first-party requests.
2569 {
2570 TestNetworkDelegate network_delegate;
mkwst3f3daac2015-02-26 20:15:262571 default_context_.set_network_delegate(&network_delegate);
2572 TestDelegate d;
2573 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362574 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262575 req->set_first_party_for_cookies(test_server.GetURL(""));
2576 req->Start();
2577 base::RunLoop().Run();
2578
2579 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") !=
2580 std::string::npos);
2581 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2582 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2583 }
2584
2585 // Verify that the cookie is not-sent for non-first-party requests.
2586 {
2587 TestNetworkDelegate network_delegate;
mkwst3f3daac2015-02-26 20:15:262588 default_context_.set_network_delegate(&network_delegate);
2589 TestDelegate d;
2590 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362591 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
mkwst3f3daac2015-02-26 20:15:262592 req->set_first_party_for_cookies(GURL("http://third-party.test/"));
2593 req->Start();
2594 base::RunLoop().Run();
2595
2596 EXPECT_TRUE(d.data_received().find("FirstPartyCookieToSet=1") ==
2597 std::string::npos);
2598 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2599 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2600 }
2601}
2602
[email protected]5095cd72012-11-01 10:29:162603// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2604// value for the |fixed_date| argument given to the constructor.
2605class FixedDateNetworkDelegate : public TestNetworkDelegate {
2606 public:
2607 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2608 : fixed_date_(fixed_date) {}
dchengb03027d2014-10-21 12:00:202609 ~FixedDateNetworkDelegate() override {}
[email protected]5095cd72012-11-01 10:29:162610
[email protected]cba24642014-08-15 20:49:592611 // NetworkDelegate implementation
dchengb03027d2014-10-21 12:00:202612 int OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592613 URLRequest* request,
2614 const CompletionCallback& callback,
2615 const HttpResponseHeaders* original_response_headers,
2616 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:132617 GURL* allowed_unsafe_redirect_url) override;
[email protected]5095cd72012-11-01 10:29:162618
2619 private:
2620 std::string fixed_date_;
2621
2622 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2623};
2624
2625int FixedDateNetworkDelegate::OnHeadersReceived(
[email protected]cba24642014-08-15 20:49:592626 URLRequest* request,
2627 const CompletionCallback& callback,
2628 const HttpResponseHeaders* original_response_headers,
2629 scoped_refptr<HttpResponseHeaders>* override_response_headers,
[email protected]5f714132014-03-26 10:41:162630 GURL* allowed_unsafe_redirect_url) {
[email protected]cba24642014-08-15 20:49:592631 HttpResponseHeaders* new_response_headers =
2632 new HttpResponseHeaders(original_response_headers->raw_headers());
[email protected]5095cd72012-11-01 10:29:162633
2634 new_response_headers->RemoveHeader("Date");
2635 new_response_headers->AddHeader("Date: " + fixed_date_);
2636
2637 *override_response_headers = new_response_headers;
2638 return TestNetworkDelegate::OnHeadersReceived(request,
2639 callback,
2640 original_response_headers,
[email protected]5f714132014-03-26 10:41:162641 override_response_headers,
2642 allowed_unsafe_redirect_url);
[email protected]5095cd72012-11-01 10:29:162643}
2644
2645// Test that cookie expiration times are adjusted for server/client clock
2646// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2647// headers by defaulting to GMT. (crbug.com/135131)
2648TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2649 LocalHttpTestServer test_server;
2650 ASSERT_TRUE(test_server.Start());
2651
2652 // Set up an expired cookie.
2653 {
2654 TestNetworkDelegate network_delegate;
2655 default_context_.set_network_delegate(&network_delegate);
2656 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192657 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192658 test_server.GetURL(
2659 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362660 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192661 req->Start();
[email protected]255620da2013-08-19 13:14:292662 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162663 }
2664 // Verify that the cookie is not set.
2665 {
2666 TestNetworkDelegate network_delegate;
2667 default_context_.set_network_delegate(&network_delegate);
2668 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192669 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362670 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192671 req->Start();
[email protected]255620da2013-08-19 13:14:292672 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162673
2674 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2675 }
2676 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2677 {
2678 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2679 default_context_.set_network_delegate(&network_delegate);
2680 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192681 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:192682 test_server.GetURL(
2683 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
davidben151423e2015-03-23 18:48:362684 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192685 req->Start();
[email protected]255620da2013-08-19 13:14:292686 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162687 }
2688 // Verify that the cookie is set.
2689 {
2690 TestNetworkDelegate network_delegate;
2691 default_context_.set_network_delegate(&network_delegate);
2692 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192693 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362694 test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192695 req->Start();
[email protected]255620da2013-08-19 13:14:292696 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162697
2698 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2699 }
2700}
2701
2702
[email protected]316c1e5e2012-09-12 15:17:442703// Check that it is impossible to change the referrer in the extra headers of
2704// an URLRequest.
2705TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2706 LocalHttpTestServer test_server;
2707 ASSERT_TRUE(test_server.Start());
2708
2709 // If extra headers contain referer and the request contains a referer,
2710 // only the latter shall be respected.
2711 {
2712 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192713 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362714 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192715 req->SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442716
2717 HttpRequestHeaders headers;
2718 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192719 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:442720
[email protected]f7022f32014-08-21 16:32:192721 req->Start();
[email protected]255620da2013-08-19 13:14:292722 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442723
2724 EXPECT_EQ("http://foo.com/", d.data_received());
2725 }
2726
2727 // If extra headers contain a referer but the request does not, no referer
2728 // shall be sent in the header.
2729 {
2730 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192731 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362732 test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:442733
2734 HttpRequestHeaders headers;
2735 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
[email protected]f7022f32014-08-21 16:32:192736 req->SetExtraRequestHeaders(headers);
2737 req->SetLoadFlags(LOAD_VALIDATE_CACHE);
[email protected]316c1e5e2012-09-12 15:17:442738
[email protected]f7022f32014-08-21 16:32:192739 req->Start();
[email protected]255620da2013-08-19 13:14:292740 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442741
2742 EXPECT_EQ("None", d.data_received());
2743 }
2744}
2745
[email protected]b89290212009-08-14 22:37:352746class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112747 public:
2748 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152749 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112750 "net/data/url_request_unittest"))) {
2751 }
2752
[email protected]b89290212009-08-14 22:37:352753 protected:
[email protected]21184962011-10-26 00:50:302754 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2755 // |request_method| is the method to use for the initial request.
2756 // |redirect_method| is the method that is expected to be used for the second
2757 // request, after redirection.
2758 // If |include_data| is true, data is uploaded with the request. The
2759 // response body is expected to match it exactly, if and only if
2760 // |request_method| == |redirect_method|.
2761 void HTTPRedirectMethodTest(const GURL& redirect_url,
2762 const std::string& request_method,
2763 const std::string& redirect_method,
2764 bool include_data) {
2765 static const char kData[] = "hello world";
2766 TestDelegate d;
davidben151423e2015-03-23 18:48:362767 scoped_ptr<URLRequest> req(
2768 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192769 req->set_method(request_method);
[email protected]21184962011-10-26 00:50:302770 if (include_data) {
mmenkecbc2b712014-10-09 20:29:072771 req->set_upload(CreateSimpleUploadData(kData));
[email protected]21184962011-10-26 00:50:302772 HttpRequestHeaders headers;
2773 headers.SetHeader(HttpRequestHeaders::kContentLength,
2774 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:192775 req->SetExtraRequestHeaders(headers);
[email protected]21184962011-10-26 00:50:302776 }
[email protected]f7022f32014-08-21 16:32:192777 req->Start();
[email protected]255620da2013-08-19 13:14:292778 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:192779 EXPECT_EQ(redirect_method, req->method());
2780 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2781 EXPECT_EQ(OK, req->status().error());
[email protected]21184962011-10-26 00:50:302782 if (include_data) {
2783 if (request_method == redirect_method) {
2784 EXPECT_EQ(kData, d.data_received());
2785 } else {
2786 EXPECT_NE(kData, d.data_received());
2787 }
2788 }
2789 if (HasFailure())
2790 LOG(WARNING) << "Request method was: " << request_method;
2791 }
2792
jww5fe460ff2015-03-28 00:22:512793 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2794 // |request_method| is the method to use for the initial request.
2795 // |redirect_method| is the method that is expected to be used for the second
2796 // request, after redirection.
2797 // |origin_value| is the expected value for the Origin header after
2798 // redirection. If empty, expects that there will be no Origin header.
2799 void HTTPRedirectOriginHeaderTest(const GURL& redirect_url,
2800 const std::string& request_method,
2801 const std::string& redirect_method,
2802 const std::string& origin_value) {
2803 TestDelegate d;
2804 scoped_ptr<URLRequest> req(
2805 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
2806 req->set_method(request_method);
2807 req->SetExtraRequestHeaderByName(HttpRequestHeaders::kOrigin,
2808 redirect_url.GetOrigin().spec(), false);
2809 req->Start();
2810
2811 base::RunLoop().Run();
2812
2813 EXPECT_EQ(redirect_method, req->method());
2814 // Note that there is no check for request success here because, for
2815 // purposes of testing, the request very well may fail. For example, if the
2816 // test redirects to an HTTPS server from an HTTP origin, thus it is cross
2817 // origin, there is not an HTTPS server in this unit test framework, so the
2818 // request would fail. However, that's fine, as long as the request headers
2819 // are in order and pass the checks below.
2820 if (origin_value.empty()) {
2821 EXPECT_FALSE(
2822 req->extra_request_headers().HasHeader(HttpRequestHeaders::kOrigin));
2823 } else {
2824 std::string origin_header;
2825 EXPECT_TRUE(req->extra_request_headers().GetHeader(
2826 HttpRequestHeaders::kOrigin, &origin_header));
2827 EXPECT_EQ(origin_value, origin_header);
2828 }
2829 }
2830
[email protected]762d2db2010-01-11 19:03:012831 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012832 const int kMsgSize = 20000; // multiple of 10
2833 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482834 char* uploadBytes = new char[kMsgSize+1];
2835 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012836 char marker = 'a';
2837 for (int idx = 0; idx < kMsgSize/10; idx++) {
2838 memcpy(ptr, "----------", 10);
2839 ptr += 10;
2840 if (idx % 100 == 0) {
2841 ptr--;
2842 *ptr++ = marker;
2843 if (++marker > 'z')
2844 marker = 'a';
2845 }
2846 }
2847 uploadBytes[kMsgSize] = '\0';
2848
[email protected]762d2db2010-01-11 19:03:012849 for (int i = 0; i < kIterations; ++i) {
2850 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192851 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:362852 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192853 r->set_method(method.c_str());
[email protected]762d2db2010-01-11 19:03:012854
mmenkecbc2b712014-10-09 20:29:072855 r->set_upload(CreateSimpleUploadData(uploadBytes));
[email protected]762d2db2010-01-11 19:03:012856
[email protected]f7022f32014-08-21 16:32:192857 r->Start();
2858 EXPECT_TRUE(r->is_pending());
[email protected]762d2db2010-01-11 19:03:012859
[email protected]255620da2013-08-19 13:14:292860 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012861
[email protected]329b68b2012-11-14 17:54:272862 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:192863 << "request failed: " << r->status().status()
2864 << ", os error: " << r->status().error();
[email protected]762d2db2010-01-11 19:03:012865
2866 EXPECT_FALSE(d.received_data_before_response());
2867 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012868 }
2869 delete[] uploadBytes;
2870 }
2871
[email protected]ef2bf422012-05-11 03:27:092872 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222873 r->AppendChunkToUpload("a", 1, false);
2874 r->AppendChunkToUpload("bcd", 3, false);
2875 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2876 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2877 r->AppendChunkToUpload("0", 1, false);
2878 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112879 }
2880
[email protected]ef2bf422012-05-11 03:27:092881 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112882 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272883 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112884 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2885
[email protected]329b68b2012-11-14 17:54:272886 ASSERT_EQ(1, d->response_started_count())
2887 << "request failed: " << r->status().status()
2888 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112889
2890 EXPECT_FALSE(d->received_data_before_response());
2891
[email protected]329b68b2012-11-14 17:54:272892 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2893 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112894 }
2895
[email protected]ede03212012-09-07 12:52:262896 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342897 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:192898 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2899 test_server_.GetURL("set-many-cookies?" +
davidben151423e2015-03-23 18:48:362900 base::IntToString(num_cookies)),
2901 DEFAULT_PRIORITY, &d));
[email protected]263163f2012-06-14 22:40:342902
[email protected]f7022f32014-08-21 16:32:192903 r->Start();
2904 EXPECT_TRUE(r->is_pending());
[email protected]263163f2012-06-14 22:40:342905
[email protected]255620da2013-08-19 13:14:292906 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342907
[email protected]f7022f32014-08-21 16:32:192908 bool is_success = r->status().is_success();
[email protected]263163f2012-06-14 22:40:342909
[email protected]ede03212012-09-07 12:52:262910 if (!is_success) {
[email protected]f7022f32014-08-21 16:32:192911 EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
[email protected]263163f2012-06-14 22:40:342912 // The test server appears to be unable to handle subsequent requests
2913 // after this error is triggered. Force it to restart.
2914 EXPECT_TRUE(test_server_.Stop());
2915 EXPECT_TRUE(test_server_.Start());
2916 }
2917
2918 return is_success;
2919 }
2920
bengr1bf8e942014-11-07 01:36:502921 LocalHttpTestServer* test_server() {
2922 return &test_server_;
2923 }
2924
2925 protected:
[email protected]1700c6a2012-02-22 18:07:072926 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352927};
2928
[email protected]95409e12010-08-17 20:07:112929// In this unit test, we're using the HTTPTestServer as a proxy server and
2930// issuing a CONNECT request with the magic host name "www.redirect.com".
2931// The HTTPTestServer will return a 302 response, which we should not
2932// follow.
[email protected]f2f31b32013-01-16 23:24:092933TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112934 ASSERT_TRUE(test_server_.Start());
2935
[email protected]ceefd7fd2012-11-29 00:36:242936 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042937 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192938 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502939
[email protected]d1ec59082009-02-11 02:48:152940 TestDelegate d;
2941 {
[email protected]f7022f32014-08-21 16:32:192942 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:362943 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192944 r->Start();
2945 EXPECT_TRUE(r->is_pending());
[email protected]d1ec59082009-02-11 02:48:152946
[email protected]255620da2013-08-19 13:14:292947 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152948
[email protected]f7022f32014-08-21 16:32:192949 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152950 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192951 EXPECT_TRUE(r->proxy_server().IsEmpty());
2952 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:082953 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152954 // We should not have followed the redirect.
2955 EXPECT_EQ(0, d.received_redirect_count());
2956 }
2957}
2958
[email protected]8202d0c2011-02-23 08:31:142959// This is the same as the previous test, but checks that the network delegate
2960// registers the error.
[email protected]c044616e2013-02-20 02:01:262961TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142962 ASSERT_TRUE(test_server_.Start());
2963
[email protected]ceefd7fd2012-11-29 00:36:242964 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042965 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:192966 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:502967
[email protected]8202d0c2011-02-23 08:31:142968 TestDelegate d;
2969 {
[email protected]f7022f32014-08-21 16:32:192970 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:362971 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:192972 r->Start();
2973 EXPECT_TRUE(r->is_pending());
[email protected]8202d0c2011-02-23 08:31:142974
[email protected]255620da2013-08-19 13:14:292975 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142976
[email protected]f7022f32014-08-21 16:32:192977 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:152978 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:192979 EXPECT_TRUE(r->proxy_server().IsEmpty());
2980 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]8202d0c2011-02-23 08:31:142981 EXPECT_EQ(1, d.response_started_count());
2982 // We should not have followed the redirect.
2983 EXPECT_EQ(0, d.received_redirect_count());
2984
2985 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052986 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142987 }
2988}
2989
[email protected]dc5a5cf2012-09-26 02:49:302990// Tests that we can block and asynchronously return OK in various stages.
2991TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2992 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2993 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2994 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2995 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2996 };
2997 static const size_t blocking_stages_length = arraysize(blocking_stages);
2998
2999 ASSERT_TRUE(test_server_.Start());
3000
3001 TestDelegate d;
3002 BlockingNetworkDelegate network_delegate(
3003 BlockingNetworkDelegate::USER_CALLBACK);
3004 network_delegate.set_block_on(
3005 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
3006 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
3007 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3008
3009 TestURLRequestContext context(true);
3010 context.set_network_delegate(&network_delegate);
3011 context.Init();
3012
3013 {
[email protected]f7022f32014-08-21 16:32:193014 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363015 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]dc5a5cf2012-09-26 02:49:303016
[email protected]f7022f32014-08-21 16:32:193017 r->Start();
[email protected]dc5a5cf2012-09-26 02:49:303018 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:293019 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303020 EXPECT_EQ(blocking_stages[i],
3021 network_delegate.stage_blocked_for_callback());
3022 network_delegate.DoCallback(OK);
3023 }
[email protected]255620da2013-08-19 13:14:293024 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193025 EXPECT_EQ(200, r->GetResponseCode());
3026 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]dc5a5cf2012-09-26 02:49:303027 EXPECT_EQ(1, network_delegate.created_requests());
3028 EXPECT_EQ(0, network_delegate.destroyed_requests());
3029 }
3030 EXPECT_EQ(1, network_delegate.destroyed_requests());
3031}
3032
[email protected]4c76d7c2011-04-15 19:14:123033// Tests that the network delegate can block and cancel a request.
3034TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
3035 ASSERT_TRUE(test_server_.Start());
3036
3037 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303038 BlockingNetworkDelegate network_delegate(
3039 BlockingNetworkDelegate::AUTO_CALLBACK);
3040 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3041 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:123042
[email protected]d5a4dd62012-05-23 01:41:043043 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193044 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503045
[email protected]4c76d7c2011-04-15 19:14:123046 {
[email protected]f7022f32014-08-21 16:32:193047 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363048 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123049
[email protected]f7022f32014-08-21 16:32:193050 r->Start();
[email protected]255620da2013-08-19 13:14:293051 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123052
[email protected]f7022f32014-08-21 16:32:193053 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153054 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193055 EXPECT_TRUE(r->proxy_server().IsEmpty());
3056 EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
[email protected]4c76d7c2011-04-15 19:14:123057 EXPECT_EQ(1, network_delegate.created_requests());
3058 EXPECT_EQ(0, network_delegate.destroyed_requests());
3059 }
3060 EXPECT_EQ(1, network_delegate.destroyed_requests());
3061}
3062
[email protected]b4438d32012-09-27 06:15:303063// Helper function for NetworkDelegateCancelRequestAsynchronously and
3064// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
3065// delegate operating in |block_mode| and a request for |url|. It blocks the
3066// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
3067void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
3068 BlockingNetworkDelegate::Stage stage,
3069 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:363070 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:303071 BlockingNetworkDelegate network_delegate(block_mode);
3072 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
3073 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:363074
[email protected]b4438d32012-09-27 06:15:303075 TestURLRequestContext context(true);
3076 context.set_network_delegate(&network_delegate);
3077 context.Init();
[email protected]3cd384c602011-08-31 16:12:363078
3079 {
davidben151423e2015-03-23 18:48:363080 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]3cd384c602011-08-31 16:12:363081
[email protected]f7022f32014-08-21 16:32:193082 r->Start();
[email protected]255620da2013-08-19 13:14:293083 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:363084
[email protected]f7022f32014-08-21 16:32:193085 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153086 // The proxy server is not set before cancellation.
[email protected]f7022f32014-08-21 16:32:193087 EXPECT_TRUE(r->proxy_server().IsEmpty());
3088 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
[email protected]3cd384c602011-08-31 16:12:363089 EXPECT_EQ(1, network_delegate.created_requests());
3090 EXPECT_EQ(0, network_delegate.destroyed_requests());
3091 }
3092 EXPECT_EQ(1, network_delegate.destroyed_requests());
3093}
3094
[email protected]b4438d32012-09-27 06:15:303095// The following 3 tests check that the network delegate can cancel a request
3096// synchronously in various stages of the request.
3097TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
3098 ASSERT_TRUE(test_server_.Start());
3099 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3100 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453101 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303102}
3103
3104TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
3105 ASSERT_TRUE(test_server_.Start());
3106 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3107 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453108 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303109}
3110
3111TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
3112 ASSERT_TRUE(test_server_.Start());
3113 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
3114 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453115 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303116}
3117
3118// The following 3 tests check that the network delegate can cancel a request
3119// asynchronously in various stages of the request.
3120TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
3121 ASSERT_TRUE(test_server_.Start());
3122 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3123 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:453124 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303125}
3126
3127TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
3128 ASSERT_TRUE(test_server_.Start());
3129 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3130 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:453131 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303132}
3133
3134TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
3135 ASSERT_TRUE(test_server_.Start());
3136 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
3137 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:453138 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:303139}
3140
[email protected]4c76d7c2011-04-15 19:14:123141// Tests that the network delegate can block and redirect a request to a new
3142// URL.
3143TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
3144 ASSERT_TRUE(test_server_.Start());
3145
3146 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303147 BlockingNetworkDelegate network_delegate(
3148 BlockingNetworkDelegate::AUTO_CALLBACK);
3149 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:123150 GURL redirect_url(test_server_.GetURL("simple.html"));
3151 network_delegate.set_redirect_url(redirect_url);
3152
[email protected]d5a4dd62012-05-23 01:41:043153 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193154 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503155
[email protected]4c76d7c2011-04-15 19:14:123156 {
[email protected]8f1ac082011-04-19 21:14:133157 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363158 scoped_ptr<URLRequest> r(
3159 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]4c76d7c2011-04-15 19:14:123160
[email protected]6be6fa92014-08-06 23:44:563161 // Quit after hitting the redirect, so can check the headers.
3162 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193163 r->Start();
[email protected]255620da2013-08-19 13:14:293164 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:123165
[email protected]6be6fa92014-08-06 23:44:563166 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193167 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3168 EXPECT_EQ(307, r->GetResponseCode());
3169 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563170 std::string location;
[email protected]f7022f32014-08-21 16:32:193171 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3172 &location));
[email protected]6be6fa92014-08-06 23:44:563173 EXPECT_EQ(redirect_url, GURL(location));
3174
3175 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193176 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563177 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:193178 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3179 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273180 EXPECT_EQ(
3181 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3182 EXPECT_TRUE(
3183 network_delegate.last_observed_proxy().Equals(
3184 test_server_.host_port_pair()));
3185
[email protected]f7022f32014-08-21 16:32:193186 EXPECT_EQ(0, r->status().error());
3187 EXPECT_EQ(redirect_url, r->url());
3188 EXPECT_EQ(original_url, r->original_url());
3189 EXPECT_EQ(2U, r->url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:123190 EXPECT_EQ(1, network_delegate.created_requests());
3191 EXPECT_EQ(0, network_delegate.destroyed_requests());
3192 }
3193 EXPECT_EQ(1, network_delegate.destroyed_requests());
3194}
3195
[email protected]b813ed72012-04-05 08:21:363196// Tests that the network delegate can block and redirect a request to a new
3197// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
3198TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
3199 ASSERT_TRUE(test_server_.Start());
3200
3201 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303202 BlockingNetworkDelegate network_delegate(
3203 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:363204 GURL redirect_url(test_server_.GetURL("simple.html"));
3205 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:363206
[email protected]d5a4dd62012-05-23 01:41:043207 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193208 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]b813ed72012-04-05 08:21:363209
3210 {
3211 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363212 scoped_ptr<URLRequest> r(
3213 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]b813ed72012-04-05 08:21:363214
[email protected]6be6fa92014-08-06 23:44:563215 // Quit after hitting the redirect, so can check the headers.
3216 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193217 r->Start();
[email protected]255620da2013-08-19 13:14:293218 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:363219
[email protected]6be6fa92014-08-06 23:44:563220 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193221 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3222 EXPECT_EQ(307, r->GetResponseCode());
3223 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563224 std::string location;
[email protected]f7022f32014-08-21 16:32:193225 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3226 &location));
[email protected]6be6fa92014-08-06 23:44:563227 EXPECT_EQ(redirect_url, GURL(location));
3228
3229 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193230 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563231 base::RunLoop().Run();
3232
[email protected]f7022f32014-08-21 16:32:193233 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3234 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273235 EXPECT_EQ(
3236 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
3237 EXPECT_TRUE(
3238 network_delegate.last_observed_proxy().Equals(
3239 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193240 EXPECT_EQ(0, r->status().error());
3241 EXPECT_EQ(redirect_url, r->url());
3242 EXPECT_EQ(original_url, r->original_url());
3243 EXPECT_EQ(2U, r->url_chain().size());
[email protected]b813ed72012-04-05 08:21:363244 EXPECT_EQ(1, network_delegate.created_requests());
3245 EXPECT_EQ(0, network_delegate.destroyed_requests());
3246 }
3247 EXPECT_EQ(1, network_delegate.destroyed_requests());
3248}
3249
[email protected]3c5ca8c2011-09-29 01:14:513250// Tests that redirects caused by the network delegate preserve POST data.
3251TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3252 ASSERT_TRUE(test_server_.Start());
3253
3254 const char kData[] = "hello world";
3255
3256 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303257 BlockingNetworkDelegate network_delegate(
3258 BlockingNetworkDelegate::AUTO_CALLBACK);
3259 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:513260 GURL redirect_url(test_server_.GetURL("echo"));
3261 network_delegate.set_redirect_url(redirect_url);
3262
[email protected]ef2bf422012-05-11 03:27:093263 TestURLRequestContext context(true);
3264 context.set_network_delegate(&network_delegate);
3265 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:513266
3267 {
3268 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363269 scoped_ptr<URLRequest> r(
3270 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193271 r->set_method("POST");
mmenkecbc2b712014-10-09 20:29:073272 r->set_upload(CreateSimpleUploadData(kData));
[email protected]3c5ca8c2011-09-29 01:14:513273 HttpRequestHeaders headers;
3274 headers.SetHeader(HttpRequestHeaders::kContentLength,
3275 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:193276 r->SetExtraRequestHeaders(headers);
[email protected]6be6fa92014-08-06 23:44:563277
3278 // Quit after hitting the redirect, so can check the headers.
3279 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:193280 r->Start();
[email protected]255620da2013-08-19 13:14:293281 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:513282
[email protected]6be6fa92014-08-06 23:44:563283 // Check headers from URLRequestJob.
[email protected]f7022f32014-08-21 16:32:193284 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3285 EXPECT_EQ(307, r->GetResponseCode());
3286 EXPECT_EQ(307, r->response_headers()->response_code());
[email protected]6be6fa92014-08-06 23:44:563287 std::string location;
[email protected]f7022f32014-08-21 16:32:193288 ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3289 &location));
[email protected]6be6fa92014-08-06 23:44:563290 EXPECT_EQ(redirect_url, GURL(location));
3291
3292 // Let the request finish.
[email protected]f7022f32014-08-21 16:32:193293 r->FollowDeferredRedirect();
[email protected]6be6fa92014-08-06 23:44:563294 base::RunLoop().Run();
3295
[email protected]f7022f32014-08-21 16:32:193296 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3297 EXPECT_EQ(0, r->status().error());
3298 EXPECT_EQ(redirect_url, r->url());
3299 EXPECT_EQ(original_url, r->original_url());
3300 EXPECT_EQ(2U, r->url_chain().size());
[email protected]3c5ca8c2011-09-29 01:14:513301 EXPECT_EQ(1, network_delegate.created_requests());
3302 EXPECT_EQ(0, network_delegate.destroyed_requests());
[email protected]f7022f32014-08-21 16:32:193303 EXPECT_EQ("POST", r->method());
[email protected]3c5ca8c2011-09-29 01:14:513304 EXPECT_EQ(kData, d.data_received());
3305 }
3306 EXPECT_EQ(1, network_delegate.destroyed_requests());
3307}
3308
[email protected]5f714132014-03-26 10:41:163309// Tests that the network delegate can block and redirect a request to a new
3310// URL during OnHeadersReceived.
3311TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3312 ASSERT_TRUE(test_server_.Start());
3313
3314 TestDelegate d;
3315 BlockingNetworkDelegate network_delegate(
3316 BlockingNetworkDelegate::AUTO_CALLBACK);
3317 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3318 GURL redirect_url(test_server_.GetURL("simple.html"));
3319 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3320
3321 TestURLRequestContextWithProxy context(
3322 test_server_.host_port_pair().ToString(), &network_delegate);
3323
3324 {
3325 GURL original_url(test_server_.GetURL("empty.html"));
davidben151423e2015-03-23 18:48:363326 scoped_ptr<URLRequest> r(
3327 context.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:163328
[email protected]f7022f32014-08-21 16:32:193329 r->Start();
[email protected]5f714132014-03-26 10:41:163330 base::RunLoop().Run();
3331
[email protected]f7022f32014-08-21 16:32:193332 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3333 EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
[email protected]597a1ab2014-06-26 08:12:273334 EXPECT_EQ(
3335 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3336 EXPECT_TRUE(
3337 network_delegate.last_observed_proxy().Equals(
3338 test_server_.host_port_pair()));
[email protected]f7022f32014-08-21 16:32:193339
3340 EXPECT_EQ(OK, r->status().error());
3341 EXPECT_EQ(redirect_url, r->url());
3342 EXPECT_EQ(original_url, r->original_url());
3343 EXPECT_EQ(2U, r->url_chain().size());
[email protected]5f714132014-03-26 10:41:163344 EXPECT_EQ(2, network_delegate.created_requests());
3345 EXPECT_EQ(0, network_delegate.destroyed_requests());
3346 }
3347 EXPECT_EQ(1, network_delegate.destroyed_requests());
3348}
3349
[email protected]c2911d72011-10-03 22:16:363350// Tests that the network delegate can synchronously complete OnAuthRequired
3351// by taking no action. This indicates that the NetworkDelegate does not want to
3352// handle the challenge, and is passing the buck along to the
3353// URLRequest::Delegate.
3354TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3355 ASSERT_TRUE(test_server_.Start());
3356
3357 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303358 BlockingNetworkDelegate network_delegate(
3359 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:363360
[email protected]ef2bf422012-05-11 03:27:093361 TestURLRequestContext context(true);
3362 context.set_network_delegate(&network_delegate);
3363 context.Init();
[email protected]c2911d72011-10-03 22:16:363364
[email protected]f3cf9802011-10-28 18:44:583365 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363366
3367 {
3368 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363369 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193370 r->Start();
[email protected]79e1fd62013-06-20 06:50:043371
[email protected]255620da2013-08-19 13:14:293372 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043373
[email protected]f7022f32014-08-21 16:32:193374 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3375 EXPECT_EQ(0, r->status().error());
3376 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043377 EXPECT_TRUE(d.auth_required_called());
3378 EXPECT_EQ(1, network_delegate.created_requests());
3379 EXPECT_EQ(0, network_delegate.destroyed_requests());
3380 }
3381 EXPECT_EQ(1, network_delegate.destroyed_requests());
3382}
3383
3384TEST_F(URLRequestTestHTTP,
3385 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3386 ASSERT_TRUE(test_server_.Start());
3387
3388 TestDelegate d;
3389 BlockingNetworkDelegate network_delegate(
3390 BlockingNetworkDelegate::SYNCHRONOUS);
3391
3392 TestURLRequestContext context(true);
3393 context.set_network_delegate(&network_delegate);
3394 context.Init();
3395
3396 d.set_credentials(AuthCredentials(kUser, kSecret));
3397
3398 {
3399 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363400 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193401 r->Start();
[email protected]79e1fd62013-06-20 06:50:043402
3403 {
3404 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193405 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043406 EXPECT_FALSE(headers.HasHeader("Authorization"));
3407 }
3408
[email protected]255620da2013-08-19 13:14:293409 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363410
[email protected]f7022f32014-08-21 16:32:193411 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3412 EXPECT_EQ(0, r->status().error());
3413 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363414 EXPECT_TRUE(d.auth_required_called());
3415 EXPECT_EQ(1, network_delegate.created_requests());
3416 EXPECT_EQ(0, network_delegate.destroyed_requests());
3417 }
3418 EXPECT_EQ(1, network_delegate.destroyed_requests());
3419}
3420
3421// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:403422// by setting credentials.
[email protected]c2911d72011-10-03 22:16:363423TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3424 ASSERT_TRUE(test_server_.Start());
3425
3426 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303427 BlockingNetworkDelegate network_delegate(
3428 BlockingNetworkDelegate::SYNCHRONOUS);
3429 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363430 network_delegate.set_auth_retval(
3431 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3432
[email protected]f3cf9802011-10-28 18:44:583433 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363434
[email protected]ef2bf422012-05-11 03:27:093435 TestURLRequestContext context(true);
3436 context.set_network_delegate(&network_delegate);
3437 context.Init();
[email protected]c2911d72011-10-03 22:16:363438
3439 {
3440 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363441 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193442 r->Start();
[email protected]255620da2013-08-19 13:14:293443 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363444
[email protected]f7022f32014-08-21 16:32:193445 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3446 EXPECT_EQ(0, r->status().error());
3447 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363448 EXPECT_FALSE(d.auth_required_called());
3449 EXPECT_EQ(1, network_delegate.created_requests());
3450 EXPECT_EQ(0, network_delegate.destroyed_requests());
3451 }
3452 EXPECT_EQ(1, network_delegate.destroyed_requests());
3453}
3454
[email protected]79e1fd62013-06-20 06:50:043455// Same as above, but also tests that GetFullRequestHeaders returns the proper
3456// headers (for the first or second request) when called at the proper times.
3457TEST_F(URLRequestTestHTTP,
3458 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3459 ASSERT_TRUE(test_server_.Start());
3460
3461 TestDelegate d;
3462 BlockingNetworkDelegate network_delegate(
3463 BlockingNetworkDelegate::SYNCHRONOUS);
3464 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3465 network_delegate.set_auth_retval(
3466 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3467
3468 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3469
3470 TestURLRequestContext context(true);
3471 context.set_network_delegate(&network_delegate);
3472 context.Init();
3473
3474 {
3475 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363476 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193477 r->Start();
[email protected]255620da2013-08-19 13:14:293478 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043479
[email protected]f7022f32014-08-21 16:32:193480 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3481 EXPECT_EQ(0, r->status().error());
3482 EXPECT_EQ(200, r->GetResponseCode());
[email protected]79e1fd62013-06-20 06:50:043483 EXPECT_FALSE(d.auth_required_called());
3484 EXPECT_EQ(1, network_delegate.created_requests());
3485 EXPECT_EQ(0, network_delegate.destroyed_requests());
3486
3487 {
3488 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193489 EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043490 EXPECT_TRUE(headers.HasHeader("Authorization"));
3491 }
3492 }
3493 EXPECT_EQ(1, network_delegate.destroyed_requests());
3494}
3495
[email protected]c2911d72011-10-03 22:16:363496// Tests that the network delegate can synchronously complete OnAuthRequired
3497// by cancelling authentication.
3498TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3499 ASSERT_TRUE(test_server_.Start());
3500
3501 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303502 BlockingNetworkDelegate network_delegate(
3503 BlockingNetworkDelegate::SYNCHRONOUS);
3504 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363505 network_delegate.set_auth_retval(
3506 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3507
[email protected]ef2bf422012-05-11 03:27:093508 TestURLRequestContext context(true);
3509 context.set_network_delegate(&network_delegate);
3510 context.Init();
[email protected]c2911d72011-10-03 22:16:363511
3512 {
3513 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363514 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193515 r->Start();
[email protected]255620da2013-08-19 13:14:293516 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363517
[email protected]f7022f32014-08-21 16:32:193518 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3519 EXPECT_EQ(OK, r->status().error());
3520 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363521 EXPECT_FALSE(d.auth_required_called());
3522 EXPECT_EQ(1, network_delegate.created_requests());
3523 EXPECT_EQ(0, network_delegate.destroyed_requests());
3524 }
3525 EXPECT_EQ(1, network_delegate.destroyed_requests());
3526}
3527
3528// Tests that the network delegate can asynchronously complete OnAuthRequired
3529// by taking no action. This indicates that the NetworkDelegate does not want
3530// to handle the challenge, and is passing the buck along to the
3531// URLRequest::Delegate.
3532TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3533 ASSERT_TRUE(test_server_.Start());
3534
3535 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303536 BlockingNetworkDelegate network_delegate(
3537 BlockingNetworkDelegate::AUTO_CALLBACK);
3538 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363539
[email protected]ef2bf422012-05-11 03:27:093540 TestURLRequestContext context(true);
3541 context.set_network_delegate(&network_delegate);
3542 context.Init();
[email protected]c2911d72011-10-03 22:16:363543
[email protected]f3cf9802011-10-28 18:44:583544 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363545
3546 {
3547 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363548 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193549 r->Start();
[email protected]255620da2013-08-19 13:14:293550 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363551
[email protected]f7022f32014-08-21 16:32:193552 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3553 EXPECT_EQ(0, r->status().error());
3554 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363555 EXPECT_TRUE(d.auth_required_called());
3556 EXPECT_EQ(1, network_delegate.created_requests());
3557 EXPECT_EQ(0, network_delegate.destroyed_requests());
3558 }
3559 EXPECT_EQ(1, network_delegate.destroyed_requests());
3560}
3561
3562// Tests that the network delegate can asynchronously complete OnAuthRequired
3563// by setting credentials.
3564TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3565 ASSERT_TRUE(test_server_.Start());
3566
3567 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303568 BlockingNetworkDelegate network_delegate(
3569 BlockingNetworkDelegate::AUTO_CALLBACK);
3570 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363571 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363572 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3573
[email protected]f3cf9802011-10-28 18:44:583574 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363575 network_delegate.set_auth_credentials(auth_credentials);
3576
[email protected]ef2bf422012-05-11 03:27:093577 TestURLRequestContext context(true);
3578 context.set_network_delegate(&network_delegate);
3579 context.Init();
[email protected]c2911d72011-10-03 22:16:363580
3581 {
3582 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363583 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193584 r->Start();
[email protected]255620da2013-08-19 13:14:293585 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363586
[email protected]f7022f32014-08-21 16:32:193587 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3588 EXPECT_EQ(0, r->status().error());
[email protected]c2911d72011-10-03 22:16:363589
[email protected]f7022f32014-08-21 16:32:193590 EXPECT_EQ(200, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363591 EXPECT_FALSE(d.auth_required_called());
3592 EXPECT_EQ(1, network_delegate.created_requests());
3593 EXPECT_EQ(0, network_delegate.destroyed_requests());
3594 }
3595 EXPECT_EQ(1, network_delegate.destroyed_requests());
3596}
3597
3598// Tests that the network delegate can asynchronously complete OnAuthRequired
3599// by cancelling authentication.
3600TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3601 ASSERT_TRUE(test_server_.Start());
3602
3603 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303604 BlockingNetworkDelegate network_delegate(
3605 BlockingNetworkDelegate::AUTO_CALLBACK);
3606 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363607 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363608 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3609
[email protected]ef2bf422012-05-11 03:27:093610 TestURLRequestContext context(true);
3611 context.set_network_delegate(&network_delegate);
3612 context.Init();
[email protected]c2911d72011-10-03 22:16:363613
3614 {
3615 GURL url(test_server_.GetURL("auth-basic"));
davidben151423e2015-03-23 18:48:363616 scoped_ptr<URLRequest> r(context.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193617 r->Start();
[email protected]255620da2013-08-19 13:14:293618 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363619
[email protected]f7022f32014-08-21 16:32:193620 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3621 EXPECT_EQ(OK, r->status().error());
3622 EXPECT_EQ(401, r->GetResponseCode());
[email protected]c2911d72011-10-03 22:16:363623 EXPECT_FALSE(d.auth_required_called());
3624 EXPECT_EQ(1, network_delegate.created_requests());
3625 EXPECT_EQ(0, network_delegate.destroyed_requests());
3626 }
3627 EXPECT_EQ(1, network_delegate.destroyed_requests());
3628}
3629
[email protected]9045b8822012-01-13 20:35:353630// Tests that we can handle when a network request was canceled while we were
3631// waiting for the network delegate.
3632// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3633TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3634 ASSERT_TRUE(test_server_.Start());
3635
3636 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303637 BlockingNetworkDelegate network_delegate(
3638 BlockingNetworkDelegate::USER_CALLBACK);
3639 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353640
[email protected]ef2bf422012-05-11 03:27:093641 TestURLRequestContext context(true);
3642 context.set_network_delegate(&network_delegate);
3643 context.Init();
[email protected]9045b8822012-01-13 20:35:353644
3645 {
[email protected]f7022f32014-08-21 16:32:193646 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363647 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353648
[email protected]f7022f32014-08-21 16:32:193649 r->Start();
[email protected]255620da2013-08-19 13:14:293650 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303651 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3652 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353653 EXPECT_EQ(0, network_delegate.completed_requests());
3654 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193655 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353656 // Ensure that network delegate is notified.
3657 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193658 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3659 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353660 EXPECT_EQ(1, network_delegate.created_requests());
3661 EXPECT_EQ(0, network_delegate.destroyed_requests());
3662 }
3663 EXPECT_EQ(1, network_delegate.destroyed_requests());
3664}
3665
3666// Tests that we can handle when a network request was canceled while we were
3667// waiting for the network delegate.
3668// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3669TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3670 ASSERT_TRUE(test_server_.Start());
3671
3672 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303673 BlockingNetworkDelegate network_delegate(
3674 BlockingNetworkDelegate::USER_CALLBACK);
3675 network_delegate.set_block_on(
3676 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353677
[email protected]ef2bf422012-05-11 03:27:093678 TestURLRequestContext context(true);
3679 context.set_network_delegate(&network_delegate);
3680 context.Init();
[email protected]9045b8822012-01-13 20:35:353681
3682 {
[email protected]f7022f32014-08-21 16:32:193683 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363684 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353685
[email protected]f7022f32014-08-21 16:32:193686 r->Start();
[email protected]255620da2013-08-19 13:14:293687 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303688 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3689 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353690 EXPECT_EQ(0, network_delegate.completed_requests());
3691 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193692 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353693 // Ensure that network delegate is notified.
3694 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193695 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3696 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353697 EXPECT_EQ(1, network_delegate.created_requests());
3698 EXPECT_EQ(0, network_delegate.destroyed_requests());
3699 }
3700 EXPECT_EQ(1, network_delegate.destroyed_requests());
3701}
3702
3703// Tests that we can handle when a network request was canceled while we were
3704// waiting for the network delegate.
3705// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3706TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3707 ASSERT_TRUE(test_server_.Start());
3708
3709 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303710 BlockingNetworkDelegate network_delegate(
3711 BlockingNetworkDelegate::USER_CALLBACK);
3712 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353713
[email protected]ef2bf422012-05-11 03:27:093714 TestURLRequestContext context(true);
3715 context.set_network_delegate(&network_delegate);
3716 context.Init();
[email protected]9045b8822012-01-13 20:35:353717
3718 {
[email protected]f7022f32014-08-21 16:32:193719 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363720 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353721
[email protected]f7022f32014-08-21 16:32:193722 r->Start();
[email protected]255620da2013-08-19 13:14:293723 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303724 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3725 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353726 EXPECT_EQ(0, network_delegate.completed_requests());
3727 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193728 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353729 // Ensure that network delegate is notified.
3730 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193731 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3732 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353733 EXPECT_EQ(1, network_delegate.created_requests());
3734 EXPECT_EQ(0, network_delegate.destroyed_requests());
3735 }
3736 EXPECT_EQ(1, network_delegate.destroyed_requests());
3737}
3738
3739// Tests that we can handle when a network request was canceled while we were
3740// waiting for the network delegate.
3741// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023742TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353743 ASSERT_TRUE(test_server_.Start());
3744
3745 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303746 BlockingNetworkDelegate network_delegate(
3747 BlockingNetworkDelegate::USER_CALLBACK);
3748 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353749
[email protected]ef2bf422012-05-11 03:27:093750 TestURLRequestContext context(true);
3751 context.set_network_delegate(&network_delegate);
3752 context.Init();
[email protected]9045b8822012-01-13 20:35:353753
3754 {
[email protected]f7022f32014-08-21 16:32:193755 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363756 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]9045b8822012-01-13 20:35:353757
[email protected]f7022f32014-08-21 16:32:193758 r->Start();
[email protected]255620da2013-08-19 13:14:293759 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303760 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3761 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353762 EXPECT_EQ(0, network_delegate.completed_requests());
3763 // Cancel before callback.
[email protected]f7022f32014-08-21 16:32:193764 r->Cancel();
[email protected]9045b8822012-01-13 20:35:353765 // Ensure that network delegate is notified.
3766 EXPECT_EQ(1, network_delegate.completed_requests());
[email protected]f7022f32014-08-21 16:32:193767 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
3768 EXPECT_EQ(ERR_ABORTED, r->status().error());
[email protected]9045b8822012-01-13 20:35:353769 EXPECT_EQ(1, network_delegate.created_requests());
3770 EXPECT_EQ(0, network_delegate.destroyed_requests());
3771 }
3772 EXPECT_EQ(1, network_delegate.destroyed_requests());
3773}
3774
[email protected]95409e12010-08-17 20:07:113775// In this unit test, we're using the HTTPTestServer as a proxy server and
3776// issuing a CONNECT request with the magic host name "www.server-auth.com".
3777// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353778TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113779 ASSERT_TRUE(test_server_.Start());
3780
[email protected]ceefd7fd2012-11-29 00:36:243781 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043782 TestURLRequestContextWithProxy context(
[email protected]2ca01e52013-10-31 22:05:193783 test_server_.host_port_pair().ToString(), &network_delegate);
[email protected]87a09a92011-07-14 15:50:503784
[email protected]dc651782009-02-14 01:45:083785 TestDelegate d;
3786 {
[email protected]f7022f32014-08-21 16:32:193787 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363788 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d));
[email protected]dc651782009-02-14 01:45:083789
[email protected]f7022f32014-08-21 16:32:193790 r->Start();
3791 EXPECT_TRUE(r->is_pending());
[email protected]dc651782009-02-14 01:45:083792
[email protected]255620da2013-08-19 13:14:293793 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083794
[email protected]f7022f32014-08-21 16:32:193795 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
[email protected]d8fc4722014-06-13 13:17:153796 // The proxy server is not set before failure.
[email protected]f7022f32014-08-21 16:32:193797 EXPECT_TRUE(r->proxy_server().IsEmpty());
3798 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
[email protected]dc651782009-02-14 01:45:083799 }
3800}
3801
[email protected]b89290212009-08-14 22:37:353802TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113803 ASSERT_TRUE(test_server_.Start());
3804
initial.commit586acc5fe2008-07-26 22:42:523805 TestDelegate d;
3806 {
[email protected]f7022f32014-08-21 16:32:193807 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363808 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523809
[email protected]f7022f32014-08-21 16:32:193810 r->Start();
3811 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523812
[email protected]255620da2013-08-19 13:14:293813 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523814
3815 EXPECT_EQ(1, d.response_started_count());
3816 EXPECT_FALSE(d.received_data_before_response());
3817 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193818 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193819 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193820 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193821 r->GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163822
[email protected]9e743cd2010-03-16 07:03:533823 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523824 }
initial.commit586acc5fe2008-07-26 22:42:523825}
3826
[email protected]263163f2012-06-14 22:40:343827// This test has the server send a large number of cookies to the client.
3828// To ensure that no number of cookies causes a crash, a galloping binary
3829// search is used to estimate that maximum number of cookies that are accepted
3830// by the browser. Beyond the maximum number, the request will fail with
3831// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303832#if defined(OS_WIN)
3833// http://crbug.com/177916
3834#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3835#else
3836#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3837#endif // defined(OS_WIN)
3838TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343839 ASSERT_TRUE(test_server_.Start());
3840
3841 int lower_bound = 0;
3842 int upper_bound = 1;
3843
3844 // Double the number of cookies until the response header limits are
3845 // exceeded.
3846 while (DoManyCookiesRequest(upper_bound)) {
3847 lower_bound = upper_bound;
3848 upper_bound *= 2;
3849 ASSERT_LT(upper_bound, 1000000);
3850 }
3851
pkasting6b68a162014-12-01 22:10:293852 int tolerance = static_cast<int>(upper_bound * 0.005);
[email protected]263163f2012-06-14 22:40:343853 if (tolerance < 2)
3854 tolerance = 2;
3855
3856 // Perform a binary search to find the highest possible number of cookies,
3857 // within the desired tolerance.
3858 while (upper_bound - lower_bound >= tolerance) {
3859 int num_cookies = (lower_bound + upper_bound) / 2;
3860
3861 if (DoManyCookiesRequest(num_cookies))
3862 lower_bound = num_cookies;
3863 else
3864 upper_bound = num_cookies;
3865 }
3866 // Success: the test did not crash.
3867}
3868
[email protected]b89290212009-08-14 22:37:353869TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113870 ASSERT_TRUE(test_server_.Start());
3871
initial.commit586acc5fe2008-07-26 22:42:523872 TestDelegate d;
3873 {
[email protected]f7022f32014-08-21 16:32:193874 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363875 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
initial.commit586acc5fe2008-07-26 22:42:523876
[email protected]f7022f32014-08-21 16:32:193877 r->Start();
3878 EXPECT_TRUE(r->is_pending());
initial.commit586acc5fe2008-07-26 22:42:523879
[email protected]255620da2013-08-19 13:14:293880 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523881
3882 EXPECT_EQ(1, d.response_started_count());
3883 EXPECT_FALSE(d.received_data_before_response());
3884 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193885 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193886 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:193887 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193888 r->GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523889 }
[email protected]5d7b373e2009-09-02 07:19:033890}
3891
[email protected]79e1fd62013-06-20 06:50:043892TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3893 ASSERT_TRUE(test_server_.Start());
3894
3895 TestDelegate d;
3896 {
3897 GURL test_url(test_server_.GetURL(std::string()));
davidben151423e2015-03-23 18:48:363898 scoped_ptr<URLRequest> r(
3899 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:043900
3901 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:193902 EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
[email protected]79e1fd62013-06-20 06:50:043903
[email protected]f7022f32014-08-21 16:32:193904 r->Start();
3905 EXPECT_TRUE(r->is_pending());
[email protected]79e1fd62013-06-20 06:50:043906
[email protected]255620da2013-08-19 13:14:293907 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043908
3909 EXPECT_EQ(1, d.response_started_count());
3910 EXPECT_FALSE(d.received_data_before_response());
3911 EXPECT_NE(0, d.bytes_received());
3912 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193913 r->GetSocketAddress().host());
[email protected]79e1fd62013-06-20 06:50:043914 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193915 r->GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:043916
3917 EXPECT_TRUE(d.have_full_request_headers());
3918 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3919 }
3920}
3921
[email protected]58e32bb2013-01-21 18:23:253922TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3923 ASSERT_TRUE(test_server_.Start());
3924
3925 TestDelegate d;
3926 {
[email protected]f7022f32014-08-21 16:32:193927 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:363928 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]58e32bb2013-01-21 18:23:253929
[email protected]f7022f32014-08-21 16:32:193930 r->Start();
3931 EXPECT_TRUE(r->is_pending());
[email protected]58e32bb2013-01-21 18:23:253932
[email protected]255620da2013-08-19 13:14:293933 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253934
3935 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:193936 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253937 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3938
3939 EXPECT_EQ(1, d.response_started_count());
3940 EXPECT_FALSE(d.received_data_before_response());
3941 EXPECT_NE(0, d.bytes_received());
3942 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:193943 r->GetSocketAddress().host());
[email protected]58e32bb2013-01-21 18:23:253944 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:193945 r->GetSocketAddress().port());
[email protected]58e32bb2013-01-21 18:23:253946 }
3947}
3948
[email protected]aad63572011-05-24 20:14:393949TEST_F(URLRequestTestHTTP, GetZippedTest) {
3950 ASSERT_TRUE(test_server_.Start());
3951
3952 // Parameter that specifies the Content-Length field in the response:
3953 // C - Compressed length.
3954 // U - Uncompressed length.
3955 // L - Large length (larger than both C & U).
3956 // M - Medium length (between C & U).
3957 // S - Small length (smaller than both C & U).
3958 const char test_parameters[] = "CULMS";
3959 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3960 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443961 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393962 // S has too little data, but we seem to accept it.
3963 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373964 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393965
3966 for (int i = 0; i < num_tests ; i++) {
3967 TestDelegate d;
3968 {
3969 std::string test_file =
3970 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3971 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393972
[email protected]ceefd7fd2012-11-29 00:36:243973 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093974 TestURLRequestContext context(true);
3975 context.set_network_delegate(&network_delegate);
3976 context.Init();
[email protected]87a09a92011-07-14 15:50:503977
[email protected]f7022f32014-08-21 16:32:193978 scoped_ptr<URLRequest> r(context.CreateRequest(
davidben151423e2015-03-23 18:48:363979 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:193980 r->Start();
3981 EXPECT_TRUE(r->is_pending());
[email protected]aad63572011-05-24 20:14:393982
[email protected]255620da2013-08-19 13:14:293983 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393984
3985 EXPECT_EQ(1, d.response_started_count());
3986 EXPECT_FALSE(d.received_data_before_response());
3987 VLOG(1) << " Received " << d.bytes_received() << " bytes"
[email protected]f7022f32014-08-21 16:32:193988 << " status = " << r->status().status()
3989 << " error = " << r->status().error();
[email protected]aad63572011-05-24 20:14:393990 if (test_expect_success[i]) {
[email protected]f7022f32014-08-21 16:32:193991 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status())
[email protected]aad63572011-05-24 20:14:393992 << " Parameter = \"" << test_file << "\"";
3993 } else {
[email protected]f7022f32014-08-21 16:32:193994 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
3995 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r->status().error())
[email protected]aad63572011-05-24 20:14:393996 << " Parameter = \"" << test_file << "\"";
3997 }
3998 }
3999 }
4000}
4001
[email protected]58e32bb2013-01-21 18:23:254002TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
4003 ASSERT_TRUE(test_server_.Start());
4004
[email protected]007b3f82013-04-09 08:46:454005 GURL destination_url = test_server_.GetURL(std::string());
4006 GURL original_url =
4007 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:254008 TestDelegate d;
davidben151423e2015-03-23 18:48:364009 scoped_ptr<URLRequest> req(
4010 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194011 req->Start();
[email protected]255620da2013-08-19 13:14:294012 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254013
4014 EXPECT_EQ(1, d.response_started_count());
4015 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194016 EXPECT_EQ(destination_url, req->url());
4017 EXPECT_EQ(original_url, req->original_url());
4018 ASSERT_EQ(2U, req->url_chain().size());
4019 EXPECT_EQ(original_url, req->url_chain()[0]);
4020 EXPECT_EQ(destination_url, req->url_chain()[1]);
[email protected]58e32bb2013-01-21 18:23:254021
4022 LoadTimingInfo load_timing_info_before_redirect;
4023 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
4024 &load_timing_info_before_redirect));
4025 TestLoadTimingNotReused(load_timing_info_before_redirect,
4026 CONNECT_TIMING_HAS_DNS_TIMES);
4027
4028 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:194029 req->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254030 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4031
4032 // Check that a new socket was used on redirect, since the server does not
4033 // supposed keep-alive sockets, and that the times before the redirect are
4034 // before the ones recorded for the second request.
4035 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
4036 load_timing_info.socket_log_id);
4037 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
4038 load_timing_info.connect_timing.connect_start);
4039}
4040
[email protected]8f1ac082011-04-19 21:14:134041TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
4042 ASSERT_TRUE(test_server_.Start());
4043
[email protected]007b3f82013-04-09 08:46:454044 GURL destination_url = test_server_.GetURL(std::string());
4045 GURL middle_redirect_url =
4046 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:134047 GURL original_url = test_server_.GetURL(
4048 "server-redirect?" + middle_redirect_url.spec());
4049 TestDelegate d;
davidben151423e2015-03-23 18:48:364050 scoped_ptr<URLRequest> req(
4051 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194052 req->Start();
[email protected]255620da2013-08-19 13:14:294053 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:134054
4055 EXPECT_EQ(1, d.response_started_count());
4056 EXPECT_EQ(2, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:194057 EXPECT_EQ(destination_url, req->url());
4058 EXPECT_EQ(original_url, req->original_url());
4059 ASSERT_EQ(3U, req->url_chain().size());
4060 EXPECT_EQ(original_url, req->url_chain()[0]);
4061 EXPECT_EQ(middle_redirect_url, req->url_chain()[1]);
4062 EXPECT_EQ(destination_url, req->url_chain()[2]);
[email protected]8f1ac082011-04-19 21:14:134063}
4064
[email protected]abe1c4a2013-10-25 19:28:514065// First and second pieces of information logged by delegates to URLRequests.
4066const char kFirstDelegateInfo[] = "Wonderful delegate";
4067const char kSecondDelegateInfo[] = "Exciting delegate";
4068
4069// Logs delegate information to a URLRequest. The first string is logged
4070// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
4071// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
4072// another asynchronous call is used to clear the delegate information
4073// before calling a callback. The object then deletes itself.
4074class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
4075 public:
4076 typedef base::Callback<void()> Callback;
4077
4078 // Each time delegate information is added to the URLRequest, the resulting
4079 // load state is checked. The expected load state after each request is
4080 // passed in as an argument.
4081 static void Run(URLRequest* url_request,
4082 LoadState expected_first_load_state,
4083 LoadState expected_second_load_state,
4084 LoadState expected_third_load_state,
4085 const Callback& callback) {
4086 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
4087 url_request,
4088 expected_first_load_state,
4089 expected_second_load_state,
4090 expected_third_load_state,
4091 callback);
4092 logger->Start();
4093 }
4094
4095 // Checks that the log entries, starting with log_position, contain the
4096 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
4097 // recorded. Returns the index of entry after the expected number of
4098 // events this logged, or entries.size() if there aren't enough entries.
4099 static size_t CheckDelegateInfo(
4100 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
4101 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
4102 if (log_position + 3 >= entries.size()) {
4103 ADD_FAILURE() << "Not enough log entries";
4104 return entries.size();
4105 }
4106 std::string delegate_info;
4107 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4108 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4109 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4110 &delegate_info));
4111 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
4112
4113 ++log_position;
4114 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4115 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4116
4117 ++log_position;
4118 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4119 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
4120 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
4121 &delegate_info));
4122 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
4123
4124 ++log_position;
4125 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
4126 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4127
4128 return log_position + 1;
4129 }
4130
[email protected]1826a402014-01-08 15:40:484131 // Find delegate request begin and end messages for OnBeforeNetworkStart.
4132 // Returns the position of the end message.
4133 static size_t ExpectBeforeNetworkEvents(
4134 const CapturingNetLog::CapturedEntryList& entries,
4135 size_t log_position) {
4136 log_position =
4137 ExpectLogContainsSomewhereAfter(entries,
4138 log_position,
4139 NetLog::TYPE_URL_REQUEST_DELEGATE,
4140 NetLog::PHASE_BEGIN);
4141 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
4142 entries[log_position + 1].type);
4143 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
4144 return log_position + 1;
4145 }
4146
[email protected]abe1c4a2013-10-25 19:28:514147 private:
4148 friend class base::RefCounted<AsyncDelegateLogger>;
4149
4150 AsyncDelegateLogger(URLRequest* url_request,
4151 LoadState expected_first_load_state,
4152 LoadState expected_second_load_state,
4153 LoadState expected_third_load_state,
4154 const Callback& callback)
4155 : url_request_(url_request),
4156 expected_first_load_state_(expected_first_load_state),
4157 expected_second_load_state_(expected_second_load_state),
4158 expected_third_load_state_(expected_third_load_state),
4159 callback_(callback) {
4160 }
4161
4162 ~AsyncDelegateLogger() {}
4163
4164 void Start() {
[email protected]f8fe5cf2013-12-04 20:11:534165 url_request_->LogBlockedBy(kFirstDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514166 LoadStateWithParam load_state = url_request_->GetLoadState();
4167 EXPECT_EQ(expected_first_load_state_, load_state.state);
4168 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
4169 base::MessageLoop::current()->PostTask(
4170 FROM_HERE,
4171 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
4172 }
4173
4174 void LogSecondDelegate() {
[email protected]f8fe5cf2013-12-04 20:11:534175 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
[email protected]abe1c4a2013-10-25 19:28:514176 LoadStateWithParam load_state = url_request_->GetLoadState();
4177 EXPECT_EQ(expected_second_load_state_, load_state.state);
4178 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
4179 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4180 } else {
4181 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
4182 }
4183 base::MessageLoop::current()->PostTask(
4184 FROM_HERE,
4185 base::Bind(&AsyncDelegateLogger::LogComplete, this));
4186 }
4187
4188 void LogComplete() {
[email protected]f8fe5cf2013-12-04 20:11:534189 url_request_->LogUnblocked();
[email protected]abe1c4a2013-10-25 19:28:514190 LoadStateWithParam load_state = url_request_->GetLoadState();
4191 EXPECT_EQ(expected_third_load_state_, load_state.state);
4192 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
[email protected]754bd202013-12-18 08:29:084193 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514194 callback_.Run();
4195 }
4196
4197 URLRequest* url_request_;
4198 const int expected_first_load_state_;
4199 const int expected_second_load_state_;
4200 const int expected_third_load_state_;
4201 const Callback callback_;
4202
4203 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
4204};
4205
4206// NetworkDelegate that logs delegate information before a request is started,
4207// before headers are sent, when headers are read, and when auth information
4208// is requested. Uses AsyncDelegateLogger.
4209class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
4210 public:
4211 AsyncLoggingNetworkDelegate() {}
dchengb03027d2014-10-21 12:00:204212 ~AsyncLoggingNetworkDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514213
4214 // NetworkDelegate implementation.
dchengb03027d2014-10-21 12:00:204215 int OnBeforeURLRequest(URLRequest* request,
4216 const CompletionCallback& callback,
4217 GURL* new_url) override {
[email protected]abe1c4a2013-10-25 19:28:514218 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
4219 return RunCallbackAsynchronously(request, callback);
4220 }
4221
dchengb03027d2014-10-21 12:00:204222 int OnBeforeSendHeaders(URLRequest* request,
4223 const CompletionCallback& callback,
4224 HttpRequestHeaders* headers) override {
[email protected]abe1c4a2013-10-25 19:28:514225 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
4226 return RunCallbackAsynchronously(request, callback);
4227 }
4228
dchengb03027d2014-10-21 12:00:204229 int OnHeadersReceived(
[email protected]abe1c4a2013-10-25 19:28:514230 URLRequest* request,
4231 const CompletionCallback& callback,
4232 const HttpResponseHeaders* original_response_headers,
[email protected]5f714132014-03-26 10:41:164233 scoped_refptr<HttpResponseHeaders>* override_response_headers,
mostynbba063d6032014-10-09 11:01:134234 GURL* allowed_unsafe_redirect_url) override {
[email protected]5f714132014-03-26 10:41:164235 TestNetworkDelegate::OnHeadersReceived(request,
4236 callback,
[email protected]abe1c4a2013-10-25 19:28:514237 original_response_headers,
[email protected]5f714132014-03-26 10:41:164238 override_response_headers,
4239 allowed_unsafe_redirect_url);
[email protected]abe1c4a2013-10-25 19:28:514240 return RunCallbackAsynchronously(request, callback);
4241 }
4242
dchengb03027d2014-10-21 12:00:204243 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
[email protected]abe1c4a2013-10-25 19:28:514244 URLRequest* request,
4245 const AuthChallengeInfo& auth_info,
4246 const AuthCallback& callback,
mostynbba063d6032014-10-09 11:01:134247 AuthCredentials* credentials) override {
[email protected]abe1c4a2013-10-25 19:28:514248 AsyncDelegateLogger::Run(
4249 request,
4250 LOAD_STATE_WAITING_FOR_DELEGATE,
4251 LOAD_STATE_WAITING_FOR_DELEGATE,
4252 LOAD_STATE_WAITING_FOR_DELEGATE,
4253 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4254 callback, credentials));
4255 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4256 }
4257
4258 private:
4259 static int RunCallbackAsynchronously(
4260 URLRequest* request,
4261 const CompletionCallback& callback) {
4262 AsyncDelegateLogger::Run(
4263 request,
4264 LOAD_STATE_WAITING_FOR_DELEGATE,
4265 LOAD_STATE_WAITING_FOR_DELEGATE,
4266 LOAD_STATE_WAITING_FOR_DELEGATE,
4267 base::Bind(callback, OK));
4268 return ERR_IO_PENDING;
4269 }
4270
4271 static void SetAuthAndResume(const AuthCallback& callback,
4272 AuthCredentials* credentials) {
4273 *credentials = AuthCredentials(kUser, kSecret);
4274 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4275 }
4276
4277 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4278};
4279
4280// URLRequest::Delegate that logs delegate information when the headers
4281// are received, when each read completes, and during redirects. Uses
4282// AsyncDelegateLogger. Can optionally cancel a request in any phase.
4283//
4284// Inherits from TestDelegate to reuse the TestDelegate code to handle
4285// advancing to the next step in most cases, as well as cancellation.
4286class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4287 public:
4288 enum CancelStage {
4289 NO_CANCEL = 0,
4290 CANCEL_ON_RECEIVED_REDIRECT,
4291 CANCEL_ON_RESPONSE_STARTED,
4292 CANCEL_ON_READ_COMPLETED
4293 };
4294
4295 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4296 : cancel_stage_(cancel_stage) {
4297 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4298 set_cancel_in_received_redirect(true);
4299 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4300 set_cancel_in_response_started(true);
4301 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4302 set_cancel_in_received_data(true);
4303 }
dchengb03027d2014-10-21 12:00:204304 ~AsyncLoggingUrlRequestDelegate() override {}
[email protected]abe1c4a2013-10-25 19:28:514305
4306 // URLRequest::Delegate implementation:
dchengb03027d2014-10-21 12:00:204307 void OnReceivedRedirect(URLRequest* request,
4308 const RedirectInfo& redirect_info,
4309 bool* defer_redirect) override {
[email protected]abe1c4a2013-10-25 19:28:514310 *defer_redirect = true;
4311 AsyncDelegateLogger::Run(
4312 request,
4313 LOAD_STATE_WAITING_FOR_DELEGATE,
4314 LOAD_STATE_WAITING_FOR_DELEGATE,
4315 LOAD_STATE_WAITING_FOR_DELEGATE,
4316 base::Bind(
4317 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
[email protected]cba24642014-08-15 20:49:594318 base::Unretained(this), request, redirect_info));
[email protected]abe1c4a2013-10-25 19:28:514319 }
4320
dchengb03027d2014-10-21 12:00:204321 void OnResponseStarted(URLRequest* request) override {
[email protected]abe1c4a2013-10-25 19:28:514322 AsyncDelegateLogger::Run(
4323 request,
4324 LOAD_STATE_WAITING_FOR_DELEGATE,
4325 LOAD_STATE_WAITING_FOR_DELEGATE,
4326 LOAD_STATE_WAITING_FOR_DELEGATE,
4327 base::Bind(
4328 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4329 base::Unretained(this), request));
4330 }
4331
dchengb03027d2014-10-21 12:00:204332 void OnReadCompleted(URLRequest* request, int bytes_read) override {
[email protected]abe1c4a2013-10-25 19:28:514333 AsyncDelegateLogger::Run(
4334 request,
4335 LOAD_STATE_IDLE,
4336 LOAD_STATE_IDLE,
4337 LOAD_STATE_IDLE,
4338 base::Bind(
4339 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4340 base::Unretained(this), request, bytes_read));
4341 }
4342
4343 private:
4344 void OnReceivedRedirectLoggingComplete(URLRequest* request,
[email protected]cba24642014-08-15 20:49:594345 const RedirectInfo& redirect_info) {
[email protected]abe1c4a2013-10-25 19:28:514346 bool defer_redirect = false;
[email protected]cba24642014-08-15 20:49:594347 TestDelegate::OnReceivedRedirect(request, redirect_info, &defer_redirect);
[email protected]abe1c4a2013-10-25 19:28:514348 // FollowDeferredRedirect should not be called after cancellation.
4349 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4350 return;
4351 if (!defer_redirect)
4352 request->FollowDeferredRedirect();
4353 }
4354
4355 void OnResponseStartedLoggingComplete(URLRequest* request) {
4356 // The parent class continues the request.
4357 TestDelegate::OnResponseStarted(request);
4358 }
4359
4360 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4361 // The parent class continues the request.
4362 TestDelegate::OnReadCompleted(request, bytes_read);
4363 }
4364
4365 const CancelStage cancel_stage_;
4366
4367 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4368};
4369
4370// Tests handling of delegate info before a request starts.
4371TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4372 ASSERT_TRUE(test_server_.Start());
4373
4374 TestDelegate request_delegate;
4375 TestURLRequestContext context(true);
4376 context.set_network_delegate(NULL);
4377 context.set_net_log(&net_log_);
4378 context.Init();
4379
4380 {
davidben151423e2015-03-23 18:48:364381 scoped_ptr<URLRequest> r(
4382 context.CreateRequest(test_server_.GetURL("empty.html"),
4383 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194384 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514385 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084386 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514387
4388 AsyncDelegateLogger::Run(
[email protected]f7022f32014-08-21 16:32:194389 r.get(),
[email protected]abe1c4a2013-10-25 19:28:514390 LOAD_STATE_WAITING_FOR_DELEGATE,
4391 LOAD_STATE_WAITING_FOR_DELEGATE,
4392 LOAD_STATE_IDLE,
[email protected]f7022f32014-08-21 16:32:194393 base::Bind(&URLRequest::Start, base::Unretained(r.get())));
[email protected]abe1c4a2013-10-25 19:28:514394
4395 base::RunLoop().Run();
4396
[email protected]f7022f32014-08-21 16:32:194397 EXPECT_EQ(200, r->GetResponseCode());
4398 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514399 }
4400
4401 CapturingNetLog::CapturedEntryList entries;
4402 net_log_.GetEntries(&entries);
4403 size_t log_position = ExpectLogContainsSomewhereAfter(
4404 entries,
4405 0,
4406 NetLog::TYPE_DELEGATE_INFO,
4407 NetLog::PHASE_BEGIN);
4408
4409 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4410
4411 // Nothing else should add any delegate info to the request.
4412 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4413 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4414}
4415
4416// Tests handling of delegate info from a network delegate.
4417TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4418 ASSERT_TRUE(test_server_.Start());
4419
4420 TestDelegate request_delegate;
4421 AsyncLoggingNetworkDelegate network_delegate;
4422 TestURLRequestContext context(true);
4423 context.set_network_delegate(&network_delegate);
4424 context.set_net_log(&net_log_);
4425 context.Init();
4426
4427 {
davidben151423e2015-03-23 18:48:364428 scoped_ptr<URLRequest> r(
4429 context.CreateRequest(test_server_.GetURL("simple.html"),
4430 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194431 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514432 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084433 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514434
[email protected]f7022f32014-08-21 16:32:194435 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514436 base::RunLoop().Run();
4437
[email protected]f7022f32014-08-21 16:32:194438 EXPECT_EQ(200, r->GetResponseCode());
4439 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514440 EXPECT_EQ(1, network_delegate.created_requests());
4441 EXPECT_EQ(0, network_delegate.destroyed_requests());
4442 }
4443 EXPECT_EQ(1, network_delegate.destroyed_requests());
4444
4445 size_t log_position = 0;
4446 CapturingNetLog::CapturedEntryList entries;
4447 net_log_.GetEntries(&entries);
4448 for (size_t i = 0; i < 3; ++i) {
4449 log_position = ExpectLogContainsSomewhereAfter(
4450 entries,
4451 log_position + 1,
4452 NetLog::TYPE_URL_REQUEST_DELEGATE,
4453 NetLog::PHASE_BEGIN);
4454
4455 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4456 log_position + 1);
4457
4458 ASSERT_LT(log_position, entries.size());
4459 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4460 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484461
4462 if (i == 1) {
4463 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4464 entries, log_position + 1);
4465 }
[email protected]abe1c4a2013-10-25 19:28:514466 }
4467
4468 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4469 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4470}
4471
4472// Tests handling of delegate info from a network delegate in the case of an
4473// HTTP redirect.
4474TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4475 ASSERT_TRUE(test_server_.Start());
4476
4477 TestDelegate request_delegate;
4478 AsyncLoggingNetworkDelegate network_delegate;
4479 TestURLRequestContext context(true);
4480 context.set_network_delegate(&network_delegate);
4481 context.set_net_log(&net_log_);
4482 context.Init();
4483
4484 {
[email protected]f7022f32014-08-21 16:32:194485 scoped_ptr<URLRequest> r(context.CreateRequest(
4486 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364487 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194488 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514489 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084490 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514491
[email protected]f7022f32014-08-21 16:32:194492 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514493 base::RunLoop().Run();
4494
[email protected]f7022f32014-08-21 16:32:194495 EXPECT_EQ(200, r->GetResponseCode());
4496 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514497 EXPECT_EQ(2, network_delegate.created_requests());
4498 EXPECT_EQ(0, network_delegate.destroyed_requests());
4499 }
4500 EXPECT_EQ(1, network_delegate.destroyed_requests());
4501
4502 size_t log_position = 0;
4503 CapturingNetLog::CapturedEntryList entries;
4504 net_log_.GetEntries(&entries);
4505 // The NetworkDelegate logged information in OnBeforeURLRequest,
4506 // OnBeforeSendHeaders, and OnHeadersReceived.
4507 for (size_t i = 0; i < 3; ++i) {
4508 log_position = ExpectLogContainsSomewhereAfter(
4509 entries,
4510 log_position + 1,
4511 NetLog::TYPE_URL_REQUEST_DELEGATE,
4512 NetLog::PHASE_BEGIN);
4513
4514 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4515 log_position + 1);
4516
4517 ASSERT_LT(log_position, entries.size());
4518 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4519 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484520
4521 if (i == 1) {
4522 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4523 entries, log_position + 1);
4524 }
[email protected]abe1c4a2013-10-25 19:28:514525 }
4526
4527 // The URLRequest::Delegate then gets informed about the redirect.
4528 log_position = ExpectLogContainsSomewhereAfter(
4529 entries,
4530 log_position + 1,
4531 NetLog::TYPE_URL_REQUEST_DELEGATE,
4532 NetLog::PHASE_BEGIN);
4533
4534 // The NetworkDelegate logged information in the same three events as before.
4535 for (size_t i = 0; i < 3; ++i) {
4536 log_position = ExpectLogContainsSomewhereAfter(
4537 entries,
4538 log_position + 1,
4539 NetLog::TYPE_URL_REQUEST_DELEGATE,
4540 NetLog::PHASE_BEGIN);
4541
4542 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4543 log_position + 1);
4544
4545 ASSERT_LT(log_position, entries.size());
4546 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4547 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4548 }
4549
4550 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4551 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4552}
4553
4554// Tests handling of delegate info from a network delegate in the case of HTTP
4555// AUTH.
4556TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4557 ASSERT_TRUE(test_server_.Start());
4558
4559 TestDelegate request_delegate;
4560 AsyncLoggingNetworkDelegate network_delegate;
4561 TestURLRequestContext context(true);
4562 context.set_network_delegate(&network_delegate);
4563 context.set_net_log(&net_log_);
4564 context.Init();
4565
4566 {
davidben151423e2015-03-23 18:48:364567 scoped_ptr<URLRequest> r(
4568 context.CreateRequest(test_server_.GetURL("auth-basic"),
4569 DEFAULT_PRIORITY, &request_delegate));
[email protected]f7022f32014-08-21 16:32:194570 LoadStateWithParam load_state = r->GetLoadState();
[email protected]abe1c4a2013-10-25 19:28:514571 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
[email protected]754bd202013-12-18 08:29:084572 EXPECT_EQ(base::string16(), load_state.param);
[email protected]abe1c4a2013-10-25 19:28:514573
[email protected]f7022f32014-08-21 16:32:194574 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514575 base::RunLoop().Run();
4576
[email protected]f7022f32014-08-21 16:32:194577 EXPECT_EQ(200, r->GetResponseCode());
4578 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514579 EXPECT_EQ(1, network_delegate.created_requests());
4580 EXPECT_EQ(0, network_delegate.destroyed_requests());
4581 }
4582 EXPECT_EQ(1, network_delegate.destroyed_requests());
4583
4584 size_t log_position = 0;
4585 CapturingNetLog::CapturedEntryList entries;
4586 net_log_.GetEntries(&entries);
4587 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4588 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4589 // OnBeforeURLRequest and OnBeforeSendHeaders.
4590 for (size_t i = 0; i < 6; ++i) {
4591 log_position = ExpectLogContainsSomewhereAfter(
4592 entries,
4593 log_position + 1,
4594 NetLog::TYPE_URL_REQUEST_DELEGATE,
4595 NetLog::PHASE_BEGIN);
4596
4597 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4598 log_position + 1);
4599
4600 ASSERT_LT(log_position, entries.size());
4601 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4602 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
[email protected]1826a402014-01-08 15:40:484603
4604 if (i == 1) {
4605 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4606 entries, log_position + 1);
4607 }
[email protected]abe1c4a2013-10-25 19:28:514608 }
4609
4610 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4611 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4612}
4613
4614// Tests handling of delegate info from a URLRequest::Delegate.
4615TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4616 ASSERT_TRUE(test_server_.Start());
4617
4618 AsyncLoggingUrlRequestDelegate request_delegate(
4619 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4620 TestURLRequestContext context(true);
4621 context.set_network_delegate(NULL);
4622 context.set_net_log(&net_log_);
4623 context.Init();
4624
4625 {
4626 // A chunked response with delays between chunks is used to make sure that
4627 // attempts by the URLRequest delegate to log information while reading the
4628 // body are ignored. Since they are ignored, this test is robust against
[email protected]1826a402014-01-08 15:40:484629 // the possibility of multiple reads being combined in the unlikely event
[email protected]abe1c4a2013-10-25 19:28:514630 // that it occurs.
[email protected]f7022f32014-08-21 16:32:194631 scoped_ptr<URLRequest> r(context.CreateRequest(
4632 test_server_.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364633 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194634 LoadStateWithParam load_state = r->GetLoadState();
4635 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514636 base::RunLoop().Run();
4637
[email protected]f7022f32014-08-21 16:32:194638 EXPECT_EQ(200, r->GetResponseCode());
4639 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514640 }
4641
4642 CapturingNetLog::CapturedEntryList entries;
4643 net_log_.GetEntries(&entries);
4644
[email protected]1826a402014-01-08 15:40:484645 size_t log_position = 0;
4646
4647 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4648 entries, log_position);
4649
[email protected]abe1c4a2013-10-25 19:28:514650 // The delegate info should only have been logged on header complete. Other
4651 // times it should silently be ignored.
[email protected]1826a402014-01-08 15:40:484652 log_position =
4653 ExpectLogContainsSomewhereAfter(entries,
4654 log_position + 1,
4655 NetLog::TYPE_URL_REQUEST_DELEGATE,
4656 NetLog::PHASE_BEGIN);
[email protected]abe1c4a2013-10-25 19:28:514657
4658 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4659 log_position + 1);
4660
4661 ASSERT_LT(log_position, entries.size());
4662 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4663 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4664
4665 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4666 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4667 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4668 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4669}
4670
4671// Tests handling of delegate info from a URLRequest::Delegate in the case of
4672// an HTTP redirect.
4673TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4674 ASSERT_TRUE(test_server_.Start());
4675
4676 AsyncLoggingUrlRequestDelegate request_delegate(
4677 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4678 TestURLRequestContext context(true);
4679 context.set_network_delegate(NULL);
4680 context.set_net_log(&net_log_);
4681 context.Init();
4682
4683 {
[email protected]f7022f32014-08-21 16:32:194684 scoped_ptr<URLRequest> r(context.CreateRequest(
4685 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364686 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194687 LoadStateWithParam load_state = r->GetLoadState();
4688 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514689 base::RunLoop().Run();
4690
[email protected]f7022f32014-08-21 16:32:194691 EXPECT_EQ(200, r->GetResponseCode());
4692 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514693 }
4694
4695 CapturingNetLog::CapturedEntryList entries;
4696 net_log_.GetEntries(&entries);
4697
4698 // Delegate info should only have been logged in OnReceivedRedirect and
4699 // OnResponseStarted.
4700 size_t log_position = 0;
4701 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484702 if (i == 0) {
4703 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4704 entries, log_position) + 1;
4705 }
4706
[email protected]abe1c4a2013-10-25 19:28:514707 log_position = ExpectLogContainsSomewhereAfter(
4708 entries,
4709 log_position,
4710 NetLog::TYPE_URL_REQUEST_DELEGATE,
4711 NetLog::PHASE_BEGIN);
4712
4713 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4714 log_position + 1);
4715
4716 ASSERT_LT(log_position, entries.size());
4717 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4718 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4719 }
4720
4721 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4722 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4723 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4724 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4725}
4726
4727// Tests handling of delegate info from a URLRequest::Delegate in the case of
4728// an HTTP redirect, with cancellation at various points.
4729TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4730 ASSERT_TRUE(test_server_.Start());
4731
4732 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4733 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4734 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4735 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4736 };
4737
4738 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4739 ++test_case) {
4740 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4741 TestURLRequestContext context(true);
4742 CapturingNetLog net_log;
4743 context.set_network_delegate(NULL);
4744 context.set_net_log(&net_log);
4745 context.Init();
4746
4747 {
[email protected]f7022f32014-08-21 16:32:194748 scoped_ptr<URLRequest> r(context.CreateRequest(
4749 test_server_.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:364750 &request_delegate));
[email protected]f7022f32014-08-21 16:32:194751 LoadStateWithParam load_state = r->GetLoadState();
4752 r->Start();
[email protected]abe1c4a2013-10-25 19:28:514753 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194754 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]abe1c4a2013-10-25 19:28:514755 }
4756
4757 CapturingNetLog::CapturedEntryList entries;
4758 net_log.GetEntries(&entries);
4759
4760 // Delegate info is always logged in both OnReceivedRedirect and
4761 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4762 // OnResponseStarted delegate call is after cancellation, but logging is
4763 // still currently supported in that call.
4764 size_t log_position = 0;
4765 for (int i = 0; i < 2; ++i) {
[email protected]1826a402014-01-08 15:40:484766 if (i == 0) {
4767 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4768 entries, log_position) + 1;
4769 }
4770
[email protected]abe1c4a2013-10-25 19:28:514771 log_position = ExpectLogContainsSomewhereAfter(
4772 entries,
4773 log_position,
4774 NetLog::TYPE_URL_REQUEST_DELEGATE,
4775 NetLog::PHASE_BEGIN);
4776
4777 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4778 log_position + 1);
4779
4780 ASSERT_LT(log_position, entries.size());
4781 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4782 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4783 }
4784
4785 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4786 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4787 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4788 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4789 }
4790}
4791
[email protected]847c0fa92012-11-06 16:37:424792namespace {
4793
4794const char kExtraHeader[] = "Allow-Snafu";
4795const char kExtraValue[] = "fubar";
4796
4797class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204798 void OnReceivedRedirect(URLRequest* request,
4799 const RedirectInfo& redirect_info,
4800 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594801 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]847c0fa92012-11-06 16:37:424802 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4803 }
4804};
4805
4806} // namespace
4807
4808TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4809 ASSERT_TRUE(test_server_.Start());
4810
4811 GURL destination_url = test_server_.GetURL(
4812 "echoheader?" + std::string(kExtraHeader));
4813 GURL original_url = test_server_.GetURL(
4814 "server-redirect?" + destination_url.spec());
4815 RedirectWithAdditionalHeadersDelegate d;
davidben151423e2015-03-23 18:48:364816 scoped_ptr<URLRequest> req(
4817 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194818 req->Start();
[email protected]255620da2013-08-19 13:14:294819 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424820
4821 std::string value;
[email protected]f7022f32014-08-21 16:32:194822 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]847c0fa92012-11-06 16:37:424823 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4824 EXPECT_EQ(kExtraValue, value);
[email protected]f7022f32014-08-21 16:32:194825 EXPECT_FALSE(req->is_pending());
4826 EXPECT_FALSE(req->is_redirecting());
[email protected]847c0fa92012-11-06 16:37:424827 EXPECT_EQ(kExtraValue, d.data_received());
4828}
4829
[email protected]251a1b92012-11-13 11:01:094830namespace {
4831
4832const char kExtraHeaderToRemove[] = "To-Be-Removed";
4833
4834class RedirectWithHeaderRemovalDelegate : public TestDelegate {
dchengb03027d2014-10-21 12:00:204835 void OnReceivedRedirect(URLRequest* request,
4836 const RedirectInfo& redirect_info,
4837 bool* defer_redirect) override {
[email protected]cba24642014-08-15 20:49:594838 TestDelegate::OnReceivedRedirect(request, redirect_info, defer_redirect);
[email protected]251a1b92012-11-13 11:01:094839 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4840 }
4841};
4842
4843} // namespace
4844
4845TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4846 ASSERT_TRUE(test_server_.Start());
4847
4848 GURL destination_url = test_server_.GetURL(
4849 "echoheader?" + std::string(kExtraHeaderToRemove));
4850 GURL original_url = test_server_.GetURL(
4851 "server-redirect?" + destination_url.spec());
4852 RedirectWithHeaderRemovalDelegate d;
davidben151423e2015-03-23 18:48:364853 scoped_ptr<URLRequest> req(
4854 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194855 req->SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4856 req->Start();
[email protected]255620da2013-08-19 13:14:294857 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094858
4859 std::string value;
[email protected]f7022f32014-08-21 16:32:194860 const HttpRequestHeaders& headers = req->extra_request_headers();
[email protected]251a1b92012-11-13 11:01:094861 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
[email protected]f7022f32014-08-21 16:32:194862 EXPECT_FALSE(req->is_pending());
4863 EXPECT_FALSE(req->is_redirecting());
[email protected]251a1b92012-11-13 11:01:094864 EXPECT_EQ("None", d.data_received());
4865}
4866
[email protected]316c1e5e2012-09-12 15:17:444867TEST_F(URLRequestTestHTTP, CancelTest) {
4868 TestDelegate d;
4869 {
[email protected]f7022f32014-08-21 16:32:194870 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364871 GURL("http://www.google.com/"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444872
[email protected]f7022f32014-08-21 16:32:194873 r->Start();
4874 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444875
[email protected]f7022f32014-08-21 16:32:194876 r->Cancel();
[email protected]316c1e5e2012-09-12 15:17:444877
[email protected]255620da2013-08-19 13:14:294878 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444879
4880 // We expect to receive OnResponseStarted even though the request has been
4881 // cancelled.
4882 EXPECT_EQ(1, d.response_started_count());
4883 EXPECT_EQ(0, d.bytes_received());
4884 EXPECT_FALSE(d.received_data_before_response());
4885 }
4886}
4887
4888TEST_F(URLRequestTestHTTP, CancelTest2) {
4889 ASSERT_TRUE(test_server_.Start());
4890
4891 TestDelegate d;
4892 {
[email protected]f7022f32014-08-21 16:32:194893 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364894 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444895
4896 d.set_cancel_in_response_started(true);
4897
[email protected]f7022f32014-08-21 16:32:194898 r->Start();
4899 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444900
[email protected]255620da2013-08-19 13:14:294901 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444902
4903 EXPECT_EQ(1, d.response_started_count());
4904 EXPECT_EQ(0, d.bytes_received());
4905 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194906 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444907 }
4908}
4909
4910TEST_F(URLRequestTestHTTP, CancelTest3) {
4911 ASSERT_TRUE(test_server_.Start());
4912
4913 TestDelegate d;
4914 {
[email protected]f7022f32014-08-21 16:32:194915 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364916 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444917
4918 d.set_cancel_in_received_data(true);
4919
[email protected]f7022f32014-08-21 16:32:194920 r->Start();
4921 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444922
[email protected]255620da2013-08-19 13:14:294923 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444924
4925 EXPECT_EQ(1, d.response_started_count());
4926 // There is no guarantee about how much data was received
4927 // before the cancel was issued. It could have been 0 bytes,
4928 // or it could have been all the bytes.
4929 // EXPECT_EQ(0, d.bytes_received());
4930 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:194931 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444932 }
4933}
4934
4935TEST_F(URLRequestTestHTTP, CancelTest4) {
4936 ASSERT_TRUE(test_server_.Start());
4937
4938 TestDelegate d;
4939 {
[email protected]f7022f32014-08-21 16:32:194940 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364941 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:444942
[email protected]f7022f32014-08-21 16:32:194943 r->Start();
4944 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:444945
4946 // The request will be implicitly canceled when it is destroyed. The
4947 // test delegate must not post a quit message when this happens because
4948 // this test doesn't actually have a message loop. The quit message would
4949 // get put on this thread's message queue and the next test would exit
4950 // early, causing problems.
4951 d.set_quit_on_complete(false);
4952 }
4953 // expect things to just cleanup properly.
4954
4955 // we won't actually get a received reponse here because we've never run the
4956 // message loop
4957 EXPECT_FALSE(d.received_data_before_response());
4958 EXPECT_EQ(0, d.bytes_received());
4959}
4960
4961TEST_F(URLRequestTestHTTP, CancelTest5) {
4962 ASSERT_TRUE(test_server_.Start());
4963
4964 // populate cache
4965 {
4966 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194967 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364968 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194969 r->Start();
[email protected]255620da2013-08-19 13:14:294970 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:194971 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444972 }
4973
4974 // cancel read from cache (see bug 990242)
4975 {
4976 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:194977 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:364978 test_server_.GetURL("cachetime"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:194979 r->Start();
4980 r->Cancel();
[email protected]255620da2013-08-19 13:14:294981 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444982
[email protected]f7022f32014-08-21 16:32:194983 EXPECT_EQ(URLRequestStatus::CANCELED, r->status().status());
[email protected]316c1e5e2012-09-12 15:17:444984 EXPECT_EQ(1, d.response_started_count());
4985 EXPECT_EQ(0, d.bytes_received());
4986 EXPECT_FALSE(d.received_data_before_response());
4987 }
4988}
4989
4990TEST_F(URLRequestTestHTTP, PostTest) {
4991 ASSERT_TRUE(test_server_.Start());
4992 HTTPUploadDataOperationTest("POST");
4993}
4994
4995TEST_F(URLRequestTestHTTP, PutTest) {
4996 ASSERT_TRUE(test_server_.Start());
4997 HTTPUploadDataOperationTest("PUT");
4998}
4999
5000TEST_F(URLRequestTestHTTP, PostEmptyTest) {
5001 ASSERT_TRUE(test_server_.Start());
5002
5003 TestDelegate d;
5004 {
[email protected]f7022f32014-08-21 16:32:195005 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365006 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195007 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445008
[email protected]f7022f32014-08-21 16:32:195009 r->Start();
5010 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445011
[email protected]255620da2013-08-19 13:14:295012 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445013
[email protected]329b68b2012-11-14 17:54:275014 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195015 << "request failed: " << r->status().status()
5016 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445017
5018 EXPECT_FALSE(d.received_data_before_response());
5019 EXPECT_TRUE(d.data_received().empty());
5020 }
5021}
5022
5023TEST_F(URLRequestTestHTTP, PostFileTest) {
5024 ASSERT_TRUE(test_server_.Start());
5025
5026 TestDelegate d;
5027 {
[email protected]f7022f32014-08-21 16:32:195028 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365029 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195030 r->set_method("POST");
[email protected]316c1e5e2012-09-12 15:17:445031
[email protected]6cdfd7f2013-02-08 20:40:155032 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:445033 PathService::Get(base::DIR_EXE, &dir);
[email protected]37b3c1992014-03-11 20:59:025034 base::SetCurrentDirectory(dir);
[email protected]316c1e5e2012-09-12 15:17:445035
[email protected]f288ef02012-12-15 20:28:285036 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:445037
[email protected]6cdfd7f2013-02-08 20:40:155038 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445039 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5040 path = path.Append(FILE_PATH_LITERAL("net"));
5041 path = path.Append(FILE_PATH_LITERAL("data"));
5042 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5043 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:365044 element_readers.push_back(
5045 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
5046 path,
5047 0,
5048 kuint64max,
5049 base::Time()));
mmenkecbc2b712014-10-09 20:29:075050 r->set_upload(make_scoped_ptr<UploadDataStream>(
5051 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:445052
[email protected]f7022f32014-08-21 16:32:195053 r->Start();
5054 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445055
[email protected]255620da2013-08-19 13:14:295056 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445057
pkasting6b68a162014-12-01 22:10:295058 int64 size64 = 0;
5059 ASSERT_EQ(true, base::GetFileSize(path, &size64));
5060 ASSERT_LE(size64, std::numeric_limits<int>::max());
5061 int size = static_cast<int>(size64);
[email protected]4356f0f2013-04-07 00:58:175062 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:445063
[email protected]7600d0b2013-12-08 21:43:305064 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:445065
[email protected]329b68b2012-11-14 17:54:275066 ASSERT_EQ(1, d.response_started_count())
[email protected]f7022f32014-08-21 16:32:195067 << "request failed: " << r->status().status()
5068 << ", error: " << r->status().error();
[email protected]316c1e5e2012-09-12 15:17:445069
5070 EXPECT_FALSE(d.received_data_before_response());
5071
[email protected]329b68b2012-11-14 17:54:275072 EXPECT_EQ(size, d.bytes_received());
5073 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:445074 }
5075}
5076
[email protected]999dd8c2013-11-12 06:45:545077TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
5078 ASSERT_TRUE(test_server_.Start());
5079
5080 TestDelegate d;
5081 {
[email protected]f7022f32014-08-21 16:32:195082 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365083 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195084 r->set_method("POST");
[email protected]999dd8c2013-11-12 06:45:545085
5086 ScopedVector<UploadElementReader> element_readers;
5087
5088 element_readers.push_back(new UploadFileElementReader(
5089 base::MessageLoopProxy::current().get(),
5090 base::FilePath(FILE_PATH_LITERAL(
5091 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
5092 0,
5093 kuint64max,
5094 base::Time()));
mmenkecbc2b712014-10-09 20:29:075095 r->set_upload(make_scoped_ptr<UploadDataStream>(
5096 new ElementsUploadDataStream(element_readers.Pass(), 0)));
[email protected]999dd8c2013-11-12 06:45:545097
[email protected]f7022f32014-08-21 16:32:195098 r->Start();
5099 EXPECT_TRUE(r->is_pending());
[email protected]999dd8c2013-11-12 06:45:545100
5101 base::RunLoop().Run();
5102
[email protected]999dd8c2013-11-12 06:45:545103 EXPECT_TRUE(d.request_failed());
5104 EXPECT_FALSE(d.received_data_before_response());
5105 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195106 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5107 EXPECT_EQ(ERR_FILE_NOT_FOUND, r->status().error());
[email protected]999dd8c2013-11-12 06:45:545108 }
5109}
5110
[email protected]316c1e5e2012-09-12 15:17:445111TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
5112 ASSERT_TRUE(test_server_.Start());
5113
5114 TestDelegate d;
5115 {
[email protected]f7022f32014-08-21 16:32:195116 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365117 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195118 r->EnableChunkedUpload();
5119 r->set_method("POST");
5120 AddChunksToUpload(r.get());
5121 r->Start();
5122 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445123
[email protected]255620da2013-08-19 13:14:295124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445125
[email protected]f7022f32014-08-21 16:32:195126 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445127 }
5128}
5129
[email protected]329b68b2012-11-14 17:54:275130TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
5131 ASSERT_TRUE(test_server_.Start());
5132
5133 TestDelegate d;
5134 {
[email protected]f7022f32014-08-21 16:32:195135 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365136 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195137 r->EnableChunkedUpload();
5138 r->set_method("POST");
5139 r->Start();
5140 EXPECT_TRUE(r->is_pending());
5141 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295142 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:275143
[email protected]f7022f32014-08-21 16:32:195144 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]329b68b2012-11-14 17:54:275145 }
5146}
5147
[email protected]316c1e5e2012-09-12 15:17:445148TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
5149 ASSERT_TRUE(test_server_.Start());
5150
5151 TestDelegate d;
5152 {
[email protected]f7022f32014-08-21 16:32:195153 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365154 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195155 r->EnableChunkedUpload();
5156 r->set_method("POST");
5157 r->Start();
5158 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:445159
[email protected]255620da2013-08-19 13:14:295160 base::RunLoop().RunUntilIdle();
[email protected]f7022f32014-08-21 16:32:195161 AddChunksToUpload(r.get());
[email protected]255620da2013-08-19 13:14:295162 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445163
[email protected]f7022f32014-08-21 16:32:195164 VerifyReceivedDataMatchesChunks(r.get(), &d);
[email protected]316c1e5e2012-09-12 15:17:445165 }
5166}
5167
5168TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
5169 ASSERT_TRUE(test_server_.Start());
5170
5171 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195172 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365173 test_server_.GetURL("files/with-headers.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195174 req->Start();
[email protected]255620da2013-08-19 13:14:295175 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445176
[email protected]f7022f32014-08-21 16:32:195177 const HttpResponseHeaders* headers = req->response_headers();
[email protected]316c1e5e2012-09-12 15:17:445178
5179 // Simple sanity check that response_info() accesses the same data.
[email protected]f7022f32014-08-21 16:32:195180 EXPECT_EQ(headers, req->response_info().headers.get());
[email protected]316c1e5e2012-09-12 15:17:445181
5182 std::string header;
5183 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
5184 EXPECT_EQ("private", header);
5185
5186 header.clear();
5187 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
5188 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
5189
5190 // The response has two "X-Multiple-Entries" headers.
5191 // This verfies our output has them concatenated together.
5192 header.clear();
5193 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
5194 EXPECT_EQ("a, b", header);
5195}
5196
[email protected]242d8562012-10-30 21:20:465197TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:225198 SpawnedTestServer::SSLOptions ssl_options;
5199 SpawnedTestServer https_test_server(
5200 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465201 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155202 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465203 ASSERT_TRUE(https_test_server.Start());
5204
5205 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195206 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365207 https_test_server.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY,
5208 &d));
[email protected]f7022f32014-08-21 16:32:195209 request->Start();
[email protected]255620da2013-08-19 13:14:295210 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465211
5212 TransportSecurityState* security_state =
5213 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465214 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265215 EXPECT_TRUE(security_state->GetDynamicDomainState(
5216 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465217 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265218 domain_state.sts.upgrade_mode);
5219 EXPECT_TRUE(domain_state.sts.include_subdomains);
5220 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275221#if defined(OS_ANDROID)
5222 // Android's CertVerifyProc does not (yet) handle pins.
5223#else
5224 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5225#endif
5226}
5227
5228// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5229// reject HPKP headers, and a test setting only HPKP headers will fail (no
5230// DomainState present because header rejected).
5231#if defined(OS_ANDROID)
5232#define MAYBE_ProcessPKP DISABLED_ProcessPKP
5233#else
5234#define MAYBE_ProcessPKP ProcessPKP
5235#endif
5236
5237// Tests that enabling HPKP on a domain does not affect the HSTS
5238// validity/expiration.
5239TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5240 SpawnedTestServer::SSLOptions ssl_options;
5241 SpawnedTestServer https_test_server(
5242 SpawnedTestServer::TYPE_HTTPS,
5243 ssl_options,
5244 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5245 ASSERT_TRUE(https_test_server.Start());
5246
5247 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195248 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365249 https_test_server.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY,
5250 &d));
[email protected]f7022f32014-08-21 16:32:195251 request->Start();
[email protected]255620da2013-08-19 13:14:295252 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275253
5254 TransportSecurityState* security_state =
5255 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275256 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265257 EXPECT_TRUE(security_state->GetDynamicDomainState(
5258 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275259 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
[email protected]9e6968d2014-05-07 21:46:265260 domain_state.sts.upgrade_mode);
5261 EXPECT_FALSE(domain_state.sts.include_subdomains);
5262 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275263 EXPECT_TRUE(domain_state.HasPublicKeyPins());
[email protected]9e6968d2014-05-07 21:46:265264 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]242d8562012-10-30 21:20:465265}
5266
5267TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:225268 SpawnedTestServer::SSLOptions ssl_options;
5269 SpawnedTestServer https_test_server(
5270 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:465271 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:155272 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:465273 ASSERT_TRUE(https_test_server.Start());
5274
5275 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195276 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]242d8562012-10-30 21:20:465277 https_test_server.GetURL("files/hsts-multiple-headers.html"),
davidben151423e2015-03-23 18:48:365278 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195279 request->Start();
[email protected]255620da2013-08-19 13:14:295280 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:465281
5282 // We should have set parameters from the first header, not the second.
5283 TransportSecurityState* security_state =
5284 default_context_.transport_security_state();
[email protected]242d8562012-10-30 21:20:465285 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265286 EXPECT_TRUE(security_state->GetDynamicDomainState(
5287 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]242d8562012-10-30 21:20:465288 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265289 domain_state.sts.upgrade_mode);
5290 EXPECT_FALSE(domain_state.sts.include_subdomains);
5291 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]242d8562012-10-30 21:20:465292}
5293
[email protected]9f972ec2013-04-10 20:24:365294TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:225295 SpawnedTestServer::SSLOptions ssl_options;
5296 SpawnedTestServer https_test_server(
5297 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:365298 ssl_options,
5299 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5300 ASSERT_TRUE(https_test_server.Start());
5301
5302 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195303 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]9f972ec2013-04-10 20:24:365304 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
davidben151423e2015-03-23 18:48:365305 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195306 request->Start();
[email protected]255620da2013-08-19 13:14:295307 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:365308
5309 // We should have set parameters from the first header, not the second.
5310 TransportSecurityState* security_state =
5311 default_context_.transport_security_state();
[email protected]9f972ec2013-04-10 20:24:365312 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265313 EXPECT_TRUE(security_state->GetDynamicDomainState(
5314 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]9f972ec2013-04-10 20:24:365315 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265316 domain_state.sts.upgrade_mode);
[email protected]9f972ec2013-04-10 20:24:365317#if defined(OS_ANDROID)
5318 // Android's CertVerifyProc does not (yet) handle pins.
5319#else
5320 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5321#endif
[email protected]9e6968d2014-05-07 21:46:265322 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]9f972ec2013-04-10 20:24:365323
[email protected]a165f092013-06-12 16:10:055324 // Even though there is an HSTS header asserting includeSubdomains, it is
5325 // the *second* such header, and we MUST process only the first.
[email protected]9e6968d2014-05-07 21:46:265326 EXPECT_FALSE(domain_state.sts.include_subdomains);
[email protected]a165f092013-06-12 16:10:055327 // includeSubdomains does not occur in the test HPKP header.
[email protected]9e6968d2014-05-07 21:46:265328 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]9f972ec2013-04-10 20:24:365329}
5330
[email protected]37fd55fb2013-06-29 13:13:275331// Tests that when multiple HPKP headers are present, asserting different
5332// policies, that only the first such policy is processed.
5333TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5334 SpawnedTestServer::SSLOptions ssl_options;
5335 SpawnedTestServer https_test_server(
5336 SpawnedTestServer::TYPE_HTTPS,
5337 ssl_options,
5338 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5339 ASSERT_TRUE(https_test_server.Start());
5340
5341 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195342 scoped_ptr<URLRequest> request(default_context_.CreateRequest(
[email protected]37fd55fb2013-06-29 13:13:275343 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
davidben151423e2015-03-23 18:48:365344 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195345 request->Start();
[email protected]255620da2013-08-19 13:14:295346 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:275347
5348 TransportSecurityState* security_state =
5349 default_context_.transport_security_state();
[email protected]37fd55fb2013-06-29 13:13:275350 TransportSecurityState::DomainState domain_state;
[email protected]9e6968d2014-05-07 21:46:265351 EXPECT_TRUE(security_state->GetDynamicDomainState(
5352 SpawnedTestServer::kLocalhost, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:275353 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
[email protected]9e6968d2014-05-07 21:46:265354 domain_state.sts.upgrade_mode);
[email protected]37fd55fb2013-06-29 13:13:275355#if defined(OS_ANDROID)
5356 // Android's CertVerifyProc does not (yet) handle pins.
5357#else
5358 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5359#endif
[email protected]9e6968d2014-05-07 21:46:265360 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
[email protected]37fd55fb2013-06-29 13:13:275361
[email protected]9e6968d2014-05-07 21:46:265362 EXPECT_TRUE(domain_state.sts.include_subdomains);
5363 EXPECT_FALSE(domain_state.pkp.include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:275364}
5365
[email protected]316c1e5e2012-09-12 15:17:445366TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5367 ASSERT_TRUE(test_server_.Start());
5368
5369 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195370 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5371 test_server_.GetURL("files/content-type-normalization.html"),
davidben151423e2015-03-23 18:48:365372 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195373 req->Start();
[email protected]255620da2013-08-19 13:14:295374 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445375
5376 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:195377 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:445378 EXPECT_EQ("text/html", mime_type);
5379
5380 std::string charset;
[email protected]f7022f32014-08-21 16:32:195381 req->GetCharset(&charset);
[email protected]316c1e5e2012-09-12 15:17:445382 EXPECT_EQ("utf-8", charset);
[email protected]f7022f32014-08-21 16:32:195383 req->Cancel();
[email protected]316c1e5e2012-09-12 15:17:445384}
5385
[email protected]02494ec2014-05-07 15:05:295386TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
[email protected]e0f35c92013-05-08 16:04:345387 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
[email protected]e0f35c92013-05-08 16:04:345388 GURL data_url("data:,foo");
[email protected]e0f35c92013-05-08 16:04:345389 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:025390 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345391
5392 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505393 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:345394}
5395
[email protected]02494ec2014-05-07 15:05:295396#if !defined(DISABLE_FILE_SUPPORT)
5397TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5398 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5399 GURL file_url("file:///foo.txt");
5400 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5401 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5402
5403 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
bengr1bf8e942014-11-07 01:36:505404 EXPECT_FALSE(job_factory_->IsSafeRedirectTarget(file_url));
[email protected]02494ec2014-05-07 15:05:295405}
5406
[email protected]588614c22013-08-16 00:09:025407TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:445408 ASSERT_TRUE(test_server_.Start());
5409
5410 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195411 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365412 test_server_.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY,
5413 &d));
[email protected]f7022f32014-08-21 16:32:195414 req->Start();
[email protected]255620da2013-08-19 13:14:295415 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445416
[email protected]f7022f32014-08-21 16:32:195417 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5418 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445419}
[email protected]02494ec2014-05-07 15:05:295420#endif // !defined(DISABLE_FILE_SUPPORT)
[email protected]316c1e5e2012-09-12 15:17:445421
[email protected]588614c22013-08-16 00:09:025422TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5423 ASSERT_TRUE(test_server_.Start());
5424
5425 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195426 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365427 test_server_.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY,
5428 &d));
[email protected]f7022f32014-08-21 16:32:195429 req->Start();
[email protected]588614c22013-08-16 00:09:025430 base::MessageLoop::current()->Run();
5431
[email protected]f7022f32014-08-21 16:32:195432 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5433 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req->status().error());
[email protected]588614c22013-08-16 00:09:025434}
5435
[email protected]316c1e5e2012-09-12 15:17:445436TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5437 ASSERT_TRUE(test_server_.Start());
5438
5439 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195440 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
5441 test_server_.GetURL("files/redirect-to-invalid-url.html"),
davidben151423e2015-03-23 18:48:365442 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195443 req->Start();
[email protected]255620da2013-08-19 13:14:295444 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445445
[email protected]f7022f32014-08-21 16:32:195446 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
5447 EXPECT_EQ(ERR_INVALID_URL, req->status().error());
[email protected]316c1e5e2012-09-12 15:17:445448}
5449
[email protected]e50efea2014-03-24 18:41:005450// Make sure redirects are cached, despite not reading their bodies.
5451TEST_F(URLRequestTestHTTP, CacheRedirect) {
5452 ASSERT_TRUE(test_server_.Start());
5453 GURL redirect_url =
5454 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5455
5456 {
5457 TestDelegate d;
davidben151423e2015-03-23 18:48:365458 scoped_ptr<URLRequest> req(
5459 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195460 req->Start();
[email protected]e50efea2014-03-24 18:41:005461 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195462 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005463 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195464 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005465 }
5466
5467 {
5468 TestDelegate d;
5469 d.set_quit_on_redirect(true);
davidben151423e2015-03-23 18:48:365470 scoped_ptr<URLRequest> req(
5471 default_context_.CreateRequest(redirect_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195472 req->Start();
[email protected]e50efea2014-03-24 18:41:005473 base::RunLoop().Run();
5474
5475 EXPECT_EQ(1, d.received_redirect_count());
5476 EXPECT_EQ(0, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195477 EXPECT_TRUE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005478
[email protected]f7022f32014-08-21 16:32:195479 req->FollowDeferredRedirect();
[email protected]e50efea2014-03-24 18:41:005480 base::RunLoop().Run();
5481 EXPECT_EQ(1, d.received_redirect_count());
5482 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:195483 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5484 EXPECT_EQ(test_server_.GetURL("echo"), req->url());
[email protected]e50efea2014-03-24 18:41:005485 }
5486}
5487
5488// Make sure a request isn't cached when a NetworkDelegate forces a redirect
5489// when the headers are read, since the body won't have been read.
5490TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5491 ASSERT_TRUE(test_server_.Start());
5492 // URL that is normally cached.
5493 GURL initial_url = test_server_.GetURL("cachetime");
5494
5495 {
5496 // Set up the TestNetworkDelegate tp force a redirect.
5497 GURL redirect_to_url = test_server_.GetURL("echo");
5498 default_network_delegate_.set_redirect_on_headers_received_url(
5499 redirect_to_url);
5500
5501 TestDelegate d;
davidben151423e2015-03-23 18:48:365502 scoped_ptr<URLRequest> req(
5503 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195504 req->Start();
[email protected]e50efea2014-03-24 18:41:005505 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:195506 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]e50efea2014-03-24 18:41:005507 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195508 EXPECT_EQ(redirect_to_url, req->url());
[email protected]e50efea2014-03-24 18:41:005509 }
5510
5511 {
5512 TestDelegate d;
davidben151423e2015-03-23 18:48:365513 scoped_ptr<URLRequest> req(
5514 default_context_.CreateRequest(initial_url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195515 req->Start();
[email protected]e50efea2014-03-24 18:41:005516 base::RunLoop().Run();
5517
[email protected]f7022f32014-08-21 16:32:195518 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
5519 EXPECT_FALSE(req->was_cached());
[email protected]e50efea2014-03-24 18:41:005520 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195521 EXPECT_EQ(initial_url, req->url());
[email protected]e50efea2014-03-24 18:41:005522 }
5523}
5524
[email protected]5f714132014-03-26 10:41:165525// Tests that redirection to an unsafe URL is allowed when it has been marked as
5526// safe.
5527TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5528 ASSERT_TRUE(test_server_.Start());
5529
5530 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5531 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5532 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5533
5534 TestDelegate d;
5535 {
[email protected]f7022f32014-08-21 16:32:195536 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365537 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165538
[email protected]f7022f32014-08-21 16:32:195539 r->Start();
[email protected]5f714132014-03-26 10:41:165540 base::RunLoop().Run();
5541
[email protected]f7022f32014-08-21 16:32:195542 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
[email protected]5f714132014-03-26 10:41:165543
[email protected]f7022f32014-08-21 16:32:195544 EXPECT_EQ(2U, r->url_chain().size());
5545 EXPECT_EQ(OK, r->status().error());
5546 EXPECT_EQ(unsafe_url, r->url());
[email protected]5f714132014-03-26 10:41:165547 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5548 }
5549}
5550
5551// Tests that a redirect to a different unsafe URL is blocked, even after adding
5552// some other URL to the whitelist.
5553TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5554 ASSERT_TRUE(test_server_.Start());
5555
5556 GURL unsafe_url("data:text/html,something");
5557 GURL different_unsafe_url("data:text/html,something-else");
5558 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5559 default_network_delegate_.set_allowed_unsafe_redirect_url(
5560 different_unsafe_url);
5561
5562 TestDelegate d;
5563 {
[email protected]f7022f32014-08-21 16:32:195564 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365565 test_server_.GetURL("whatever"), DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165566
[email protected]f7022f32014-08-21 16:32:195567 r->Start();
[email protected]5f714132014-03-26 10:41:165568 base::RunLoop().Run();
5569
[email protected]f7022f32014-08-21 16:32:195570 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
5571 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r->status().error());
[email protected]5f714132014-03-26 10:41:165572 }
5573}
5574
[email protected]5f714132014-03-26 10:41:165575// Redirects from an URL with fragment to an unsafe URL with fragment should
5576// be allowed, and the reference fragment of the target URL should be preserved.
5577TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5578 ASSERT_TRUE(test_server_.Start());
5579
5580 GURL original_url(test_server_.GetURL("original#fragment1"));
5581 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5582 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5583
5584 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5585 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5586
5587 TestDelegate d;
5588 {
davidben151423e2015-03-23 18:48:365589 scoped_ptr<URLRequest> r(
5590 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165591
[email protected]f7022f32014-08-21 16:32:195592 r->Start();
[email protected]5f714132014-03-26 10:41:165593 base::RunLoop().Run();
5594
[email protected]f7022f32014-08-21 16:32:195595 EXPECT_EQ(2U, r->url_chain().size());
5596 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5597 EXPECT_EQ(OK, r->status().error());
5598 EXPECT_EQ(original_url, r->original_url());
5599 EXPECT_EQ(expected_url, r->url());
[email protected]5f714132014-03-26 10:41:165600 }
5601}
5602
5603// When a delegate has specified a safe redirect URL, but it does not match the
5604// redirect target, then do not prevent the reference fragment from being added.
[email protected]f878230e2014-04-03 15:36:145605TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
[email protected]5f714132014-03-26 10:41:165606 ASSERT_TRUE(test_server_.Start());
5607
5608 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5609 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5610 GURL redirect_url(test_server_.GetURL("target"));
5611 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5612
5613 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5614 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5615
5616 TestDelegate d;
5617 {
davidben151423e2015-03-23 18:48:365618 scoped_ptr<URLRequest> r(
5619 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]5f714132014-03-26 10:41:165620
[email protected]f7022f32014-08-21 16:32:195621 r->Start();
[email protected]5f714132014-03-26 10:41:165622 base::RunLoop().Run();
5623
[email protected]f7022f32014-08-21 16:32:195624 EXPECT_EQ(2U, r->url_chain().size());
5625 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5626 EXPECT_EQ(OK, r->status().error());
5627 EXPECT_EQ(original_url, r->original_url());
5628 EXPECT_EQ(expected_redirect_url, r->url());
[email protected]5f714132014-03-26 10:41:165629 }
5630}
5631
[email protected]f878230e2014-04-03 15:36:145632// When a delegate has specified a safe redirect URL, assume that the redirect
5633// URL should not be changed. In particular, the reference fragment should not
5634// be modified.
5635TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5636 ASSERT_TRUE(test_server_.Start());
5637
5638 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5639 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5640
5641 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5642 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5643
5644 TestDelegate d;
5645 {
davidben151423e2015-03-23 18:48:365646 scoped_ptr<URLRequest> r(
5647 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145648
[email protected]f7022f32014-08-21 16:32:195649 r->Start();
[email protected]f878230e2014-04-03 15:36:145650 base::RunLoop().Run();
5651
[email protected]f7022f32014-08-21 16:32:195652 EXPECT_EQ(2U, r->url_chain().size());
5653 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5654 EXPECT_EQ(OK, r->status().error());
5655 EXPECT_EQ(original_url, r->original_url());
5656 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145657 }
5658}
5659
5660// When a URLRequestRedirectJob is created, the redirection must be followed and
5661// the reference fragment of the target URL must not be modified.
5662TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5663 ASSERT_TRUE(test_server_.Start());
5664
5665 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5666 GURL redirect_url(test_server_.GetURL("echo"));
5667
5668 TestDelegate d;
davidben151423e2015-03-23 18:48:365669 scoped_ptr<URLRequest> r(
5670 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:145671
5672 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:195673 r.get(), &default_network_delegate_, redirect_url,
[email protected]f878230e2014-04-03 15:36:145674 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5675 AddTestInterceptor()->set_main_intercept_job(job);
5676
[email protected]f7022f32014-08-21 16:32:195677 r->Start();
[email protected]f878230e2014-04-03 15:36:145678 base::RunLoop().Run();
5679
[email protected]f7022f32014-08-21 16:32:195680 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
5681 EXPECT_EQ(OK, r->status().error());
5682 EXPECT_EQ(original_url, r->original_url());
5683 EXPECT_EQ(redirect_url, r->url());
[email protected]f878230e2014-04-03 15:36:145684}
5685
[email protected]316c1e5e2012-09-12 15:17:445686TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5687 ASSERT_TRUE(test_server_.Start());
5688
5689 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195690 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365691 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195692 req->SetReferrer("http://user:[email protected]/");
5693 req->Start();
[email protected]255620da2013-08-19 13:14:295694 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445695
5696 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5697}
5698
[email protected]99ecf6e2013-04-10 22:46:135699TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5700 ASSERT_TRUE(test_server_.Start());
5701
5702 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195703 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365704 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195705 req->SetReferrer("http://foo.com/test#fragment");
5706 req->Start();
[email protected]255620da2013-08-19 13:14:295707 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135708
5709 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5710}
5711
5712TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5713 ASSERT_TRUE(test_server_.Start());
5714
5715 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195716 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365717 test_server_.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195718 req->SetReferrer("http://foo.com/test#fragment");
5719 req->SetReferrer("");
5720 req->Start();
[email protected]255620da2013-08-19 13:14:295721 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:135722
5723 EXPECT_EQ(std::string("None"), d.data_received());
5724}
5725
[email protected]1826a402014-01-08 15:40:485726// Defer network start and then resume, checking that the request was a success
5727// and bytes were received.
5728TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5729 ASSERT_TRUE(test_server_.Start());
5730
5731 TestDelegate d;
5732 {
5733 d.set_quit_on_network_start(true);
5734 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365735 scoped_ptr<URLRequest> req(
5736 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485737
[email protected]f7022f32014-08-21 16:32:195738 req->Start();
[email protected]1826a402014-01-08 15:40:485739 base::RunLoop().Run();
5740
5741 EXPECT_EQ(1, d.received_before_network_start_count());
5742 EXPECT_EQ(0, d.response_started_count());
5743
[email protected]f7022f32014-08-21 16:32:195744 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485745 base::RunLoop().Run();
5746
5747 EXPECT_EQ(1, d.response_started_count());
5748 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195749 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485750 }
5751}
5752
5753// Check that OnBeforeNetworkStart is only called once even if there is a
5754// redirect.
5755TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5756 ASSERT_TRUE(test_server_.Start());
5757
5758 TestDelegate d;
5759 {
5760 d.set_quit_on_redirect(true);
5761 d.set_quit_on_network_start(true);
[email protected]f7022f32014-08-21 16:32:195762 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365763 test_server_.GetURL("server-redirect?echo"), DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485764
[email protected]f7022f32014-08-21 16:32:195765 req->Start();
[email protected]1826a402014-01-08 15:40:485766 base::RunLoop().Run();
5767
5768 EXPECT_EQ(1, d.received_before_network_start_count());
5769 EXPECT_EQ(0, d.response_started_count());
5770 EXPECT_EQ(0, d.received_redirect_count());
5771
[email protected]f7022f32014-08-21 16:32:195772 req->ResumeNetworkStart();
[email protected]1826a402014-01-08 15:40:485773 base::RunLoop().Run();
5774
5775 EXPECT_EQ(1, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:195776 req->FollowDeferredRedirect();
[email protected]1826a402014-01-08 15:40:485777 base::RunLoop().Run();
5778
5779 // Check that the redirect's new network transaction does not get propagated
5780 // to a second OnBeforeNetworkStart() notification.
5781 EXPECT_EQ(1, d.received_before_network_start_count());
5782
5783 EXPECT_EQ(1, d.response_started_count());
5784 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195785 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]1826a402014-01-08 15:40:485786 }
5787}
5788
5789// Cancel the request after learning that the request would use the network.
5790TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5791 ASSERT_TRUE(test_server_.Start());
5792
5793 TestDelegate d;
5794 {
5795 d.set_quit_on_network_start(true);
5796 GURL test_url(test_server_.GetURL("echo"));
davidben151423e2015-03-23 18:48:365797 scoped_ptr<URLRequest> req(
5798 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]1826a402014-01-08 15:40:485799
[email protected]f7022f32014-08-21 16:32:195800 req->Start();
[email protected]1826a402014-01-08 15:40:485801 base::RunLoop().Run();
5802
5803 EXPECT_EQ(1, d.received_before_network_start_count());
5804 EXPECT_EQ(0, d.response_started_count());
5805
[email protected]f7022f32014-08-21 16:32:195806 req->Cancel();
[email protected]1826a402014-01-08 15:40:485807 base::RunLoop().Run();
5808
5809 EXPECT_EQ(1, d.response_started_count());
5810 EXPECT_EQ(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:195811 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]1826a402014-01-08 15:40:485812 }
5813}
5814
[email protected]316c1e5e2012-09-12 15:17:445815TEST_F(URLRequestTestHTTP, CancelRedirect) {
5816 ASSERT_TRUE(test_server_.Start());
5817
5818 TestDelegate d;
5819 {
5820 d.set_cancel_in_received_redirect(true);
[email protected]f7022f32014-08-21 16:32:195821 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365822 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195823 req->Start();
[email protected]255620da2013-08-19 13:14:295824 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445825
5826 EXPECT_EQ(1, d.response_started_count());
5827 EXPECT_EQ(0, d.bytes_received());
5828 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195829 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445830 }
5831}
5832
5833TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5834 ASSERT_TRUE(test_server_.Start());
5835
5836 TestDelegate d;
5837 {
5838 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:045839 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:365840 scoped_ptr<URLRequest> req(
5841 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:045842
[email protected]f7022f32014-08-21 16:32:195843 req->Start();
[email protected]255620da2013-08-19 13:14:295844 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445845
5846 EXPECT_EQ(1, d.received_redirect_count());
5847
[email protected]f7022f32014-08-21 16:32:195848 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295849 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445850
5851 EXPECT_EQ(1, d.response_started_count());
5852 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195853 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445854
[email protected]6cdfd7f2013-02-08 20:40:155855 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:445856 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5857 path = path.Append(FILE_PATH_LITERAL("net"));
5858 path = path.Append(FILE_PATH_LITERAL("data"));
5859 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5860 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5861
5862 std::string contents;
[email protected]82f84b92013-08-30 18:23:505863 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:445864 EXPECT_EQ(contents, d.data_received());
5865 }
5866}
5867
[email protected]79e1fd62013-06-20 06:50:045868TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5869 ASSERT_TRUE(test_server_.Start());
5870
5871 TestDelegate d;
5872 {
5873 d.set_quit_on_redirect(true);
5874 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
davidben151423e2015-03-23 18:48:365875 scoped_ptr<URLRequest> req(
5876 default_context_.CreateRequest(test_url, DEFAULT_PRIORITY, &d));
[email protected]79e1fd62013-06-20 06:50:045877
5878 EXPECT_FALSE(d.have_full_request_headers());
5879
[email protected]f7022f32014-08-21 16:32:195880 req->Start();
[email protected]255620da2013-08-19 13:14:295881 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045882
5883 EXPECT_EQ(1, d.received_redirect_count());
5884 EXPECT_TRUE(d.have_full_request_headers());
5885 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5886 d.ClearFullRequestHeaders();
5887
[email protected]f7022f32014-08-21 16:32:195888 req->FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:295889 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:045890
5891 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5892 EXPECT_EQ(1, d.response_started_count());
5893 EXPECT_TRUE(d.have_full_request_headers());
5894 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5895 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195896 EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
[email protected]79e1fd62013-06-20 06:50:045897
5898 base::FilePath path;
5899 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5900 path = path.Append(FILE_PATH_LITERAL("net"));
5901 path = path.Append(FILE_PATH_LITERAL("data"));
5902 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5903 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5904
5905 std::string contents;
[email protected]82f84b92013-08-30 18:23:505906 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045907 EXPECT_EQ(contents, d.data_received());
5908 }
5909}
5910
[email protected]316c1e5e2012-09-12 15:17:445911TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5912 ASSERT_TRUE(test_server_.Start());
5913
5914 TestDelegate d;
5915 {
5916 d.set_quit_on_redirect(true);
[email protected]f7022f32014-08-21 16:32:195917 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365918 test_server_.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:195919 req->Start();
[email protected]255620da2013-08-19 13:14:295920 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445921
5922 EXPECT_EQ(1, d.received_redirect_count());
5923
[email protected]f7022f32014-08-21 16:32:195924 req->Cancel();
[email protected]255620da2013-08-19 13:14:295925 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445926
5927 EXPECT_EQ(1, d.response_started_count());
5928 EXPECT_EQ(0, d.bytes_received());
5929 EXPECT_FALSE(d.received_data_before_response());
[email protected]f7022f32014-08-21 16:32:195930 EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
[email protected]316c1e5e2012-09-12 15:17:445931 }
5932}
5933
5934TEST_F(URLRequestTestHTTP, VaryHeader) {
5935 ASSERT_TRUE(test_server_.Start());
5936
[email protected]3b23a222013-05-15 21:33:255937 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445938 {
5939 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195940 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365941 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445942 HttpRequestHeaders headers;
5943 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:195944 req->SetExtraRequestHeaders(headers);
5945 req->Start();
[email protected]255620da2013-08-19 13:14:295946 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255947
5948 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195949 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255950 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445951 }
5952
[email protected]3b23a222013-05-15 21:33:255953 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445954 {
5955 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195956 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365957 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445958 HttpRequestHeaders headers;
5959 headers.SetHeader("foo", "1");
[email protected]f7022f32014-08-21 16:32:195960 req->SetExtraRequestHeaders(headers);
5961 req->Start();
[email protected]255620da2013-08-19 13:14:295962 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445963
[email protected]f7022f32014-08-21 16:32:195964 EXPECT_TRUE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:255965
5966 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195967 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255968 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445969 }
5970
[email protected]3b23a222013-05-15 21:33:255971 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445972 {
5973 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:195974 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365975 test_server_.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:445976 HttpRequestHeaders headers;
5977 headers.SetHeader("foo", "2");
[email protected]f7022f32014-08-21 16:32:195978 req->SetExtraRequestHeaders(headers);
5979 req->Start();
[email protected]255620da2013-08-19 13:14:295980 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445981
[email protected]f7022f32014-08-21 16:32:195982 EXPECT_FALSE(req->was_cached());
[email protected]3b23a222013-05-15 21:33:255983
5984 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:195985 req->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255986 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445987 }
5988}
5989
5990TEST_F(URLRequestTestHTTP, BasicAuth) {
5991 ASSERT_TRUE(test_server_.Start());
5992
5993 // populate the cache
5994 {
5995 TestDelegate d;
5996 d.set_credentials(AuthCredentials(kUser, kSecret));
5997
[email protected]f7022f32014-08-21 16:32:195998 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:365999 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196000 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446001
[email protected]255620da2013-08-19 13:14:296002 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446003
6004 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6005 }
6006
6007 // repeat request with end-to-end validation. since auth-basic results in a
6008 // cachable page, we expect this test to result in a 304. in which case, the
6009 // response should be fetched from the cache.
6010 {
6011 TestDelegate d;
6012 d.set_credentials(AuthCredentials(kUser, kSecret));
6013
[email protected]f7022f32014-08-21 16:32:196014 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366015 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196016 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6017 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446018
[email protected]255620da2013-08-19 13:14:296019 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446020
6021 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6022
6023 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196024 EXPECT_TRUE(r->was_cached());
[email protected]316c1e5e2012-09-12 15:17:446025 }
6026}
6027
6028// Check that Set-Cookie headers in 401 responses are respected.
6029// http://crbug.com/6450
6030TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
6031 ASSERT_TRUE(test_server_.Start());
6032
6033 GURL url_requiring_auth =
6034 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
6035
6036 // Request a page that will give a 401 containing a Set-Cookie header.
6037 // Verify that when the transaction is restarted, it includes the new cookie.
6038 {
[email protected]ceefd7fd2012-11-29 00:36:246039 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446040 TestURLRequestContext context(true);
6041 context.set_network_delegate(&network_delegate);
6042 context.Init();
6043
6044 TestDelegate d;
6045 d.set_credentials(AuthCredentials(kUser, kSecret));
6046
davidben151423e2015-03-23 18:48:366047 scoped_ptr<URLRequest> r(
6048 context.CreateRequest(url_requiring_auth, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196049 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446050
[email protected]255620da2013-08-19 13:14:296051 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446052
6053 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6054
6055 // Make sure we sent the cookie in the restarted transaction.
6056 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6057 != std::string::npos);
6058 }
6059
6060 // Same test as above, except this time the restart is initiated earlier
6061 // (without user intervention since identity is embedded in the URL).
6062 {
[email protected]ceefd7fd2012-11-29 00:36:246063 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:446064 TestURLRequestContext context(true);
6065 context.set_network_delegate(&network_delegate);
6066 context.Init();
6067
6068 TestDelegate d;
6069
6070 GURL::Replacements replacements;
mgiuca77752c32015-02-05 07:31:186071 replacements.SetUsernameStr("user2");
6072 replacements.SetPasswordStr("secret");
[email protected]316c1e5e2012-09-12 15:17:446073 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
6074
davidben151423e2015-03-23 18:48:366075 scoped_ptr<URLRequest> r(
6076 context.CreateRequest(url_with_identity, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196077 r->Start();
[email protected]316c1e5e2012-09-12 15:17:446078
[email protected]255620da2013-08-19 13:14:296079 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446080
6081 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
6082
6083 // Make sure we sent the cookie in the restarted transaction.
6084 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
6085 != std::string::npos);
6086 }
6087}
6088
[email protected]58e32bb2013-01-21 18:23:256089// Tests that load timing works as expected with auth and the cache.
6090TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
6091 ASSERT_TRUE(test_server_.Start());
6092
6093 // populate the cache
6094 {
6095 TestDelegate d;
6096 d.set_credentials(AuthCredentials(kUser, kSecret));
6097
[email protected]f7022f32014-08-21 16:32:196098 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366099 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196100 r->Start();
[email protected]58e32bb2013-01-21 18:23:256101
[email protected]255620da2013-08-19 13:14:296102 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256103
6104 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6105
6106 LoadTimingInfo load_timing_info_before_auth;
6107 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
6108 &load_timing_info_before_auth));
6109 TestLoadTimingNotReused(load_timing_info_before_auth,
6110 CONNECT_TIMING_HAS_DNS_TIMES);
6111
6112 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196113 r->GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:256114 // The test server does not support keep alive sockets, so the second
6115 // request with auth should use a new socket.
6116 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
6117 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
6118 load_timing_info.socket_log_id);
6119 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
6120 load_timing_info.connect_timing.connect_start);
6121 }
6122
[email protected]3b23a222013-05-15 21:33:256123 // Repeat request with end-to-end validation. Since auth-basic results in a
6124 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:256125 // response should be fetched from the cache.
6126 {
6127 TestDelegate d;
6128 d.set_credentials(AuthCredentials(kUser, kSecret));
6129
[email protected]f7022f32014-08-21 16:32:196130 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366131 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196132 r->SetLoadFlags(LOAD_VALIDATE_CACHE);
6133 r->Start();
[email protected]58e32bb2013-01-21 18:23:256134
[email protected]255620da2013-08-19 13:14:296135 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:256136
6137 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
6138
6139 // Should be the same cached document.
[email protected]f7022f32014-08-21 16:32:196140 EXPECT_TRUE(r->was_cached());
[email protected]58e32bb2013-01-21 18:23:256141
[email protected]3b23a222013-05-15 21:33:256142 // Since there was a request that went over the wire, the load timing
6143 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:256144 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:196145 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256146 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:256147 }
6148}
6149
[email protected]316c1e5e2012-09-12 15:17:446150// In this test, we do a POST which the server will 302 redirect.
6151// The subsequent transaction should use GET, and should not send the
6152// Content-Type header.
6153// http://code.google.com/p/chromium/issues/detail?id=843
6154TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
6155 ASSERT_TRUE(test_server_.Start());
6156
6157 const char kData[] = "hello world";
6158
6159 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196160 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366161 test_server_.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196162 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076163 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446164
6165 // Set headers (some of which are specific to the POST).
6166 HttpRequestHeaders headers;
6167 headers.AddHeadersFromString(
6168 "Content-Type: multipart/form-data; "
6169 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
6170 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
6171 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
6172 "Accept-Language: en-US,en\r\n"
6173 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
6174 "Content-Length: 11\r\n"
6175 "Origin: http://localhost:1337/");
[email protected]f7022f32014-08-21 16:32:196176 req->SetExtraRequestHeaders(headers);
6177 req->Start();
[email protected]255620da2013-08-19 13:14:296178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446179
6180 std::string mime_type;
[email protected]f7022f32014-08-21 16:32:196181 req->GetMimeType(&mime_type);
[email protected]316c1e5e2012-09-12 15:17:446182 EXPECT_EQ("text/html", mime_type);
6183
6184 const std::string& data = d.data_received();
6185
6186 // Check that the post-specific headers were stripped:
6187 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6188 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6189 EXPECT_FALSE(ContainsString(data, "Origin:"));
6190
6191 // These extra request headers should not have been stripped.
6192 EXPECT_TRUE(ContainsString(data, "Accept:"));
6193 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6194 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6195}
6196
jww5fe460ff2015-03-28 00:22:516197// The following tests check that we handle mutating the request for HTTP
6198// redirects as expected.
6199// See https://crbug.com/56373, https://crbug.com/102130, and
6200// https://crbug.com/465517.
[email protected]316c1e5e2012-09-12 15:17:446201
6202TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6203 ASSERT_TRUE(test_server_.Start());
6204
6205 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
jww5fe460ff2015-03-28 00:22:516206 const GURL https_redirect_url =
6207 test_server_.GetURL("files/redirect301-to-https");
[email protected]316c1e5e2012-09-12 15:17:446208
6209 HTTPRedirectMethodTest(url, "POST", "GET", true);
6210 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6211 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516212
6213 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6214 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6215 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6216 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6217 std::string());
[email protected]316c1e5e2012-09-12 15:17:446218}
6219
6220TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6221 ASSERT_TRUE(test_server_.Start());
6222
6223 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
jww5fe460ff2015-03-28 00:22:516224 const GURL https_redirect_url =
6225 test_server_.GetURL("files/redirect302-to-https");
[email protected]316c1e5e2012-09-12 15:17:446226
6227 HTTPRedirectMethodTest(url, "POST", "GET", true);
6228 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6229 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516230
6231 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6232 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6233 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6234 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6235 std::string());
[email protected]316c1e5e2012-09-12 15:17:446236}
6237
6238TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6239 ASSERT_TRUE(test_server_.Start());
6240
6241 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
jww5fe460ff2015-03-28 00:22:516242 const GURL https_redirect_url =
6243 test_server_.GetURL("files/redirect303-to-https");
[email protected]316c1e5e2012-09-12 15:17:446244
6245 HTTPRedirectMethodTest(url, "POST", "GET", true);
6246 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6247 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516248
6249 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6250 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6251 HTTPRedirectOriginHeaderTest(url, "POST", "GET", std::string());
6252 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "GET",
6253 std::string());
[email protected]316c1e5e2012-09-12 15:17:446254}
6255
6256TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6257 ASSERT_TRUE(test_server_.Start());
6258
6259 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
jww5fe460ff2015-03-28 00:22:516260 const GURL https_redirect_url =
6261 test_server_.GetURL("files/redirect307-to-https");
[email protected]316c1e5e2012-09-12 15:17:446262
6263 HTTPRedirectMethodTest(url, "POST", "POST", true);
6264 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6265 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516266
6267 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6268 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6269 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6270 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]316c1e5e2012-09-12 15:17:446271}
6272
[email protected]0a17aab32014-04-24 03:32:376273TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6274 ASSERT_TRUE(test_server_.Start());
6275
6276 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
jww5fe460ff2015-03-28 00:22:516277 const GURL https_redirect_url =
6278 test_server_.GetURL("files/redirect308-to-https");
[email protected]0a17aab32014-04-24 03:32:376279
6280 HTTPRedirectMethodTest(url, "POST", "POST", true);
6281 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6282 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
jww5fe460ff2015-03-28 00:22:516283
6284 HTTPRedirectOriginHeaderTest(url, "GET", "GET", url.GetOrigin().spec());
6285 HTTPRedirectOriginHeaderTest(https_redirect_url, "GET", "GET", "null");
6286 HTTPRedirectOriginHeaderTest(url, "POST", "POST", url.GetOrigin().spec());
6287 HTTPRedirectOriginHeaderTest(https_redirect_url, "POST", "POST", "null");
[email protected]0a17aab32014-04-24 03:32:376288}
6289
6290// Make sure that 308 responses without bodies are not treated as redirects.
6291// Certain legacy apis that pre-date the response code expect this behavior
6292// (Like Google Drive).
6293TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6294 ASSERT_TRUE(test_server_.Start());
6295
6296 TestDelegate d;
6297 const GURL url = test_server_.GetURL("files/308-without-location-header");
6298
davidben151423e2015-03-23 18:48:366299 scoped_ptr<URLRequest> request(
6300 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]0a17aab32014-04-24 03:32:376301
[email protected]f7022f32014-08-21 16:32:196302 request->Start();
[email protected]0a17aab32014-04-24 03:32:376303 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196304 EXPECT_EQ(URLRequestStatus::SUCCESS, request->status().status());
6305 EXPECT_EQ(OK, request->status().error());
[email protected]0a17aab32014-04-24 03:32:376306 EXPECT_EQ(0, d.received_redirect_count());
[email protected]f7022f32014-08-21 16:32:196307 EXPECT_EQ(308, request->response_headers()->response_code());
[email protected]0a17aab32014-04-24 03:32:376308 EXPECT_EQ("This is not a redirect.", d.data_received());
6309}
6310
[email protected]f878230e2014-04-03 15:36:146311TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6312 ASSERT_TRUE(test_server_.Start());
6313
6314 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6315 GURL expected_url(test_server_.GetURL("echo#fragment"));
6316
6317 TestDelegate d;
6318 {
davidben151423e2015-03-23 18:48:366319 scoped_ptr<URLRequest> r(
6320 default_context_.CreateRequest(original_url, DEFAULT_PRIORITY, &d));
[email protected]f878230e2014-04-03 15:36:146321
[email protected]f7022f32014-08-21 16:32:196322 r->Start();
[email protected]f878230e2014-04-03 15:36:146323 base::RunLoop().Run();
6324
[email protected]f7022f32014-08-21 16:32:196325 EXPECT_EQ(2U, r->url_chain().size());
6326 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6327 EXPECT_EQ(OK, r->status().error());
6328 EXPECT_EQ(original_url, r->original_url());
6329 EXPECT_EQ(expected_url, r->url());
[email protected]f878230e2014-04-03 15:36:146330 }
6331}
6332
[email protected]cba24642014-08-15 20:49:596333TEST_F(URLRequestTestHTTP, RedirectPreserveFirstPartyURL) {
6334 ASSERT_TRUE(test_server_.Start());
6335
6336 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6337 GURL first_party_url("http://example.com");
6338
6339 TestDelegate d;
6340 {
davidben151423e2015-03-23 18:48:366341 scoped_ptr<URLRequest> r(
6342 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196343 r->set_first_party_for_cookies(first_party_url);
[email protected]cba24642014-08-15 20:49:596344
[email protected]f7022f32014-08-21 16:32:196345 r->Start();
[email protected]cba24642014-08-15 20:49:596346 base::RunLoop().Run();
6347
[email protected]f7022f32014-08-21 16:32:196348 EXPECT_EQ(2U, r->url_chain().size());
6349 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6350 EXPECT_EQ(OK, r->status().error());
6351 EXPECT_EQ(first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596352 }
6353}
6354
6355TEST_F(URLRequestTestHTTP, RedirectUpdateFirstPartyURL) {
6356 ASSERT_TRUE(test_server_.Start());
6357
6358 GURL url(test_server_.GetURL("files/redirect302-to-echo"));
6359 GURL original_first_party_url("http://example.com");
6360 GURL expected_first_party_url(test_server_.GetURL("echo"));
6361
6362 TestDelegate d;
6363 {
davidben151423e2015-03-23 18:48:366364 scoped_ptr<URLRequest> r(
6365 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196366 r->set_first_party_for_cookies(original_first_party_url);
6367 r->set_first_party_url_policy(
[email protected]cba24642014-08-15 20:49:596368 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT);
6369
[email protected]f7022f32014-08-21 16:32:196370 r->Start();
[email protected]cba24642014-08-15 20:49:596371 base::RunLoop().Run();
6372
[email protected]f7022f32014-08-21 16:32:196373 EXPECT_EQ(2U, r->url_chain().size());
6374 EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
6375 EXPECT_EQ(OK, r->status().error());
6376 EXPECT_EQ(expected_first_party_url, r->first_party_for_cookies());
[email protected]cba24642014-08-15 20:49:596377 }
6378}
6379
[email protected]316c1e5e2012-09-12 15:17:446380TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6381 ASSERT_TRUE(test_server_.Start());
6382
6383 const char kData[] = "hello world";
6384
6385 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196386 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366387 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196388 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076389 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446390 HttpRequestHeaders headers;
6391 headers.SetHeader(HttpRequestHeaders::kContentLength,
6392 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196393 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446394
6395 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196396 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096397 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446398 AddTestInterceptor()->set_main_intercept_job(job);
6399
[email protected]f7022f32014-08-21 16:32:196400 req->Start();
[email protected]255620da2013-08-19 13:14:296401 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196402 EXPECT_EQ("GET", req->method());
[email protected]316c1e5e2012-09-12 15:17:446403}
6404
6405TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6406 ASSERT_TRUE(test_server_.Start());
6407
6408 const char kData[] = "hello world";
6409
6410 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196411 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366412 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196413 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:076414 req->set_upload(CreateSimpleUploadData(kData));
[email protected]316c1e5e2012-09-12 15:17:446415 HttpRequestHeaders headers;
6416 headers.SetHeader(HttpRequestHeaders::kContentLength,
6417 base::UintToString(arraysize(kData) - 1));
[email protected]f7022f32014-08-21 16:32:196418 req->SetExtraRequestHeaders(headers);
[email protected]316c1e5e2012-09-12 15:17:446419
6420 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196421 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096422 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6423 "Very Good Reason");
[email protected]316c1e5e2012-09-12 15:17:446424 AddTestInterceptor()->set_main_intercept_job(job);
6425
[email protected]f7022f32014-08-21 16:32:196426 req->Start();
[email protected]255620da2013-08-19 13:14:296427 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196428 EXPECT_EQ("POST", req->method());
[email protected]316c1e5e2012-09-12 15:17:446429 EXPECT_EQ(kData, d.data_received());
6430}
6431
6432// Check that default A-L header is sent.
6433TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6434 ASSERT_TRUE(test_server_.Start());
6435
[email protected]8790210c2013-12-02 05:29:536436 StaticHttpUserAgentSettings settings("en", std::string());
[email protected]ceefd7fd2012-11-29 00:36:246437 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446438 TestURLRequestContext context(true);
6439 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:436440 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446441 context.Init();
6442
6443 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196444 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366445 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196446 req->Start();
[email protected]255620da2013-08-19 13:14:296447 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446448 EXPECT_EQ("en", d.data_received());
6449}
6450
6451// Check that an empty A-L header is not sent. http://crbug.com/77365.
6452TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6453 ASSERT_TRUE(test_server_.Start());
6454
[email protected]8790210c2013-12-02 05:29:536455 std::string empty_string; // Avoid most vexing parse on line below.
6456 StaticHttpUserAgentSettings settings(empty_string, empty_string);
[email protected]ceefd7fd2012-11-29 00:36:246457 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:446458 TestURLRequestContext context(true);
6459 context.set_network_delegate(&network_delegate);
6460 context.Init();
6461 // We override the language after initialization because empty entries
6462 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:436463 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:446464
6465 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196466 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366467 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196468 req->Start();
[email protected]255620da2013-08-19 13:14:296469 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446470 EXPECT_EQ("None", d.data_received());
6471}
6472
6473// Check that if request overrides the A-L header, the default is not appended.
6474// See http://crbug.com/20894
6475TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6476 ASSERT_TRUE(test_server_.Start());
6477
6478 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196479 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366480 test_server_.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446481 HttpRequestHeaders headers;
6482 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
[email protected]f7022f32014-08-21 16:32:196483 req->SetExtraRequestHeaders(headers);
6484 req->Start();
[email protected]255620da2013-08-19 13:14:296485 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446486 EXPECT_EQ(std::string("ru"), d.data_received());
6487}
6488
6489// Check that default A-E header is sent.
6490TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6491 ASSERT_TRUE(test_server_.Start());
6492
6493 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196494 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366495 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446496 HttpRequestHeaders headers;
[email protected]f7022f32014-08-21 16:32:196497 req->SetExtraRequestHeaders(headers);
6498 req->Start();
[email protected]255620da2013-08-19 13:14:296499 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446500 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6501}
6502
6503// Check that if request overrides the A-E header, the default is not appended.
6504// See http://crbug.com/47381
6505TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6506 ASSERT_TRUE(test_server_.Start());
6507
6508 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196509 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366510 test_server_.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446511 HttpRequestHeaders headers;
6512 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
[email protected]f7022f32014-08-21 16:32:196513 req->SetExtraRequestHeaders(headers);
6514 req->Start();
[email protected]255620da2013-08-19 13:14:296515 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446516 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6517 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6518}
6519
[email protected]84f05432013-03-15 01:00:126520// Check that setting the A-C header sends the proper header.
6521TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:446522 ASSERT_TRUE(test_server_.Start());
6523
6524 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196525 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366526 test_server_.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446527 HttpRequestHeaders headers;
6528 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
[email protected]f7022f32014-08-21 16:32:196529 req->SetExtraRequestHeaders(headers);
6530 req->Start();
[email protected]255620da2013-08-19 13:14:296531 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446532 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6533}
6534
6535// Check that default User-Agent header is sent.
6536TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6537 ASSERT_TRUE(test_server_.Start());
6538
6539 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196540 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366541 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196542 req->Start();
[email protected]255620da2013-08-19 13:14:296543 base::RunLoop().Run();
[email protected]f7022f32014-08-21 16:32:196544 EXPECT_EQ(default_context_.http_user_agent_settings()->GetUserAgent(),
[email protected]051a4b32014-01-09 04:02:376545 d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446546}
6547
6548// Check that if request overrides the User-Agent header,
6549// the default is not appended.
6550TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6551 ASSERT_TRUE(test_server_.Start());
6552
6553 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196554 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366555 test_server_.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:446556 HttpRequestHeaders headers;
6557 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
[email protected]f7022f32014-08-21 16:32:196558 req->SetExtraRequestHeaders(headers);
6559 req->Start();
[email protected]255620da2013-08-19 13:14:296560 base::RunLoop().Run();
[email protected]cd6f2522014-01-16 18:27:356561 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:446562}
6563
[email protected]ee4c30d2012-11-07 15:08:436564// Check that a NULL HttpUserAgentSettings causes the corresponding empty
6565// User-Agent header to be sent but does not send the Accept-Language and
6566// Accept-Charset headers.
6567TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6568 ASSERT_TRUE(test_server_.Start());
6569
[email protected]ceefd7fd2012-11-29 00:36:246570 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:436571 TestURLRequestContext context(true);
6572 context.set_network_delegate(&network_delegate);
6573 context.Init();
6574 // We override the HttpUserAgentSettings after initialization because empty
6575 // entries get overridden by Init().
6576 context.set_http_user_agent_settings(NULL);
6577
6578 struct {
6579 const char* request;
6580 const char* expected_response;
6581 } tests[] = { { "echoheader?Accept-Language", "None" },
6582 { "echoheader?Accept-Charset", "None" },
6583 { "echoheader?User-Agent", "" } };
6584
viettrungluue4a8b882014-10-16 06:17:386585 for (size_t i = 0; i < arraysize(tests); i++) {
[email protected]ee4c30d2012-11-07 15:08:436586 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196587 scoped_ptr<URLRequest> req(context.CreateRequest(
davidben151423e2015-03-23 18:48:366588 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196589 req->Start();
[email protected]255620da2013-08-19 13:14:296590 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:436591 EXPECT_EQ(tests[i].expected_response, d.data_received())
6592 << " Request = \"" << tests[i].request << "\"";
6593 }
6594}
6595
[email protected]5033ab82013-03-22 20:17:466596// Make sure that URLRequest passes on its priority updates to
6597// newly-created jobs after the first one.
6598TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6599 ASSERT_TRUE(test_server_.Start());
6600
6601 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:196602 scoped_ptr<URLRequest> req(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:366603 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196604 EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
[email protected]5033ab82013-03-22 20:17:466605
6606 scoped_refptr<URLRequestRedirectJob> redirect_job =
6607 new URLRequestRedirectJob(
[email protected]f7022f32014-08-21 16:32:196608 req.get(), &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]7983c4a2014-03-12 01:47:096609 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
[email protected]90499482013-06-01 00:39:506610 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:466611
[email protected]f7022f32014-08-21 16:32:196612 req->SetPriority(LOW);
6613 req->Start();
6614 EXPECT_TRUE(req->is_pending());
[email protected]5033ab82013-03-22 20:17:466615
6616 scoped_refptr<URLRequestTestJob> job =
[email protected]f7022f32014-08-21 16:32:196617 new URLRequestTestJob(req.get(), &default_network_delegate_);
[email protected]90499482013-06-01 00:39:506618 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:466619
6620 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:296621 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:466622 EXPECT_EQ(LOW, job->priority());
6623}
6624
[email protected]80abdad2014-03-15 00:20:546625// Check that creating a network request while entering/exiting suspend mode
6626// fails as it should. This is the only case where an HttpTransactionFactory
6627// does not return an HttpTransaction.
6628TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6629 // Create a new HttpNetworkLayer that thinks it's suspended.
6630 HttpNetworkSession::Params params;
6631 params.host_resolver = default_context_.host_resolver();
6632 params.cert_verifier = default_context_.cert_verifier();
6633 params.transport_security_state = default_context_.transport_security_state();
6634 params.proxy_service = default_context_.proxy_service();
6635 params.ssl_config_service = default_context_.ssl_config_service();
6636 params.http_auth_handler_factory =
6637 default_context_.http_auth_handler_factory();
6638 params.network_delegate = &default_network_delegate_;
6639 params.http_server_properties = default_context_.http_server_properties();
6640 scoped_ptr<HttpNetworkLayer> network_layer(
6641 new HttpNetworkLayer(new HttpNetworkSession(params)));
6642 network_layer->OnSuspend();
6643
6644 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6645 HttpCache::DefaultBackend::InMemory(0));
6646
6647 TestURLRequestContext context(true);
6648 context.set_http_transaction_factory(&http_cache);
6649 context.Init();
6650
6651 TestDelegate d;
davidben151423e2015-03-23 18:48:366652 scoped_ptr<URLRequest> req(
6653 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196654 req->Start();
[email protected]80abdad2014-03-15 00:20:546655 base::RunLoop().Run();
6656
6657 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196658 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6659 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546660}
6661
6662// Check that creating a network request while entering/exiting suspend mode
6663// fails as it should in the case there is no cache. This is the only case
6664// where an HttpTransactionFactory does not return an HttpTransaction.
6665TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6666 // Create a new HttpNetworkLayer that thinks it's suspended.
6667 HttpNetworkSession::Params params;
6668 params.host_resolver = default_context_.host_resolver();
6669 params.cert_verifier = default_context_.cert_verifier();
6670 params.transport_security_state = default_context_.transport_security_state();
6671 params.proxy_service = default_context_.proxy_service();
6672 params.ssl_config_service = default_context_.ssl_config_service();
6673 params.http_auth_handler_factory =
6674 default_context_.http_auth_handler_factory();
6675 params.network_delegate = &default_network_delegate_;
6676 params.http_server_properties = default_context_.http_server_properties();
6677 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6678 network_layer.OnSuspend();
6679
6680 TestURLRequestContext context(true);
6681 context.set_http_transaction_factory(&network_layer);
6682 context.Init();
6683
6684 TestDelegate d;
davidben151423e2015-03-23 18:48:366685 scoped_ptr<URLRequest> req(
6686 context.CreateRequest(GURL("http://127.0.0.1/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:196687 req->Start();
[email protected]80abdad2014-03-15 00:20:546688 base::RunLoop().Run();
6689
6690 EXPECT_TRUE(d.request_failed());
[email protected]f7022f32014-08-21 16:32:196691 EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
6692 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req->status().error());
[email protected]80abdad2014-03-15 00:20:546693}
6694
bengr1bf8e942014-11-07 01:36:506695class URLRequestInterceptorTestHTTP : public URLRequestTestHTTP {
6696 public:
6697 // TODO(bengr): Merge this with the URLRequestInterceptorHTTPTest fixture,
6698 // ideally remove the dependency on URLRequestTestJob, and maybe move these
6699 // tests into the factory tests.
6700 URLRequestInterceptorTestHTTP() : URLRequestTestHTTP(), interceptor_(NULL) {
6701 }
6702
6703 void SetUpFactory() override {
6704 interceptor_ = new MockURLRequestInterceptor();
6705 job_factory_.reset(new URLRequestInterceptingJobFactory(
6706 job_factory_.Pass(), make_scoped_ptr(interceptor_)));
6707 }
6708
6709 MockURLRequestInterceptor* interceptor() const {
6710 return interceptor_;
6711 }
6712
6713 private:
6714 MockURLRequestInterceptor* interceptor_;
6715};
6716
6717TEST_F(URLRequestInterceptorTestHTTP,
6718 NetworkDelegateNotificationOnRedirectIntercept) {
6719 interceptor()->set_intercept_redirect(true);
6720 interceptor()->set_redirect_headers(MockURLRequestInterceptor::ok_headers());
6721 interceptor()->set_redirect_data(MockURLRequestInterceptor::ok_data());
6722
6723 ASSERT_TRUE(test_server()->Start());
6724
6725 TestDelegate d;
6726 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366727 test_server()->GetURL("files/redirect-test.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506728 req->Start();
6729 base::RunLoop().Run();
6730
6731 EXPECT_TRUE(interceptor()->did_intercept_redirect());
6732 // Check we got one good response
6733 EXPECT_TRUE(req->status().is_success());
6734 if (req->status().is_success())
6735 EXPECT_EQ(200, req->response_headers()->response_code());
6736
6737 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6738 EXPECT_EQ(1, d.response_started_count());
6739 EXPECT_EQ(0, d.received_redirect_count());
6740
6741 EXPECT_EQ(1, default_network_delegate()->created_requests());
6742 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6743 EXPECT_EQ(1, default_network_delegate()->headers_received_count());
6744}
6745
6746TEST_F(URLRequestInterceptorTestHTTP,
6747 NetworkDelegateNotificationOnErrorIntercept) {
6748 // Intercept that error and respond with an OK response.
6749 interceptor()->set_intercept_final_response(true);
6750 interceptor()->set_final_headers(MockURLRequestInterceptor::ok_headers());
6751 interceptor()->set_final_data(MockURLRequestInterceptor::ok_data());
6752 default_network_delegate()->set_can_be_intercepted_on_error(true);
6753
6754 ASSERT_TRUE(test_server()->Start());
6755
6756 TestDelegate d;
6757 scoped_ptr<URLRequest> req(default_context().CreateRequest(
6758 test_server()->GetURL("files/two-content-lengths.html"), DEFAULT_PRIORITY,
davidben151423e2015-03-23 18:48:366759 &d));
bengr1bf8e942014-11-07 01:36:506760 req->set_method("GET");
6761 req->Start();
6762 base::RunLoop().Run();
6763
6764 EXPECT_TRUE(interceptor()->did_intercept_final());
6765
6766 // Check we received one good response.
6767 EXPECT_TRUE(req->status().is_success());
6768 if (req->status().is_success())
6769 EXPECT_EQ(200, req->response_headers()->response_code());
6770 EXPECT_EQ(MockURLRequestInterceptor::ok_data(), d.data_received());
6771 EXPECT_EQ(1, d.response_started_count());
6772 EXPECT_EQ(0, d.received_redirect_count());
6773
6774 EXPECT_EQ(1, default_network_delegate()->created_requests());
6775 EXPECT_EQ(1, default_network_delegate()->before_send_headers_count());
6776 EXPECT_EQ(0, default_network_delegate()->headers_received_count());
6777}
6778
6779TEST_F(URLRequestInterceptorTestHTTP,
6780 NetworkDelegateNotificationOnResponseIntercept) {
6781 // Intercept that error and respond with an OK response.
6782 interceptor()->set_intercept_final_response(true);
6783
6784 // Intercept with a real URLRequestHttpJob.
6785 interceptor()->set_use_url_request_http_job(true);
6786
6787 ASSERT_TRUE(test_server()->Start());
6788
6789 TestDelegate d;
6790 scoped_ptr<URLRequest> req(default_context().CreateRequest(
davidben151423e2015-03-23 18:48:366791 test_server()->GetURL("files/simple.html"), DEFAULT_PRIORITY, &d));
bengr1bf8e942014-11-07 01:36:506792 req->set_method("GET");
6793 req->Start();
6794 base::RunLoop().Run();
6795
6796 EXPECT_TRUE(interceptor()->did_intercept_final());
6797
6798 // Check we received one good response.
6799 EXPECT_TRUE(req->status().is_success());
6800 if (req->status().is_success())
6801 EXPECT_EQ(200, req->response_headers()->response_code());
6802 EXPECT_EQ("hello", d.data_received());
6803 EXPECT_EQ(1, d.response_started_count());
6804 EXPECT_EQ(0, d.received_redirect_count());
6805
6806 EXPECT_EQ(1, default_network_delegate()->created_requests());
6807 EXPECT_EQ(2, default_network_delegate()->before_send_headers_count());
6808 EXPECT_EQ(2, default_network_delegate()->headers_received_count());
6809}
6810
mkwst0c5eab872014-11-21 14:18:546811class URLRequestTestReferrerPolicy : public URLRequestTest {
6812 public:
6813 URLRequestTestReferrerPolicy() {}
6814
6815 void InstantiateSameOriginServers(SpawnedTestServer::Type origin_type) {
6816 origin_server_.reset(new SpawnedTestServer(
6817 origin_type, SpawnedTestServer::kLocalhost,
6818 origin_type == SpawnedTestServer::TYPE_HTTPS
6819 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6820 : base::FilePath(
6821 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6822 ASSERT_TRUE(origin_server_->Start());
6823 }
6824
6825 void InstantiateCrossOriginServers(SpawnedTestServer::Type origin_type,
6826 SpawnedTestServer::Type destination_type) {
6827 origin_server_.reset(new SpawnedTestServer(
6828 origin_type, SpawnedTestServer::kLocalhost,
6829 origin_type == SpawnedTestServer::TYPE_HTTPS
6830 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6831 : base::FilePath(
6832 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6833 ASSERT_TRUE(origin_server_->Start());
6834
6835 destination_server_.reset(new SpawnedTestServer(
6836 destination_type, SpawnedTestServer::kLocalhost,
6837 destination_type == SpawnedTestServer::TYPE_HTTPS
6838 ? base::FilePath(FILE_PATH_LITERAL("net/data/ssl"))
6839 : base::FilePath(
6840 FILE_PATH_LITERAL("net/data/url_request_unittest"))));
6841 ASSERT_TRUE(destination_server_->Start());
6842 }
6843
6844 void VerifyReferrerAfterRedirect(URLRequest::ReferrerPolicy policy,
6845 const GURL& referrer,
6846 const GURL& expected) {
6847 // Create and execute the request: we'll only have a |destination_server_|
6848 // if the origins are meant to be distinct. Otherwise, we'll use the
6849 // |origin_server_| for both endpoints.
6850 GURL destination_url =
6851 destination_server_ ? destination_server_->GetURL("echoheader?Referer")
6852 : origin_server_->GetURL("echoheader?Referer");
6853 GURL origin_url =
6854 origin_server_->GetURL("server-redirect?" + destination_url.spec());
6855
6856 TestDelegate d;
6857 scoped_ptr<URLRequest> req(
davidben151423e2015-03-23 18:48:366858 default_context_.CreateRequest(origin_url, DEFAULT_PRIORITY, &d));
mkwst0c5eab872014-11-21 14:18:546859 req->set_referrer_policy(policy);
6860 req->SetReferrer(referrer.spec());
6861 req->Start();
6862 base::RunLoop().Run();
6863
6864 EXPECT_EQ(1, d.response_started_count());
6865 EXPECT_EQ(1, d.received_redirect_count());
6866 EXPECT_EQ(destination_url, req->url());
6867 EXPECT_TRUE(req->status().is_success());
6868 EXPECT_EQ(200, req->response_headers()->response_code());
6869
6870 EXPECT_EQ(expected.spec(), req->referrer());
6871 if (expected.is_empty())
6872 EXPECT_EQ("None", d.data_received());
6873 else
6874 EXPECT_EQ(expected.spec(), d.data_received());
6875 }
6876
6877 SpawnedTestServer* origin_server() const { return origin_server_.get(); }
6878
6879 private:
6880 scoped_ptr<SpawnedTestServer> origin_server_;
6881 scoped_ptr<SpawnedTestServer> destination_server_;
6882};
6883
6884TEST_F(URLRequestTestReferrerPolicy, HTTPToSameOriginHTTP) {
6885 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTP);
6886
6887 VerifyReferrerAfterRedirect(
6888 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6889 origin_server()->GetURL("path/to/file.html"),
6890 origin_server()->GetURL("path/to/file.html"));
6891
6892 VerifyReferrerAfterRedirect(
6893 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6894 origin_server()->GetURL("path/to/file.html"),
6895 origin_server()->GetURL("path/to/file.html"));
6896
6897 VerifyReferrerAfterRedirect(
6898 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6899 origin_server()->GetURL("path/to/file.html"),
6900 origin_server()->GetURL("path/to/file.html"));
6901
6902 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6903 origin_server()->GetURL("path/to/file.html"),
6904 origin_server()->GetURL("path/to/file.html"));
6905}
6906
6907TEST_F(URLRequestTestReferrerPolicy, HTTPToCrossOriginHTTP) {
6908 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
6909 SpawnedTestServer::TYPE_HTTP);
6910
6911 VerifyReferrerAfterRedirect(
6912 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6913 origin_server()->GetURL("path/to/file.html"),
6914 origin_server()->GetURL("path/to/file.html"));
6915
6916 VerifyReferrerAfterRedirect(
6917 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6918 origin_server()->GetURL("path/to/file.html"),
6919 origin_server()->GetURL(std::string()));
6920
6921 VerifyReferrerAfterRedirect(
6922 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6923 origin_server()->GetURL("path/to/file.html"),
6924 origin_server()->GetURL(std::string()));
6925
6926 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6927 origin_server()->GetURL("path/to/file.html"),
6928 origin_server()->GetURL("path/to/file.html"));
6929}
6930
6931TEST_F(URLRequestTestReferrerPolicy, HTTPSToSameOriginHTTPS) {
6932 InstantiateSameOriginServers(SpawnedTestServer::TYPE_HTTPS);
6933
6934 VerifyReferrerAfterRedirect(
6935 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6936 origin_server()->GetURL("path/to/file.html"),
6937 origin_server()->GetURL("path/to/file.html"));
6938
6939 VerifyReferrerAfterRedirect(
6940 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6941 origin_server()->GetURL("path/to/file.html"),
6942 origin_server()->GetURL("path/to/file.html"));
6943
6944 VerifyReferrerAfterRedirect(
6945 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6946 origin_server()->GetURL("path/to/file.html"),
6947 origin_server()->GetURL("path/to/file.html"));
6948
6949 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6950 origin_server()->GetURL("path/to/file.html"),
6951 origin_server()->GetURL("path/to/file.html"));
6952}
6953
6954TEST_F(URLRequestTestReferrerPolicy, HTTPSToCrossOriginHTTPS) {
6955 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
6956 SpawnedTestServer::TYPE_HTTPS);
6957
6958 VerifyReferrerAfterRedirect(
6959 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6960 origin_server()->GetURL("path/to/file.html"),
6961 origin_server()->GetURL("path/to/file.html"));
6962
6963 VerifyReferrerAfterRedirect(
6964 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6965 origin_server()->GetURL("path/to/file.html"),
6966 origin_server()->GetURL(std::string()));
6967
6968 VerifyReferrerAfterRedirect(
6969 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6970 origin_server()->GetURL("path/to/file.html"),
6971 origin_server()->GetURL(std::string()));
6972
6973 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6974 origin_server()->GetURL("path/to/file.html"),
6975 origin_server()->GetURL("path/to/file.html"));
6976}
6977
6978TEST_F(URLRequestTestReferrerPolicy, HTTPToHTTPS) {
6979 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTP,
6980 SpawnedTestServer::TYPE_HTTPS);
6981
6982 VerifyReferrerAfterRedirect(
6983 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
6984 origin_server()->GetURL("path/to/file.html"),
6985 origin_server()->GetURL("path/to/file.html"));
6986
6987 VerifyReferrerAfterRedirect(
6988 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
6989 origin_server()->GetURL("path/to/file.html"),
6990 origin_server()->GetURL(std::string()));
6991
6992 VerifyReferrerAfterRedirect(
6993 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
6994 origin_server()->GetURL("path/to/file.html"),
6995 origin_server()->GetURL(std::string()));
6996
6997 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
6998 origin_server()->GetURL("path/to/file.html"),
6999 origin_server()->GetURL("path/to/file.html"));
7000}
7001
7002TEST_F(URLRequestTestReferrerPolicy, HTTPSToHTTP) {
7003 InstantiateCrossOriginServers(SpawnedTestServer::TYPE_HTTPS,
7004 SpawnedTestServer::TYPE_HTTP);
7005
7006 VerifyReferrerAfterRedirect(
7007 URLRequest::CLEAR_REFERRER_ON_TRANSITION_FROM_SECURE_TO_INSECURE,
7008 origin_server()->GetURL("path/to/file.html"), GURL());
7009
7010 VerifyReferrerAfterRedirect(
7011 URLRequest::REDUCE_REFERRER_GRANULARITY_ON_TRANSITION_CROSS_ORIGIN,
7012 origin_server()->GetURL("path/to/file.html"), GURL());
7013
7014 VerifyReferrerAfterRedirect(
7015 URLRequest::ORIGIN_ONLY_ON_TRANSITION_CROSS_ORIGIN,
7016 origin_server()->GetURL("path/to/file.html"),
7017 origin_server()->GetURL(std::string()));
7018
7019 VerifyReferrerAfterRedirect(URLRequest::NEVER_CLEAR_REFERRER,
7020 origin_server()->GetURL("path/to/file.html"),
7021 origin_server()->GetURL("path/to/file.html"));
7022}
7023
[email protected]73e0bba2009-02-19 22:57:097024class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:507025 public:
[email protected]ef2bf422012-05-11 03:27:097026 HTTPSRequestTest() : default_context_(true) {
7027 default_context_.set_network_delegate(&default_network_delegate_);
7028 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:507029 }
dcheng67be2b1f2014-10-27 21:47:297030 ~HTTPSRequestTest() override {}
[email protected]87a09a92011-07-14 15:50:507031
7032 protected:
[email protected]ceefd7fd2012-11-29 00:36:247033 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:097034 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:467035};
7036
[email protected]c044616e2013-02-20 02:01:267037TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227038 SpawnedTestServer test_server(
7039 SpawnedTestServer::TYPE_HTTPS,
7040 SpawnedTestServer::kLocalhost,
7041 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117042 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:467043
[email protected]ea224582008-12-07 20:25:467044 TestDelegate d;
7045 {
[email protected]f7022f32014-08-21 16:32:197046 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367047 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197048 r->Start();
7049 EXPECT_TRUE(r->is_pending());
[email protected]ea224582008-12-07 20:25:467050
[email protected]255620da2013-08-19 13:14:297051 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:467052
7053 EXPECT_EQ(1, d.response_started_count());
7054 EXPECT_FALSE(d.received_data_before_response());
7055 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197056 CheckSSLInfo(r->ssl_info());
[email protected]6d81b482011-02-22 19:47:197057 EXPECT_EQ(test_server.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:197058 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:197059 EXPECT_EQ(test_server.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:197060 r->GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:467061 }
[email protected]ea224582008-12-07 20:25:467062}
7063
[email protected]5774ada2010-07-15 06:30:547064TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227065 SpawnedTestServer::SSLOptions ssl_options(
7066 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7067 SpawnedTestServer test_server(
7068 SpawnedTestServer::TYPE_HTTPS,
7069 ssl_options,
7070 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117071 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337072
7073 bool err_allowed = true;
7074 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7075 TestDelegate d;
7076 {
7077 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197078 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367079 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337080
[email protected]f7022f32014-08-21 16:32:197081 r->Start();
7082 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337083
[email protected]255620da2013-08-19 13:14:297084 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337085
7086 EXPECT_EQ(1, d.response_started_count());
7087 EXPECT_FALSE(d.received_data_before_response());
7088 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177089 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337090 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197091 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177092 } else {
[email protected]bacff652009-03-31 17:50:337093 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177094 }
[email protected]bacff652009-03-31 17:50:337095 }
7096 }
7097}
7098
[email protected]5774ada2010-07-15 06:30:547099TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227100 SpawnedTestServer::SSLOptions ssl_options(
7101 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
7102 SpawnedTestServer test_server(
7103 SpawnedTestServer::TYPE_HTTPS,
7104 ssl_options,
7105 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:117106 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:337107
7108 // Iterate from false to true, just so that we do the opposite of the
7109 // previous test in order to increase test coverage.
7110 bool err_allowed = false;
7111 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
7112 TestDelegate d;
7113 {
7114 d.set_allow_certificate_errors(err_allowed);
[email protected]f7022f32014-08-21 16:32:197115 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367116 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]bacff652009-03-31 17:50:337117
[email protected]f7022f32014-08-21 16:32:197118 r->Start();
7119 EXPECT_TRUE(r->is_pending());
[email protected]bacff652009-03-31 17:50:337120
[email protected]255620da2013-08-19 13:14:297121 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:337122
7123 EXPECT_EQ(1, d.response_started_count());
7124 EXPECT_FALSE(d.received_data_before_response());
7125 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:177126 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:337127 EXPECT_NE(0, d.bytes_received());
[email protected]f7022f32014-08-21 16:32:197128 CheckSSLInfo(r->ssl_info());
[email protected]96adadb2010-08-28 01:16:177129 } else {
[email protected]bacff652009-03-31 17:50:337130 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:177131 }
[email protected]bacff652009-03-31 17:50:337132 }
7133 }
7134}
[email protected]73e0bba2009-02-19 22:57:097135
[email protected]316c1e5e2012-09-12 15:17:447136// This tests that a load of www.google.com with a certificate error sets
7137// the |certificate_errors_are_fatal| flag correctly. This flag will cause
7138// the interstitial to be fatal.
7139TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227140 SpawnedTestServer::SSLOptions ssl_options(
7141 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7142 SpawnedTestServer test_server(
7143 SpawnedTestServer::TYPE_HTTPS,
7144 ssl_options,
7145 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447146 ASSERT_TRUE(test_server.Start());
7147
7148 // We require that the URL be www.google.com in order to pick up the
7149 // preloaded HSTS entries in the TransportSecurityState. This means that we
7150 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:247151 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447152
7153 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247154 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447155 TestURLRequestContext context(true);
7156 context.set_network_delegate(&network_delegate);
7157 context.set_host_resolver(&host_resolver);
7158 TransportSecurityState transport_security_state;
7159 context.set_transport_security_state(&transport_security_state);
7160 context.Init();
7161
7162 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197163 scoped_ptr<URLRequest> r(context.CreateRequest(
7164 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367165 test_server.host_port_pair().port())),
7166 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447167
[email protected]f7022f32014-08-21 16:32:197168 r->Start();
7169 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447170
[email protected]255620da2013-08-19 13:14:297171 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447172
7173 EXPECT_EQ(1, d.response_started_count());
7174 EXPECT_FALSE(d.received_data_before_response());
7175 EXPECT_TRUE(d.have_certificate_errors());
7176 EXPECT_TRUE(d.certificate_errors_are_fatal());
7177}
7178
7179// This tests that cached HTTPS page loads do not cause any updates to the
7180// TransportSecurityState.
7181TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
7182 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
7183 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:227184 SpawnedTestServer::SSLOptions ssl_options(
7185 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
7186 SpawnedTestServer test_server(
7187 SpawnedTestServer::TYPE_HTTPS,
7188 ssl_options,
7189 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447190 ASSERT_TRUE(test_server.Start());
7191
[email protected]9e6968d2014-05-07 21:46:267192 // We require that the URL be www.google.com in order to pick up the static
7193 // and dynamic STS and PKP entries in the TransportSecurityState. This means
7194 // that we have to use a MockHostResolver in order to direct www.google.com to
7195 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:447196
7197 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:247198 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:447199 TestURLRequestContext context(true);
7200 context.set_network_delegate(&network_delegate);
7201 context.set_host_resolver(&host_resolver);
7202 TransportSecurityState transport_security_state;
[email protected]9e6968d2014-05-07 21:46:267203
7204 TransportSecurityState::DomainState static_domain_state;
7205 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127206 "www.google.com", &static_domain_state));
[email protected]316c1e5e2012-09-12 15:17:447207 context.set_transport_security_state(&transport_security_state);
7208 context.Init();
7209
[email protected]9e6968d2014-05-07 21:46:267210 TransportSecurityState::DomainState dynamic_domain_state;
7211 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7212 "www.google.com", &dynamic_domain_state));
7213
[email protected]316c1e5e2012-09-12 15:17:447214 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197215 scoped_ptr<URLRequest> r(context.CreateRequest(
7216 GURL(base::StringPrintf("https://www.google.com:%d",
davidben151423e2015-03-23 18:48:367217 test_server.host_port_pair().port())),
7218 DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447219
[email protected]f7022f32014-08-21 16:32:197220 r->Start();
7221 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447222
[email protected]255620da2013-08-19 13:14:297223 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447224
7225 EXPECT_EQ(1, d.response_started_count());
7226 EXPECT_FALSE(d.received_data_before_response());
7227 EXPECT_TRUE(d.have_certificate_errors());
7228 EXPECT_TRUE(d.certificate_errors_are_fatal());
7229
[email protected]9e6968d2014-05-07 21:46:267230 // Get a fresh copy of the states, and check that they haven't changed.
7231 TransportSecurityState::DomainState new_static_domain_state;
7232 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
Adam Langley5cbb7d7a2014-09-25 23:14:127233 "www.google.com", &new_static_domain_state));
[email protected]9e6968d2014-05-07 21:46:267234 TransportSecurityState::DomainState new_dynamic_domain_state;
7235 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
7236 "www.google.com", &new_dynamic_domain_state));
7237
7238 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
7239 static_domain_state.sts.upgrade_mode);
7240 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
7241 static_domain_state.sts.include_subdomains);
7242 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
7243 static_domain_state.pkp.include_subdomains);
7244 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
7245 static_domain_state.pkp.spki_hashes));
7246 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
7247 static_domain_state.pkp.bad_spki_hashes));
[email protected]316c1e5e2012-09-12 15:17:447248}
7249
[email protected]8ccc69f2012-11-28 19:52:147250// Make sure HSTS preserves a POST request's method and body.
7251TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
7252 static const char kData[] = "hello world";
7253
[email protected]ce7d0cbc2013-05-03 18:57:227254 SpawnedTestServer::SSLOptions ssl_options(
7255 SpawnedTestServer::SSLOptions::CERT_OK);
7256 SpawnedTestServer test_server(
7257 SpawnedTestServer::TYPE_HTTPS,
7258 ssl_options,
7259 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:147260 ASSERT_TRUE(test_server.Start());
7261
7262
7263 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7264 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:227265 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
7266 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:147267 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:147268
7269 // Force https for www.somewhere.com.
7270 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:207271 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
7272 bool include_subdomains = false;
7273 transport_security_state.AddHSTS("www.somewhere.com", expiry,
7274 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:147275
7276 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7277
7278 TestURLRequestContext context(true);
7279 context.set_host_resolver(&host_resolver);
7280 context.set_transport_security_state(&transport_security_state);
7281 context.set_network_delegate(&network_delegate);
7282 context.Init();
7283
7284 TestDelegate d;
7285 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
7286 // cause a certificate error. Ignore the error.
7287 d.set_allow_certificate_errors(true);
7288
[email protected]f7022f32014-08-21 16:32:197289 scoped_ptr<URLRequest> req(context.CreateRequest(
7290 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
davidben151423e2015-03-23 18:48:367291 test_server.host_port_pair().port())),
7292 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:197293 req->set_method("POST");
mmenkecbc2b712014-10-09 20:29:077294 req->set_upload(CreateSimpleUploadData(kData));
[email protected]8ccc69f2012-11-28 19:52:147295
[email protected]f7022f32014-08-21 16:32:197296 req->Start();
[email protected]255620da2013-08-19 13:14:297297 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:147298
[email protected]f7022f32014-08-21 16:32:197299 EXPECT_EQ("https", req->url().scheme());
7300 EXPECT_EQ("POST", req->method());
[email protected]8ccc69f2012-11-28 19:52:147301 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:407302
7303 LoadTimingInfo load_timing_info;
7304 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
7305 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
7306 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:147307}
7308
rob4e0be1f2014-09-11 23:40:227309// Make sure that the CORS headers are added to cross-origin HSTS redirects.
7310TEST_F(HTTPSRequestTest, HSTSCrossOriginAddHeaders) {
7311 static const char kOriginHeaderValue[] = "http://www.example.com";
7312
7313 SpawnedTestServer::SSLOptions ssl_options(
7314 SpawnedTestServer::SSLOptions::CERT_OK);
7315 SpawnedTestServer test_server(
7316 SpawnedTestServer::TYPE_HTTPS,
7317 ssl_options,
7318 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7319 ASSERT_TRUE(test_server.Start());
7320
7321 // Per spec, TransportSecurityState expects a domain name, rather than an IP
7322 // address, so a MockHostResolver is needed to redirect example.net to the
7323 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
7324 MockHostResolver host_resolver;
7325
7326 TransportSecurityState transport_security_state;
7327 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7328 bool include_subdomains = false;
7329 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7330
7331 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
7332
7333 MockCertVerifier cert_verifier;
7334 cert_verifier.set_default_result(OK);
7335
7336 TestURLRequestContext context(true);
7337 context.set_host_resolver(&host_resolver);
7338 context.set_transport_security_state(&transport_security_state);
7339 context.set_network_delegate(&network_delegate);
7340 context.set_cert_verifier(&cert_verifier);
7341 context.Init();
7342
7343 GURL hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
7344 test_server.host_port_pair().port()));
7345 url::Replacements<char> replacements;
7346 const char kNewScheme[] = "https";
7347 replacements.SetScheme(kNewScheme, url::Component(0, strlen(kNewScheme)));
7348 GURL hsts_https_url = hsts_http_url.ReplaceComponents(replacements);
7349
7350 TestDelegate d;
7351 // Quit on redirect to allow response header inspection upon redirect.
7352 d.set_quit_on_redirect(true);
7353
davidben151423e2015-03-23 18:48:367354 scoped_ptr<URLRequest> req(
7355 context.CreateRequest(hsts_http_url, DEFAULT_PRIORITY, &d));
rob4e0be1f2014-09-11 23:40:227356 // Set Origin header to simulate a cross-origin request.
7357 HttpRequestHeaders request_headers;
7358 request_headers.SetHeader("Origin", kOriginHeaderValue);
7359 req->SetExtraRequestHeaders(request_headers);
7360
7361 req->Start();
7362 base::RunLoop().Run();
7363
7364 EXPECT_EQ(1, d.received_redirect_count());
7365
7366 const HttpResponseHeaders* headers = req->response_headers();
7367 std::string redirect_location;
7368 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Location", &redirect_location));
7369 EXPECT_EQ(hsts_https_url.spec(), redirect_location);
7370
7371 std::string received_cors_header;
7372 EXPECT_TRUE(headers->EnumerateHeader(NULL, "Access-Control-Allow-Origin",
7373 &received_cors_header));
7374 EXPECT_EQ(kOriginHeaderValue, received_cors_header);
7375}
7376
Adam Ricecb76ac62015-02-20 05:33:257377// This just tests the behaviour of GetHSTSRedirect(). End-to-end tests of HSTS
7378// are performed in net/websockets/websocket_end_to_end_test.cc.
7379TEST(WebSocketURLRequestTest, HSTSApplied) {
7380 TestNetworkDelegate network_delegate;
7381 TransportSecurityState transport_security_state;
7382 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1);
7383 bool include_subdomains = false;
7384 transport_security_state.AddHSTS("example.net", expiry, include_subdomains);
7385 TestURLRequestContext context(true);
7386 context.set_transport_security_state(&transport_security_state);
7387 context.set_network_delegate(&network_delegate);
7388 context.Init();
7389 GURL ws_url("ws://example.net/echo");
7390 TestDelegate delegate;
7391 scoped_ptr<URLRequest> request(
davidben151423e2015-03-23 18:48:367392 context.CreateRequest(ws_url, DEFAULT_PRIORITY, &delegate));
Adam Ricecb76ac62015-02-20 05:33:257393 EXPECT_TRUE(request->GetHSTSRedirect(&ws_url));
7394 EXPECT_TRUE(ws_url.SchemeIs("wss"));
7395}
7396
[email protected]316c1e5e2012-09-12 15:17:447397namespace {
7398
7399class SSLClientAuthTestDelegate : public TestDelegate {
7400 public:
7401 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
7402 }
dchengb03027d2014-10-21 12:00:207403 void OnCertificateRequested(URLRequest* request,
7404 SSLCertRequestInfo* cert_request_info) override {
[email protected]316c1e5e2012-09-12 15:17:447405 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:347406 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:447407 }
7408 int on_certificate_requested_count() {
7409 return on_certificate_requested_count_;
7410 }
7411 private:
7412 int on_certificate_requested_count_;
7413};
7414
7415} // namespace
7416
7417// TODO(davidben): Test the rest of the code. Specifically,
7418// - Filtering which certificates to select.
7419// - Sending a certificate back.
7420// - Getting a certificate request in an SSL renegotiation sending the
7421// HTTP request.
7422TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:227423 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447424 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:227425 SpawnedTestServer test_server(
7426 SpawnedTestServer::TYPE_HTTPS,
7427 ssl_options,
7428 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447429 ASSERT_TRUE(test_server.Start());
7430
7431 SSLClientAuthTestDelegate d;
7432 {
[email protected]f7022f32014-08-21 16:32:197433 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367434 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447435
[email protected]f7022f32014-08-21 16:32:197436 r->Start();
7437 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447438
[email protected]255620da2013-08-19 13:14:297439 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447440
7441 EXPECT_EQ(1, d.on_certificate_requested_count());
7442 EXPECT_FALSE(d.received_data_before_response());
7443 EXPECT_EQ(0, d.bytes_received());
7444
7445 // Send no certificate.
7446 // TODO(davidben): Get temporary client cert import (with keys) working on
7447 // all platforms so we can test sending a cert as well.
[email protected]f7022f32014-08-21 16:32:197448 r->ContinueWithCertificate(NULL);
[email protected]316c1e5e2012-09-12 15:17:447449
[email protected]255620da2013-08-19 13:14:297450 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447451
7452 EXPECT_EQ(1, d.response_started_count());
7453 EXPECT_FALSE(d.received_data_before_response());
7454 EXPECT_NE(0, d.bytes_received());
7455 }
7456}
7457
7458TEST_F(HTTPSRequestTest, ResumeTest) {
7459 // Test that we attempt a session resume when making two connections to the
7460 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:227461 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447462 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227463 SpawnedTestServer test_server(
7464 SpawnedTestServer::TYPE_HTTPS,
7465 ssl_options,
7466 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447467 ASSERT_TRUE(test_server.Start());
7468
7469 SSLClientSocket::ClearSessionCache();
7470
7471 {
7472 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197473 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367474 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447475
[email protected]f7022f32014-08-21 16:32:197476 r->Start();
7477 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447478
[email protected]255620da2013-08-19 13:14:297479 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447480
7481 EXPECT_EQ(1, d.response_started_count());
7482 }
7483
7484 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7485 CloseAllConnections();
7486
7487 {
7488 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197489 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367490 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447491
[email protected]f7022f32014-08-21 16:32:197492 r->Start();
7493 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447494
[email protected]255620da2013-08-19 13:14:297495 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447496
7497 // The response will look like;
7498 // insert abc
7499 // lookup abc
7500 // insert xyz
7501 //
7502 // With a newline at the end which makes the split think that there are
7503 // four lines.
7504
7505 EXPECT_EQ(1, d.response_started_count());
7506 std::vector<std::string> lines;
7507 base::SplitString(d.data_received(), '\n', &lines);
7508 ASSERT_EQ(4u, lines.size()) << d.data_received();
7509
7510 std::string session_id;
7511
7512 for (size_t i = 0; i < 2; i++) {
7513 std::vector<std::string> parts;
7514 base::SplitString(lines[i], '\t', &parts);
7515 ASSERT_EQ(2u, parts.size());
7516 if (i == 0) {
7517 EXPECT_EQ("insert", parts[0]);
7518 session_id = parts[1];
7519 } else {
7520 EXPECT_EQ("lookup", parts[0]);
7521 EXPECT_EQ(session_id, parts[1]);
7522 }
7523 }
7524 }
7525}
7526
Adam Langley32352ad2014-10-14 22:31:007527// AssertTwoDistinctSessionsInserted checks that |session_info|, which must be
7528// the result of fetching "ssl-session-cache" from the test server, indicates
7529// that exactly two different sessions were inserted, with no lookups etc.
7530static void AssertTwoDistinctSessionsInserted(const string& session_info) {
7531 std::vector<std::string> lines;
7532 base::SplitString(session_info, '\n', &lines);
7533 ASSERT_EQ(3u, lines.size()) << session_info;
7534
7535 std::string session_id;
7536 for (size_t i = 0; i < 2; i++) {
7537 std::vector<std::string> parts;
7538 base::SplitString(lines[i], '\t', &parts);
7539 ASSERT_EQ(2u, parts.size());
7540 EXPECT_EQ("insert", parts[0]);
7541 if (i == 0) {
7542 session_id = parts[1];
7543 } else {
7544 EXPECT_NE(session_id, parts[1]);
7545 }
7546 }
7547}
7548
[email protected]316c1e5e2012-09-12 15:17:447549TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
7550 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
7551 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:227552 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:447553 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:227554 SpawnedTestServer test_server(
7555 SpawnedTestServer::TYPE_HTTPS,
7556 ssl_options,
7557 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:447558 ASSERT_TRUE(test_server.Start());
7559
7560 SSLClientSocket::ClearSessionCache();
7561
7562 {
7563 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197564 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367565 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447566
[email protected]f7022f32014-08-21 16:32:197567 r->Start();
7568 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447569
[email protected]255620da2013-08-19 13:14:297570 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447571
7572 EXPECT_EQ(1, d.response_started_count());
7573 }
7574
7575 // Now create a new HttpCache with a different ssl_session_cache_shard value.
7576 HttpNetworkSession::Params params;
7577 params.host_resolver = default_context_.host_resolver();
7578 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:117579 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:447580 params.proxy_service = default_context_.proxy_service();
7581 params.ssl_config_service = default_context_.ssl_config_service();
7582 params.http_auth_handler_factory =
7583 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:417584 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:447585 params.http_server_properties = default_context_.http_server_properties();
7586 params.ssl_session_cache_shard = "alternate";
7587
[email protected]cba24642014-08-15 20:49:597588 scoped_ptr<HttpCache> cache(new HttpCache(
7589 new HttpNetworkSession(params),
7590 HttpCache::DefaultBackend::InMemory(0)));
[email protected]316c1e5e2012-09-12 15:17:447591
7592 default_context_.set_http_transaction_factory(cache.get());
7593
7594 {
7595 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:197596 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367597 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]316c1e5e2012-09-12 15:17:447598
[email protected]f7022f32014-08-21 16:32:197599 r->Start();
7600 EXPECT_TRUE(r->is_pending());
[email protected]316c1e5e2012-09-12 15:17:447601
[email protected]255620da2013-08-19 13:14:297602 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:447603
7604 // The response will look like;
7605 // insert abc
7606 // insert xyz
7607 //
7608 // With a newline at the end which makes the split think that there are
7609 // three lines.
7610
7611 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:007612 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]316c1e5e2012-09-12 15:17:447613 }
7614}
7615
davidben8ecc3072014-09-03 23:19:097616#if defined(OS_WIN)
7617
7618namespace {
7619
7620bool IsECDSACipherSuite(uint16_t cipher_suite) {
7621 const char* key_exchange;
7622 const char* cipher;
7623 const char* mac;
7624 bool is_aead;
7625 SSLCipherSuiteToStrings(&key_exchange, &cipher, &mac, &is_aead, cipher_suite);
7626 return std::string(key_exchange).find("ECDSA") != std::string::npos;
7627}
7628
7629} // namespace
7630
7631// Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7632// verified.
davidben9399c952014-10-07 04:09:117633TEST_F(HTTPSRequestTest, DisableECDSAOnXP) {
davidben8ecc3072014-09-03 23:19:097634 if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
7635 LOG(INFO) << "Skipping test on this version.";
7636 return;
7637 }
7638
7639 SpawnedTestServer test_server(
7640 SpawnedTestServer::TYPE_HTTPS,
7641 SpawnedTestServer::kLocalhost,
7642 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7643 ASSERT_TRUE(test_server.Start());
7644
7645 TestDelegate d;
7646 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:367647 test_server.GetURL("client-cipher-list"), DEFAULT_PRIORITY, &d));
davidben8ecc3072014-09-03 23:19:097648 r->Start();
7649 EXPECT_TRUE(r->is_pending());
7650
7651 base::RunLoop().Run();
7652
7653 EXPECT_EQ(1, d.response_started_count());
7654 std::vector<std::string> lines;
7655 base::SplitString(d.data_received(), '\n', &lines);
7656
7657 for (size_t i = 0; i < lines.size(); i++) {
7658 int cipher_suite;
7659 ASSERT_TRUE(base::StringToInt(lines[i], &cipher_suite));
7660 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite))
7661 << "ClientHello advertised " << cipher_suite;
7662 }
7663}
7664
7665#endif // OS_WIN
7666
Adam Langley32352ad2014-10-14 22:31:007667class TestSSLConfigService : public SSLConfigService {
7668 public:
7669 TestSSLConfigService(bool ev_enabled,
7670 bool online_rev_checking,
7671 bool rev_checking_required_local_anchors)
7672 : ev_enabled_(ev_enabled),
7673 online_rev_checking_(online_rev_checking),
7674 rev_checking_required_local_anchors_(
7675 rev_checking_required_local_anchors),
Adam Langleyac6f24b42014-10-31 20:24:027676 min_version_(kDefaultSSLVersionMin),
7677 fallback_min_version_(kDefaultSSLVersionFallbackMin) {}
7678
7679 void set_min_version(uint16 version) {
7680 min_version_ = version;
7681 }
Adam Langley32352ad2014-10-14 22:31:007682
7683 void set_fallback_min_version(uint16 version) {
7684 fallback_min_version_ = version;
7685 }
7686
7687 // SSLConfigService:
dchengb03027d2014-10-21 12:00:207688 void GetSSLConfig(SSLConfig* config) override {
Adam Langley32352ad2014-10-14 22:31:007689 *config = SSLConfig();
7690 config->rev_checking_enabled = online_rev_checking_;
7691 config->verify_ev_cert = ev_enabled_;
7692 config->rev_checking_required_local_anchors =
7693 rev_checking_required_local_anchors_;
7694 if (fallback_min_version_) {
7695 config->version_fallback_min = fallback_min_version_;
7696 }
Adam Langleyac6f24b42014-10-31 20:24:027697 if (min_version_) {
7698 config->version_min = min_version_;
7699 }
Adam Langley32352ad2014-10-14 22:31:007700 }
7701
7702 protected:
dchengb03027d2014-10-21 12:00:207703 ~TestSSLConfigService() override {}
Adam Langley32352ad2014-10-14 22:31:007704
7705 private:
7706 const bool ev_enabled_;
7707 const bool online_rev_checking_;
7708 const bool rev_checking_required_local_anchors_;
Adam Langleyac6f24b42014-10-31 20:24:027709 uint16 min_version_;
Adam Langley32352ad2014-10-14 22:31:007710 uint16 fallback_min_version_;
7711};
7712
7713class FallbackTestURLRequestContext : public TestURLRequestContext {
7714 public:
7715 explicit FallbackTestURLRequestContext(bool delay_initialization)
7716 : TestURLRequestContext(delay_initialization) {}
7717
7718 void set_fallback_min_version(uint16 version) {
7719 TestSSLConfigService *ssl_config_service =
7720 new TestSSLConfigService(true /* check for EV */,
7721 false /* online revocation checking */,
7722 false /* require rev. checking for local
7723 anchors */);
Adam Langleyac6f24b42014-10-31 20:24:027724 ssl_config_service->set_min_version(SSL_PROTOCOL_VERSION_SSL3);
Adam Langley32352ad2014-10-14 22:31:007725 ssl_config_service->set_fallback_min_version(version);
7726 set_ssl_config_service(ssl_config_service);
7727 }
7728};
7729
[email protected]48d2b7c52014-06-27 01:16:557730class HTTPSFallbackTest : public testing::Test {
7731 public:
Adam Langley32352ad2014-10-14 22:31:007732 HTTPSFallbackTest() : context_(true) {}
dcheng67be2b1f2014-10-27 21:47:297733 ~HTTPSFallbackTest() override {}
[email protected]48d2b7c52014-06-27 01:16:557734
7735 protected:
7736 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
7737 DCHECK(!request_);
Adam Langley32352ad2014-10-14 22:31:007738 context_.Init();
7739 delegate_.set_allow_certificate_errors(true);
7740
[email protected]48d2b7c52014-06-27 01:16:557741 SpawnedTestServer test_server(
7742 SpawnedTestServer::TYPE_HTTPS,
7743 ssl_options,
7744 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7745 ASSERT_TRUE(test_server.Start());
7746
davidben151423e2015-03-23 18:48:367747 request_ = context_.CreateRequest(test_server.GetURL(std::string()),
7748 DEFAULT_PRIORITY, &delegate_);
[email protected]48d2b7c52014-06-27 01:16:557749 request_->Start();
7750
7751 base::RunLoop().Run();
7752 }
7753
Adam Langley32352ad2014-10-14 22:31:007754 void set_fallback_min_version(uint16 version) {
7755 context_.set_fallback_min_version(version);
7756 }
7757
[email protected]48d2b7c52014-06-27 01:16:557758 void ExpectConnection(int version) {
7759 EXPECT_EQ(1, delegate_.response_started_count());
7760 EXPECT_NE(0, delegate_.bytes_received());
7761 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7762 request_->ssl_info().connection_status));
7763 EXPECT_TRUE(request_->ssl_info().connection_status &
7764 SSL_CONNECTION_VERSION_FALLBACK);
7765 }
7766
7767 void ExpectFailure(int error) {
7768 EXPECT_EQ(1, delegate_.response_started_count());
7769 EXPECT_FALSE(request_->status().is_success());
7770 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7771 EXPECT_EQ(error, request_->status().error());
7772 }
7773
7774 private:
7775 TestDelegate delegate_;
Adam Langley32352ad2014-10-14 22:31:007776 FallbackTestURLRequestContext context_;
[email protected]48d2b7c52014-06-27 01:16:557777 scoped_ptr<URLRequest> request_;
7778};
7779
7780// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7781// than necessary.
7782TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7783 SpawnedTestServer::SSLOptions ssl_options(
7784 SpawnedTestServer::SSLOptions::CERT_OK);
7785 ssl_options.tls_intolerant =
7786 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7787
7788 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7789 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7790}
7791
7792// This test is disabled on Android because the remote test server doesn't cause
7793// a TCP reset.
7794#if !defined(OS_ANDROID)
7795// Tests fallback to TLS 1.0 on connection reset.
7796TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7797 SpawnedTestServer::SSLOptions ssl_options(
7798 SpawnedTestServer::SSLOptions::CERT_OK);
7799 ssl_options.tls_intolerant =
7800 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7801 ssl_options.tls_intolerance_type =
7802 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7803
7804 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7805 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7806}
7807#endif // !OS_ANDROID
7808
[email protected]12833302014-07-02 01:57:317809// Tests that we don't fallback on handshake failure with servers that implement
7810// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]48d2b7c52014-06-27 01:16:557811TEST_F(HTTPSFallbackTest, FallbackSCSV) {
[email protected]48d2b7c52014-06-27 01:16:557812 SpawnedTestServer::SSLOptions ssl_options(
7813 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:437814 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]48d2b7c52014-06-27 01:16:557815 // a version fallback.
7816 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:437817 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]48d2b7c52014-06-27 01:16:557818 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7819 // connections are rejected.
7820 ssl_options.fallback_scsv_enabled = true;
7821
7822 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7823
7824 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7825 // intolerance. If the fallback SCSV is processed when the original error
7826 // that caused the fallback should be returned, which should be
7827 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7828 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7829}
7830
[email protected]12833302014-07-02 01:57:317831// Tests that we don't fallback on connection closed with servers that implement
7832// TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
[email protected]12833302014-07-02 01:57:317833TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
[email protected]12833302014-07-02 01:57:317834 SpawnedTestServer::SSLOptions ssl_options(
7835 SpawnedTestServer::SSLOptions::CERT_OK);
davidbenc8dc58c2015-01-06 21:08:437836 // Configure HTTPS server to be intolerant of TLS >= 1.1 in order to trigger
[email protected]12833302014-07-02 01:57:317837 // a version fallback.
7838 ssl_options.tls_intolerant =
davidbenc8dc58c2015-01-06 21:08:437839 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
[email protected]12833302014-07-02 01:57:317840 ssl_options.tls_intolerance_type =
7841 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7842 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7843 // connections are rejected.
7844 ssl_options.fallback_scsv_enabled = true;
7845
7846 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7847
7848 // The original error should be replayed on rejected fallback.
7849 ExpectFailure(ERR_CONNECTION_CLOSED);
7850}
7851
Adam Langley32352ad2014-10-14 22:31:007852// Tests that the SSLv3 fallback doesn't happen by default.
[email protected]48d2b7c52014-06-27 01:16:557853TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7854 SpawnedTestServer::SSLOptions ssl_options(
7855 SpawnedTestServer::SSLOptions::CERT_OK);
7856 ssl_options.tls_intolerant =
7857 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7858
7859 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
Adam Langleyac6f24b42014-10-31 20:24:027860 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
Adam Langley32352ad2014-10-14 22:31:007861}
7862
7863// Tests that the SSLv3 fallback works when explicitly enabled.
7864TEST_F(HTTPSFallbackTest, SSLv3FallbackEnabled) {
7865 SpawnedTestServer::SSLOptions ssl_options(
7866 SpawnedTestServer::SSLOptions::CERT_OK);
7867 ssl_options.tls_intolerant =
7868 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7869 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7870
7871 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
[email protected]48d2b7c52014-06-27 01:16:557872 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7873}
7874
Adam Langley32352ad2014-10-14 22:31:007875// Tests that the SSLv3 fallback triggers on closed connections when explicitly
7876// enabled.
[email protected]48d2b7c52014-06-27 01:16:557877TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
7878 SpawnedTestServer::SSLOptions ssl_options(
7879 SpawnedTestServer::SSLOptions::CERT_OK);
7880 ssl_options.tls_intolerant =
7881 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7882 ssl_options.tls_intolerance_type =
7883 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
Adam Langley32352ad2014-10-14 22:31:007884 set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
[email protected]48d2b7c52014-06-27 01:16:557885
7886 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7887 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7888}
7889
Adam Langley32352ad2014-10-14 22:31:007890// Test that SSLv3 fallback probe connections don't cause sessions to be cached.
7891TEST_F(HTTPSRequestTest, SSLv3FallbackNoCache) {
7892 SpawnedTestServer::SSLOptions ssl_options(
7893 SpawnedTestServer::SSLOptions::CERT_OK);
7894 ssl_options.tls_intolerant =
7895 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7896 ssl_options.tls_intolerance_type =
7897 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7898 ssl_options.record_resume = true;
7899
7900 SpawnedTestServer test_server(
7901 SpawnedTestServer::TYPE_HTTPS,
7902 ssl_options,
7903 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7904 ASSERT_TRUE(test_server.Start());
7905
7906 SSLClientSocket::ClearSessionCache();
7907
7908 // Make a connection that does a probe fallback to SSLv3 but fails because
7909 // SSLv3 fallback is disabled. We don't wish a session for this connection to
7910 // be inserted locally.
7911 {
7912 TestDelegate delegate;
7913 FallbackTestURLRequestContext context(true);
7914
Adam Langleyac6f24b42014-10-31 20:24:027915 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_TLS1);
Adam Langley32352ad2014-10-14 22:31:007916 context.Init();
7917 scoped_ptr<URLRequest> request(context.CreateRequest(
davidben151423e2015-03-23 18:48:367918 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:007919 request->Start();
7920
7921 base::RunLoop().Run();
7922
7923 EXPECT_EQ(1, delegate.response_started_count());
7924 EXPECT_FALSE(request->status().is_success());
7925 EXPECT_EQ(URLRequestStatus::FAILED, request->status().status());
7926 EXPECT_EQ(ERR_SSL_FALLBACK_BEYOND_MINIMUM_VERSION,
7927 request->status().error());
7928 }
7929
7930 // Now allow SSLv3 connections and request the session cache log.
7931 {
7932 TestDelegate delegate;
7933 FallbackTestURLRequestContext context(true);
7934 context.set_fallback_min_version(SSL_PROTOCOL_VERSION_SSL3);
7935
7936 context.Init();
davidben151423e2015-03-23 18:48:367937 scoped_ptr<URLRequest> request(context.CreateRequest(
7938 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &delegate));
Adam Langley32352ad2014-10-14 22:31:007939 request->Start();
7940
7941 base::RunLoop().Run();
7942
7943 EXPECT_EQ(1, delegate.response_started_count());
7944 EXPECT_NE(0, delegate.bytes_received());
7945 EXPECT_EQ(SSL_CONNECTION_VERSION_SSL3, SSLConnectionStatusToVersion(
7946 request->ssl_info().connection_status));
7947 EXPECT_TRUE(request->ssl_info().connection_status &
7948 SSL_CONNECTION_VERSION_FALLBACK);
7949
7950 std::vector<std::string> lines;
7951 // If no sessions were cached then the server should have seen two sessions
7952 // inserted with no lookups.
7953 AssertTwoDistinctSessionsInserted(delegate.data_received());
7954 }
7955}
7956
[email protected]48d2b7c52014-06-27 01:16:557957// This test is disabled on Android because the remote test server doesn't cause
[email protected]5aea79182014-07-14 20:43:417958// a TCP reset.
7959#if !defined(OS_ANDROID)
[email protected]48d2b7c52014-06-27 01:16:557960// Tests that a reset connection does not fallback down to SSL3.
7961TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
7962 SpawnedTestServer::SSLOptions ssl_options(
7963 SpawnedTestServer::SSLOptions::CERT_OK);
7964 ssl_options.tls_intolerant =
7965 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7966 ssl_options.tls_intolerance_type =
7967 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7968
7969 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7970 ExpectFailure(ERR_CONNECTION_RESET);
7971}
[email protected]5aea79182014-07-14 20:43:417972#endif // !OS_ANDROID
[email protected]48d2b7c52014-06-27 01:16:557973
[email protected]a8fed1742013-12-27 02:14:247974class HTTPSSessionTest : public testing::Test {
7975 public:
7976 HTTPSSessionTest() : default_context_(true) {
[email protected]cba24642014-08-15 20:49:597977 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:247978
7979 default_context_.set_network_delegate(&default_network_delegate_);
7980 default_context_.set_cert_verifier(&cert_verifier_);
7981 default_context_.Init();
7982 }
dcheng67be2b1f2014-10-27 21:47:297983 ~HTTPSSessionTest() override {}
[email protected]a8fed1742013-12-27 02:14:247984
7985 protected:
7986 MockCertVerifier cert_verifier_;
7987 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7988 TestURLRequestContext default_context_;
7989};
7990
7991// Tests that session resumption is not attempted if an invalid certificate
7992// is presented.
7993TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7994 SpawnedTestServer::SSLOptions ssl_options;
7995 ssl_options.record_resume = true;
7996 SpawnedTestServer test_server(
7997 SpawnedTestServer::TYPE_HTTPS,
7998 ssl_options,
7999 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
8000 ASSERT_TRUE(test_server.Start());
8001
8002 SSLClientSocket::ClearSessionCache();
8003
8004 // Simulate the certificate being expired and attempt a connection.
[email protected]cba24642014-08-15 20:49:598005 cert_verifier_.set_default_result(ERR_CERT_DATE_INVALID);
[email protected]a8fed1742013-12-27 02:14:248006 {
8007 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198008 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368009 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248010
[email protected]f7022f32014-08-21 16:32:198011 r->Start();
8012 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248013
8014 base::RunLoop().Run();
8015
8016 EXPECT_EQ(1, d.response_started_count());
8017 }
8018
8019 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
8020 CloseAllConnections();
8021
8022 // Now change the certificate to be acceptable (so that the response is
8023 // loaded), and ensure that no session id is presented to the peer.
[email protected]cba24642014-08-15 20:49:598024 cert_verifier_.set_default_result(OK);
[email protected]a8fed1742013-12-27 02:14:248025 {
8026 TestDelegate d;
[email protected]f7022f32014-08-21 16:32:198027 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368028 test_server.GetURL("ssl-session-cache"), DEFAULT_PRIORITY, &d));
[email protected]a8fed1742013-12-27 02:14:248029
[email protected]f7022f32014-08-21 16:32:198030 r->Start();
8031 EXPECT_TRUE(r->is_pending());
[email protected]a8fed1742013-12-27 02:14:248032
8033 base::RunLoop().Run();
8034
8035 // The response will look like;
8036 // insert abc
8037 // insert xyz
8038 //
8039 // With a newline at the end which makes the split think that there are
8040 // three lines.
8041 //
8042 // If a session was presented (eg: a bug), then the response would look
8043 // like;
8044 // insert abc
8045 // lookup abc
8046 // insert xyz
8047
8048 EXPECT_EQ(1, d.response_started_count());
Adam Langley32352ad2014-10-14 22:31:008049 AssertTwoDistinctSessionsInserted(d.data_received());
[email protected]a8fed1742013-12-27 02:14:248050 }
8051}
8052
[email protected]dffe8242012-03-20 15:14:278053// This the fingerprint of the "Testing CA" certificate used by the testserver.
8054// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:268055static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:278056 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
8057 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
8058
[email protected]51523f52013-07-31 21:57:288059// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
8060// testserver.
8061static const SHA256HashValue kOCSPTestCertSPKI = { {
8062 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
8063 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
8064 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
8065 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
8066} };
8067
[email protected]dffe8242012-03-20 15:14:278068// This is the policy OID contained in the certificates that testserver
8069// generates.
8070static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
8071
8072class HTTPSOCSPTest : public HTTPSRequestTest {
8073 public:
8074 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:098075 : context_(true),
[email protected]b6f2de32012-08-17 04:35:088076 ev_test_policy_(
8077 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
8078 kOCSPTestCertFingerprint,
8079 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:028080 }
8081
dcheng67be2b1f2014-10-27 21:47:298082 void SetUp() override {
[email protected]ef2bf422012-05-11 03:27:098083 SetupContext(&context_);
8084 context_.Init();
[email protected]dffe8242012-03-20 15:14:278085
[email protected]cba24642014-08-15 20:49:598086 scoped_refptr<X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:208087 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
dchengc2e01e82014-08-27 00:24:428088 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert.get());
[email protected]90499482013-06-01 00:39:508089 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:278090
[email protected]a592c0432012-12-01 18:10:298091#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:098092 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:278093 EnsureNSSHttpIOInit();
8094#endif
8095 }
8096
[email protected]ce7d0cbc2013-05-03 18:57:228097 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:278098 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:538099 // We always overwrite out_cert_status.
8100 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:228101 SpawnedTestServer test_server(
8102 SpawnedTestServer::TYPE_HTTPS,
8103 ssl_options,
8104 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:278105 ASSERT_TRUE(test_server.Start());
8106
8107 TestDelegate d;
8108 d.set_allow_certificate_errors(true);
[email protected]f7022f32014-08-21 16:32:198109 scoped_ptr<URLRequest> r(context_.CreateRequest(
davidben151423e2015-03-23 18:48:368110 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198111 r->Start();
[email protected]dffe8242012-03-20 15:14:278112
[email protected]255620da2013-08-19 13:14:298113 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:278114
8115 EXPECT_EQ(1, d.response_started_count());
[email protected]f7022f32014-08-21 16:32:198116 *out_cert_status = r->ssl_info().cert_status;
[email protected]dffe8242012-03-20 15:14:278117 }
8118
dcheng67be2b1f2014-10-27 21:47:298119 ~HTTPSOCSPTest() override {
[email protected]a592c0432012-12-01 18:10:298120#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278121 ShutdownNSSHttpIO();
8122#endif
8123 }
8124
[email protected]a13234c2012-03-20 21:45:028125 protected:
8126 // SetupContext configures the URLRequestContext that will be used for making
8127 // connetions to testserver. This can be overridden in test subclasses for
8128 // different behaviour.
8129 virtual void SetupContext(URLRequestContext* context) {
8130 context->set_ssl_config_service(
8131 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208132 true /* online revocation checking */,
8133 false /* require rev. checking for local
8134 anchors */));
[email protected]a13234c2012-03-20 21:45:028135 }
8136
[email protected]dffe8242012-03-20 15:14:278137 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:098138 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:088139 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:278140};
8141
[email protected]a13234c2012-03-20 21:45:028142static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:018143#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028144 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
8145 // have that ability on other platforms.
8146 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
8147#else
8148 return 0;
8149#endif
8150}
8151
[email protected]3a86a712013-07-30 07:16:208152// SystemSupportsHardFailRevocationChecking returns true iff the current
8153// operating system supports revocation checking and can distinguish between
8154// situations where a given certificate lacks any revocation information (eg:
8155// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
8156// revocation information cannot be obtained (eg: the CRL was unreachable).
8157// If it does not, then tests which rely on 'hard fail' behaviour should be
8158// skipped.
8159static bool SystemSupportsHardFailRevocationChecking() {
8160#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
8161 return true;
8162#else
8163 return false;
8164#endif
8165}
8166
[email protected]a13234c2012-03-20 21:45:028167// SystemUsesChromiumEVMetadata returns true iff the current operating system
8168// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
8169// several tests are effected because our testing EV certificate won't be
8170// recognised as EV.
8171static bool SystemUsesChromiumEVMetadata() {
[email protected]e1b2d732014-03-28 16:20:328172#if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
[email protected]5c504192012-03-27 19:00:578173 // http://crbug.com/117478 - OpenSSL does not support EV validation.
8174 return false;
[email protected]e1b2d732014-03-28 16:20:328175#elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
8176 // On OS X and Android, we use the system to tell us whether a certificate is
8177 // EV or not and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:018178 return false;
8179#else
8180 return true;
8181#endif
8182}
8183
[email protected]b6f2de32012-08-17 04:35:088184static bool SystemSupportsOCSP() {
davidbend1fb2f12014-11-08 02:51:008185#if defined(USE_OPENSSL_CERTS)
[email protected]5c504192012-03-27 19:00:578186 // http://crbug.com/117478 - OpenSSL does not support OCSP.
8187 return false;
8188#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:028189 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8190#elif defined(OS_ANDROID)
8191 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
8192 return false;
8193#else
8194 return true;
8195#endif
8196}
8197
davidbend1fb2f12014-11-08 02:51:008198static bool SystemSupportsOCSPStapling() {
8199#if defined(USE_NSS)
8200 return true;
8201#elif defined(OS_WIN)
8202 return base::win::GetVersion() >= base::win::VERSION_VISTA;
8203#else
8204 return false;
8205#endif
8206}
8207
[email protected]dffe8242012-03-20 15:14:278208TEST_F(HTTPSOCSPTest, Valid) {
8209 if (!SystemSupportsOCSP()) {
8210 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8211 return;
8212 }
8213
[email protected]ce7d0cbc2013-05-03 18:57:228214 SpawnedTestServer::SSLOptions ssl_options(
8215 SpawnedTestServer::SSLOptions::CERT_AUTO);
8216 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:278217
[email protected]924e9f92012-12-16 22:00:538218 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128219 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278220
8221 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8222
[email protected]a13234c2012-03-20 21:45:028223 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8224 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:278225
8226 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8227}
8228
8229TEST_F(HTTPSOCSPTest, Revoked) {
8230 if (!SystemSupportsOCSP()) {
8231 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8232 return;
8233 }
8234
[email protected]ce7d0cbc2013-05-03 18:57:228235 SpawnedTestServer::SSLOptions ssl_options(
8236 SpawnedTestServer::SSLOptions::CERT_AUTO);
8237 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:278238
8239 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128240 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278241
[email protected]a592c0432012-12-01 18:10:298242#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:278243 // Doesn't pass on OS X yet for reasons that need to be investigated.
8244 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8245#endif
8246 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8247 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8248}
8249
8250TEST_F(HTTPSOCSPTest, Invalid) {
8251 if (!SystemSupportsOCSP()) {
8252 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8253 return;
8254 }
8255
[email protected]ce7d0cbc2013-05-03 18:57:228256 SpawnedTestServer::SSLOptions ssl_options(
8257 SpawnedTestServer::SSLOptions::CERT_AUTO);
8258 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:278259
[email protected]924e9f92012-12-16 22:00:538260 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128261 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:278262
[email protected]a13234c2012-03-20 21:45:028263 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:278264 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:278265
8266 // Without a positive OCSP response, we shouldn't show the EV status.
8267 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8268 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8269}
[email protected]a13234c2012-03-20 21:45:028270
davidbend1fb2f12014-11-08 02:51:008271TEST_F(HTTPSOCSPTest, ValidStapled) {
8272 if (!SystemSupportsOCSPStapling()) {
8273 LOG(WARNING)
8274 << "Skipping test because system doesn't support OCSP stapling";
8275 return;
8276 }
8277
8278 SpawnedTestServer::SSLOptions ssl_options(
8279 SpawnedTestServer::SSLOptions::CERT_AUTO);
8280 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8281 ssl_options.staple_ocsp_response = true;
8282 ssl_options.ocsp_server_unavailable = true;
8283
8284 CertStatus cert_status;
8285 DoConnection(ssl_options, &cert_status);
8286
8287 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8288
8289 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8290 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8291
8292 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8293}
8294
davidben6c3191b2014-11-21 22:38:048295// Disabled on NSS ports. See https://crbug.com/431716.
8296#if defined(USE_NSS)
8297#define MAYBE_RevokedStapled DISABLED_RevokedStapled
8298#else
8299#define MAYBE_RevokedStapled RevokedStapled
8300#endif
8301TEST_F(HTTPSOCSPTest, MAYBE_RevokedStapled) {
davidbend1fb2f12014-11-08 02:51:008302 if (!SystemSupportsOCSPStapling()) {
8303 LOG(WARNING)
8304 << "Skipping test because system doesn't support OCSP stapling";
8305 return;
8306 }
8307
8308 SpawnedTestServer::SSLOptions ssl_options(
8309 SpawnedTestServer::SSLOptions::CERT_AUTO);
8310 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8311 ssl_options.staple_ocsp_response = true;
8312 ssl_options.ocsp_server_unavailable = true;
8313
8314 CertStatus cert_status;
8315 DoConnection(ssl_options, &cert_status);
8316
8317 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8318 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8319 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8320}
8321
[email protected]3a86a712013-07-30 07:16:208322class HTTPSHardFailTest : public HTTPSOCSPTest {
8323 protected:
dchengb03027d2014-10-21 12:00:208324 void SetupContext(URLRequestContext* context) override {
[email protected]3a86a712013-07-30 07:16:208325 context->set_ssl_config_service(
8326 new TestSSLConfigService(false /* check for EV */,
8327 false /* online revocation checking */,
8328 true /* require rev. checking for local
8329 anchors */));
8330 }
8331};
8332
[email protected]3a86a712013-07-30 07:16:208333TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
8334 if (!SystemSupportsOCSP()) {
8335 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8336 return;
8337 }
8338
8339 if (!SystemSupportsHardFailRevocationChecking()) {
8340 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
8341 << "revocation checking";
8342 return;
8343 }
8344
8345 SpawnedTestServer::SSLOptions ssl_options(
8346 SpawnedTestServer::SSLOptions::CERT_AUTO);
8347 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8348
8349 CertStatus cert_status;
8350 DoConnection(ssl_options, &cert_status);
8351
8352 EXPECT_EQ(CERT_STATUS_REVOKED,
8353 cert_status & CERT_STATUS_REVOKED);
8354
8355 // Without a positive OCSP response, we shouldn't show the EV status.
8356 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8357}
8358
[email protected]a13234c2012-03-20 21:45:028359class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
8360 protected:
dchengb03027d2014-10-21 12:00:208361 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028362 context->set_ssl_config_service(
8363 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208364 false /* online revocation checking */,
8365 false /* require rev. checking for local
8366 anchors */));
[email protected]a13234c2012-03-20 21:45:028367 }
8368};
8369
8370TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
8371 if (!SystemSupportsOCSP()) {
8372 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8373 return;
8374 }
8375
[email protected]ce7d0cbc2013-05-03 18:57:228376 SpawnedTestServer::SSLOptions ssl_options(
8377 SpawnedTestServer::SSLOptions::CERT_AUTO);
8378 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028379 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8380
[email protected]924e9f92012-12-16 22:00:538381 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128382 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028383
8384 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8385 cert_status & CERT_STATUS_ALL_ERRORS);
8386
8387 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088388 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8389 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028390}
8391
[email protected]be0fff62013-08-29 23:37:488392TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
8393 if (!SystemSupportsOCSP()) {
8394 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8395 return;
8396 }
8397
8398 SpawnedTestServer::SSLOptions ssl_options(
8399 SpawnedTestServer::SSLOptions::CERT_AUTO);
8400 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
8401 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8402
8403 CertStatus cert_status;
8404 DoConnection(ssl_options, &cert_status);
8405
8406 // Currently only works for Windows. When using NSS or OS X, it's not
8407 // possible to determine whether the check failed because of actual
8408 // revocation or because there was an OCSP failure.
8409#if defined(OS_WIN)
8410 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8411#else
8412 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8413#endif
8414
8415 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8416 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8417 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8418}
8419
[email protected]a13234c2012-03-20 21:45:028420TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
8421 if (!SystemSupportsOCSP()) {
8422 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8423 return;
8424 }
8425
[email protected]ce7d0cbc2013-05-03 18:57:228426 SpawnedTestServer::SSLOptions ssl_options(
8427 SpawnedTestServer::SSLOptions::CERT_AUTO);
8428 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:028429 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
8430
8431 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128432 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028433
8434 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8435
8436 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8437 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:088438 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8439 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028440}
8441
8442TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
8443 if (!SystemSupportsOCSP()) {
8444 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8445 return;
8446 }
8447
[email protected]ce7d0cbc2013-05-03 18:57:228448 SpawnedTestServer::SSLOptions ssl_options(
8449 SpawnedTestServer::SSLOptions::CERT_AUTO);
8450 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028451 SSLConfigService::SetCRLSet(
8452 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8453
8454 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128455 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028456
8457 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8458 cert_status & CERT_STATUS_ALL_ERRORS);
8459
8460 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:088461 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8462 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028463}
8464
[email protected]51523f52013-07-31 21:57:288465TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
8466 if (!SystemSupportsOCSP()) {
8467 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8468 return;
8469 }
8470
8471 SpawnedTestServer::SSLOptions ssl_options(
8472 SpawnedTestServer::SSLOptions::CERT_AUTO);
8473 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
8474 SSLConfigService::SetCRLSet(
8475 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8476 false, &kOCSPTestCertSPKI, "")));
8477
8478 CertStatus cert_status;
8479 DoConnection(ssl_options, &cert_status);
8480
8481 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
8482 // revocation check for EV.
8483 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8484 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
8485 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
8486 EXPECT_FALSE(
8487 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8488}
8489
8490TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
8491 if (!SystemSupportsOCSP()) {
8492 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8493 return;
8494 }
8495
[email protected]ce7d0cbc2013-05-03 18:57:228496 SpawnedTestServer::SSLOptions ssl_options(
8497 SpawnedTestServer::SSLOptions::CERT_AUTO);
8498 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028499 SSLConfigService::SetCRLSet(
8500 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
8501
[email protected]51523f52013-07-31 21:57:288502 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:128503 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028504
[email protected]51523f52013-07-31 21:57:288505 // Even with a fresh CRLSet, we should still do online revocation checks when
8506 // the certificate chain isn't covered by the CRLSet, which it isn't in this
8507 // test.
8508 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
8509 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:028510
[email protected]51523f52013-07-31 21:57:288511 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:028512 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:288513 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:028514}
8515
[email protected]b6f2de32012-08-17 04:35:088516TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
8517 // Test that when EV verification is requested, but online revocation
8518 // checking is disabled, and the leaf certificate is not in fact EV, that
8519 // no revocation checking actually happens.
8520 if (!SystemSupportsOCSP()) {
8521 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
8522 return;
8523 }
8524
8525 // Unmark the certificate's OID as EV, which should disable revocation
8526 // checking (as per the user preference)
8527 ev_test_policy_.reset();
8528
[email protected]ce7d0cbc2013-05-03 18:57:228529 SpawnedTestServer::SSLOptions ssl_options(
8530 SpawnedTestServer::SSLOptions::CERT_AUTO);
8531 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:088532 SSLConfigService::SetCRLSet(
8533 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8534
8535 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128536 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:088537
8538 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8539
8540 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8541 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8542}
8543
[email protected]a13234c2012-03-20 21:45:028544class HTTPSCRLSetTest : public HTTPSOCSPTest {
8545 protected:
dchengb03027d2014-10-21 12:00:208546 void SetupContext(URLRequestContext* context) override {
[email protected]a13234c2012-03-20 21:45:028547 context->set_ssl_config_service(
8548 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:208549 false /* online revocation checking */,
8550 false /* require rev. checking for local
8551 anchors */));
[email protected]a13234c2012-03-20 21:45:028552 }
8553};
8554
8555TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:228556 SpawnedTestServer::SSLOptions ssl_options(
8557 SpawnedTestServer::SSLOptions::CERT_AUTO);
8558 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:028559 SSLConfigService::SetCRLSet(
8560 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
8561
[email protected]924e9f92012-12-16 22:00:538562 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:128563 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:028564
8565 // If we're not trying EV verification then, even if the CRLSet has expired,
8566 // we don't fall back to online revocation checks.
8567 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
8568 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8569 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
8570}
[email protected]51523f52013-07-31 21:57:288571
8572TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
[email protected]591cffcd2014-08-18 20:02:308573#if defined(OS_ANDROID)
[email protected]51523f52013-07-31 21:57:288574 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
8575 return;
8576#endif
8577
8578 SpawnedTestServer::SSLOptions ssl_options(
8579 SpawnedTestServer::SSLOptions::CERT_AUTO);
8580 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
8581 ssl_options.cert_serial = 10;
8582 SSLConfigService::SetCRLSet(
8583 scoped_refptr<CRLSet>(CRLSet::ForTesting(
8584 false, &kOCSPTestCertSPKI, "\x0a")));
8585
8586 CertStatus cert_status = 0;
8587 DoConnection(ssl_options, &cert_status);
8588
8589 // If the certificate is recorded as revoked in the CRLSet, that should be
8590 // reflected without online revocation checking.
8591 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
8592 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
8593 EXPECT_FALSE(
8594 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
8595}
[email protected]316c1e5e2012-09-12 15:17:448596#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:278597
[email protected]316c1e5e2012-09-12 15:17:448598#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:318599class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:118600 public:
[email protected]d9fca99a2012-02-24 16:16:208601 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:228602 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:158603 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:118604 }
8605
[email protected]b89ca032009-08-31 21:41:318606 protected:
[email protected]ce7d0cbc2013-05-03 18:57:228607 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:318608};
8609
[email protected]d2a133182012-08-05 16:44:088610// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:098611TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:088612 ASSERT_TRUE(test_server_.Start());
8613
[email protected]9d5730b2012-08-24 17:42:498614 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:348615 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:088616
8617 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:088618 job_factory.SetProtocolHandler(
8619 "ftp",
[email protected]e0f35c92013-05-08 16:04:348620 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:088621 default_context_.set_job_factory(&job_factory);
8622
8623 TestDelegate d;
8624 {
davidben151423e2015-03-23 18:48:368625 scoped_ptr<URLRequest> r(
8626 default_context_.CreateRequest(url, DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198627 r->Start();
8628 EXPECT_TRUE(r->is_pending());
[email protected]d2a133182012-08-05 16:44:088629
[email protected]255620da2013-08-19 13:14:298630 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:088631
[email protected]f7022f32014-08-21 16:32:198632 EXPECT_FALSE(r->is_pending());
8633 EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
8634 EXPECT_EQ(ERR_UNSAFE_PORT, r->status().error());
[email protected]d2a133182012-08-05 16:44:088635 }
8636}
8637
[email protected]5accf7332009-11-24 03:41:388638// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128639TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:118640 ASSERT_TRUE(test_server_.Start());
8641
[email protected]a25e90e2009-09-09 17:05:378642 TestDelegate d;
8643 {
[email protected]f7022f32014-08-21 16:32:198644 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368645 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198646 r->Start();
8647 EXPECT_TRUE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378648
[email protected]255620da2013-08-19 13:14:298649 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:378650
[email protected]f7022f32014-08-21 16:32:198651 EXPECT_FALSE(r->is_pending());
[email protected]a25e90e2009-09-09 17:05:378652 EXPECT_EQ(1, d.response_started_count());
8653 EXPECT_FALSE(d.received_data_before_response());
8654 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:198655 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198656 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198657 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198658 r->GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:378659 }
8660}
8661
[email protected]7df70012010-02-04 00:09:558662// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128663TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:118664 ASSERT_TRUE(test_server_.Start());
8665
[email protected]6cdfd7f2013-02-08 20:40:158666 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278667 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028668 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278669 TestDelegate d;
8670 {
[email protected]f7022f32014-08-21 16:32:198671 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368672 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198673 r->Start();
8674 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278675
[email protected]255620da2013-08-19 13:14:298676 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278677
8678 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498679 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278680
[email protected]f7022f32014-08-21 16:32:198681 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278682 EXPECT_EQ(1, d.response_started_count());
8683 EXPECT_FALSE(d.received_data_before_response());
8684 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:198685 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198686 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198687 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198688 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278689 }
8690}
8691
[email protected]e9ecbd12009-12-20 18:44:408692// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128693TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:118694 ASSERT_TRUE(test_server_.Start());
8695
[email protected]6cdfd7f2013-02-08 20:40:158696 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278697 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028698 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278699 TestDelegate d;
8700 {
[email protected]f7022f32014-08-21 16:32:198701 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]95409e12010-08-17 20:07:118702 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:368703 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198704 r->Start();
8705 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278706
[email protected]255620da2013-08-19 13:14:298707 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278708
8709 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498710 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278711
[email protected]f7022f32014-08-21 16:32:198712 EXPECT_FALSE(r->is_pending());
[email protected]6d81b482011-02-22 19:47:198713 EXPECT_EQ(test_server_.host_port_pair().host(),
[email protected]f7022f32014-08-21 16:32:198714 r->GetSocketAddress().host());
[email protected]6d81b482011-02-22 19:47:198715 EXPECT_EQ(test_server_.host_port_pair().port(),
[email protected]f7022f32014-08-21 16:32:198716 r->GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:278717 EXPECT_EQ(1, d.response_started_count());
8718 EXPECT_FALSE(d.received_data_before_response());
8719 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:258720
8721 LoadTimingInfo load_timing_info;
[email protected]f7022f32014-08-21 16:32:198722 r->GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:258723 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:278724 }
8725}
8726
[email protected]49abd652010-08-05 05:04:538727// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128728TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:118729 ASSERT_TRUE(test_server_.Start());
8730
[email protected]6cdfd7f2013-02-08 20:40:158731 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278732 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028733 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278734 TestDelegate d;
8735 {
[email protected]f7022f32014-08-21 16:32:198736 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8737 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8738 "wrong_password"),
davidben151423e2015-03-23 18:48:368739 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198740 r->Start();
8741 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278742
[email protected]255620da2013-08-19 13:14:298743 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278744
8745 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498746 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278747
[email protected]f7022f32014-08-21 16:32:198748 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278749 EXPECT_EQ(1, d.response_started_count());
8750 EXPECT_FALSE(d.received_data_before_response());
8751 EXPECT_EQ(d.bytes_received(), 0);
8752 }
8753}
8754
[email protected]cde4e80d2009-10-16 19:58:158755// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128756TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:118757 ASSERT_TRUE(test_server_.Start());
8758
[email protected]6cdfd7f2013-02-08 20:40:158759 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588760 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8761 app_path = app_path.AppendASCII("LICENSE");
8762 TestDelegate d;
8763 // Set correct login credentials. The delegate will be asked for them when
8764 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588765 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588766 {
[email protected]f7022f32014-08-21 16:32:198767 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8768 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8769 "wrong_password"),
davidben151423e2015-03-23 18:48:368770 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198771 r->Start();
8772 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588773
[email protected]255620da2013-08-19 13:14:298774 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588775
8776 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498777 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588778
[email protected]f7022f32014-08-21 16:32:198779 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588780 EXPECT_EQ(1, d.response_started_count());
8781 EXPECT_FALSE(d.received_data_before_response());
8782 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8783 }
8784}
8785
[email protected]49abd652010-08-05 05:04:538786// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128787TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:118788 ASSERT_TRUE(test_server_.Start());
8789
[email protected]6cdfd7f2013-02-08 20:40:158790 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:278791 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:028792 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:278793 TestDelegate d;
8794 {
davidben151423e2015-03-23 18:48:368795 scoped_ptr<URLRequest> r(
8796 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8797 "/LICENSE", "wrong_user", "chrome"),
8798 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198799 r->Start();
8800 EXPECT_TRUE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278801
[email protected]255620da2013-08-19 13:14:298802 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:278803
8804 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498805 base::GetFileSize(app_path, &file_size);
[email protected]dd265012009-01-08 20:45:278806
[email protected]f7022f32014-08-21 16:32:198807 EXPECT_FALSE(r->is_pending());
[email protected]dd265012009-01-08 20:45:278808 EXPECT_EQ(1, d.response_started_count());
8809 EXPECT_FALSE(d.received_data_before_response());
8810 EXPECT_EQ(d.bytes_received(), 0);
8811 }
8812}
[email protected]8b8a197d2009-08-26 15:57:588813
[email protected]cde4e80d2009-10-16 19:58:158814// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128815TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:118816 ASSERT_TRUE(test_server_.Start());
8817
[email protected]6cdfd7f2013-02-08 20:40:158818 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:588819 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8820 app_path = app_path.AppendASCII("LICENSE");
8821 TestDelegate d;
8822 // Set correct login credentials. The delegate will be asked for them when
8823 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588824 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:588825 {
davidben151423e2015-03-23 18:48:368826 scoped_ptr<URLRequest> r(
8827 default_context_.CreateRequest(test_server_.GetURLWithUserAndPassword(
8828 "/LICENSE", "wrong_user", "chrome"),
8829 DEFAULT_PRIORITY, &d));
[email protected]f7022f32014-08-21 16:32:198830 r->Start();
8831 EXPECT_TRUE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588832
[email protected]255620da2013-08-19 13:14:298833 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:588834
8835 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498836 base::GetFileSize(app_path, &file_size);
[email protected]8b8a197d2009-08-26 15:57:588837
[email protected]f7022f32014-08-21 16:32:198838 EXPECT_FALSE(r->is_pending());
[email protected]8b8a197d2009-08-26 15:57:588839 EXPECT_EQ(1, d.response_started_count());
8840 EXPECT_FALSE(d.received_data_before_response());
8841 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8842 }
8843}
[email protected]60a3df52009-09-22 16:13:248844
[email protected]cde4e80d2009-10-16 19:58:158845// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128846TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:118847 ASSERT_TRUE(test_server_.Start());
8848
[email protected]6cdfd7f2013-02-08 20:40:158849 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248850 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8851 app_path = app_path.AppendASCII("LICENSE");
8852
8853 scoped_ptr<TestDelegate> d(new TestDelegate);
8854 {
8855 // Pass correct login identity in the URL.
[email protected]f7022f32014-08-21 16:32:198856 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
[email protected]2ca01e52013-10-31 22:05:198857 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
davidben151423e2015-03-23 18:48:368858 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:198859 r->Start();
8860 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248861
[email protected]255620da2013-08-19 13:14:298862 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248863
8864 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498865 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248866
[email protected]f7022f32014-08-21 16:32:198867 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248868 EXPECT_EQ(1, d->response_started_count());
8869 EXPECT_FALSE(d->received_data_before_response());
8870 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8871 }
8872
8873 d.reset(new TestDelegate);
8874 {
8875 // This request should use cached identity from previous request.
[email protected]f7022f32014-08-21 16:32:198876 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368877 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:198878 r->Start();
8879 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248880
[email protected]255620da2013-08-19 13:14:298881 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248882
8883 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498884 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248885
[email protected]f7022f32014-08-21 16:32:198886 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248887 EXPECT_EQ(1, d->response_started_count());
8888 EXPECT_FALSE(d->received_data_before_response());
8889 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8890 }
8891}
8892
[email protected]cde4e80d2009-10-16 19:58:158893// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:128894TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:118895 ASSERT_TRUE(test_server_.Start());
8896
[email protected]6cdfd7f2013-02-08 20:40:158897 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:248898 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8899 app_path = app_path.AppendASCII("LICENSE");
8900
8901 scoped_ptr<TestDelegate> d(new TestDelegate);
8902 // Set correct login credentials. The delegate will be asked for them when
8903 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:588904 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:248905 {
[email protected]f7022f32014-08-21 16:32:198906 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
8907 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome",
8908 "wrong_password"),
davidben151423e2015-03-23 18:48:368909 DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:198910 r->Start();
8911 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248912
[email protected]255620da2013-08-19 13:14:298913 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248914
8915 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498916 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248917
[email protected]f7022f32014-08-21 16:32:198918 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248919 EXPECT_EQ(1, d->response_started_count());
8920 EXPECT_FALSE(d->received_data_before_response());
8921 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8922 }
8923
8924 // Use a new delegate without explicit credentials. The cached ones should be
8925 // used.
8926 d.reset(new TestDelegate);
8927 {
8928 // Don't pass wrong credentials in the URL, they would override valid cached
8929 // ones.
[email protected]f7022f32014-08-21 16:32:198930 scoped_ptr<URLRequest> r(default_context_.CreateRequest(
davidben151423e2015-03-23 18:48:368931 test_server_.GetURL("/LICENSE"), DEFAULT_PRIORITY, d.get()));
[email protected]f7022f32014-08-21 16:32:198932 r->Start();
8933 EXPECT_TRUE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248934
[email protected]255620da2013-08-19 13:14:298935 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:248936
8937 int64 file_size = 0;
[email protected]56285702013-12-04 18:22:498938 base::GetFileSize(app_path, &file_size);
[email protected]60a3df52009-09-22 16:13:248939
[email protected]f7022f32014-08-21 16:32:198940 EXPECT_FALSE(r->is_pending());
[email protected]60a3df52009-09-22 16:13:248941 EXPECT_EQ(1, d->response_started_count());
8942 EXPECT_FALSE(d->received_data_before_response());
8943 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8944 }
8945}
[email protected]316c1e5e2012-09-12 15:17:448946#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:518947
8948} // namespace net