blob: 6f5786e51f3304823ea4e8319b49e16defd0db08 [file] [log] [blame]
[email protected]9045b8822012-01-13 20:35:351// Copyright (c) 2012 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commit586acc5fe2008-07-26 22:42:524
[email protected]ea224582008-12-07 20:25:465#include "build/build_config.h"
6
[email protected]9396b252008-09-29 17:29:387#if defined(OS_WIN)
[email protected]d8eb84242010-09-25 02:25:068#include <windows.h>
[email protected]aa84a7e2012-03-15 21:29:069#include <shlobj.h>
[email protected]9396b252008-09-29 17:29:3810#endif
11
initial.commit586acc5fe2008-07-26 22:42:5212#include <algorithm>
13#include <string>
14
[email protected]aad63572011-05-24 20:14:3915#include "base/basictypes.h"
[email protected]218aa6a12011-09-13 17:38:3816#include "base/bind.h"
[email protected]8523ba52011-05-22 19:00:5817#include "base/compiler_specific.h"
[email protected]399b8702009-05-01 20:34:0218#include "base/file_util.h"
[email protected]34b2b002009-11-20 06:53:2819#include "base/format_macros.h"
[email protected]084262c2011-12-01 21:12:4720#include "base/memory/weak_ptr.h"
[email protected]7f86564d2013-07-18 00:41:2221#include "base/message_loop/message_loop.h"
[email protected]255620da2013-08-19 13:14:2922#include "base/message_loop/message_loop_proxy.h"
initial.commit586acc5fe2008-07-26 22:42:5223#include "base/path_service.h"
[email protected]255620da2013-08-19 13:14:2924#include "base/run_loop.h"
[email protected]4dc3ad4f2013-06-11 07:15:5025#include "base/strings/string_number_conversions.h"
[email protected]d069c11a2013-04-13 00:01:5526#include "base/strings/string_piece.h"
[email protected]d778e0422013-03-06 18:10:2227#include "base/strings/string_split.h"
[email protected]7f86564d2013-07-18 00:41:2228#include "base/strings/string_util.h"
29#include "base/strings/stringprintf.h"
[email protected]750b2f3c2013-06-07 18:41:0530#include "base/strings/utf_string_conversions.h"
[email protected]58e32bb2013-01-21 18:23:2531#include "net/base/capturing_net_log.h"
initial.commit586acc5fe2008-07-26 22:42:5232#include "net/base/load_flags.h"
[email protected]58e32bb2013-01-21 18:23:2533#include "net/base/load_timing_info.h"
34#include "net/base/load_timing_info_test_util.h"
[email protected]d8eb84242010-09-25 02:25:0635#include "net/base/net_errors.h"
[email protected]9e743cd2010-03-16 07:03:5336#include "net/base/net_log.h"
37#include "net/base/net_log_unittest.h"
initial.commit586acc5fe2008-07-26 22:42:5238#include "net/base/net_module.h"
39#include "net/base/net_util.h"
[email protected]42fdb452012-11-01 12:44:4040#include "net/base/test_data_directory.h"
[email protected]f288ef02012-12-15 20:28:2841#include "net/base/upload_bytes_element_reader.h"
42#include "net/base/upload_data_stream.h"
43#include "net/base/upload_file_element_reader.h"
[email protected]6e7845ae2013-03-29 21:48:1144#include "net/cert/ev_root_ca_metadata.h"
45#include "net/cert/test_root_certs.h"
[email protected]aa84a7e2012-03-15 21:29:0646#include "net/cookies/cookie_monster.h"
47#include "net/cookies/cookie_store_test_helpers.h"
initial.commit586acc5fe2008-07-26 22:42:5248#include "net/disk_cache/disk_cache.h"
[email protected]f2cb3cf2013-03-21 01:40:5349#include "net/dns/mock_host_resolver.h"
[email protected]ba2f3342009-07-30 18:08:4250#include "net/ftp/ftp_network_layer.h"
initial.commit586acc5fe2008-07-26 22:42:5251#include "net/http/http_cache.h"
52#include "net/http/http_network_layer.h"
[email protected]c3456bb2011-12-12 22:22:1953#include "net/http/http_network_session.h"
[email protected]88e6b6f32010-05-07 23:14:2554#include "net/http/http_request_headers.h"
[email protected]319d9e6f2009-02-18 19:47:2155#include "net/http/http_response_headers.h"
[email protected]dffe8242012-03-20 15:14:2756#include "net/ocsp/nss_ocsp.h"
[email protected]63de95b2008-12-10 04:11:2757#include "net/proxy/proxy_service.h"
[email protected]c3456bb2011-12-12 22:22:1958#include "net/socket/ssl_client_socket.h"
[email protected]536fd0b2013-03-14 17:41:5759#include "net/ssl/ssl_connection_status_flags.h"
[email protected]6e7845ae2013-03-29 21:48:1160#include "net/test/cert_test_util.h"
[email protected]89b32522013-05-07 20:04:2161#include "net/test/spawned_test_server/spawned_test_server.h"
[email protected]e0f35c92013-05-08 16:04:3462#include "net/url_request/data_protocol_handler.h"
63#include "net/url_request/file_protocol_handler.h"
[email protected]d2a133182012-08-05 16:44:0864#include "net/url_request/ftp_protocol_handler.h"
[email protected]ee4c30d2012-11-07 15:08:4365#include "net/url_request/static_http_user_agent_settings.h"
initial.commit586acc5fe2008-07-26 22:42:5266#include "net/url_request/url_request.h"
[email protected]7886a8c2009-08-21 04:11:0967#include "net/url_request/url_request_file_dir_job.h"
[email protected]bcb84f8b2009-08-31 16:20:1468#include "net/url_request/url_request_http_job.h"
[email protected]9d5730b2012-08-24 17:42:4969#include "net/url_request/url_request_job_factory_impl.h"
[email protected]3c5ca8c2011-09-29 01:14:5170#include "net/url_request/url_request_redirect_job.h"
[email protected]a5c713f2009-04-16 21:05:4771#include "net/url_request/url_request_test_job.h"
[email protected]d2db0292011-01-26 20:23:4472#include "net/url_request/url_request_test_util.h"
initial.commit586acc5fe2008-07-26 22:42:5273#include "testing/gtest/include/gtest/gtest.h"
[email protected]23887f04f2008-12-02 19:20:1574#include "testing/platform_test.h"
initial.commit586acc5fe2008-07-26 22:42:5275
[email protected]dffe8242012-03-20 15:14:2776#if defined(OS_WIN)
[email protected]451fd902012-10-03 17:14:4877#include "base/win/scoped_com_initializer.h"
[email protected]aed9efb2013-04-13 01:20:5678#include "base/win/scoped_comptr.h"
[email protected]dffe8242012-03-20 15:14:2779#include "base/win/windows_version.h"
80#endif
81
[email protected]e1acf6f2008-10-27 20:43:3382using base::Time;
83
[email protected]7461a402011-03-24 23:19:5184namespace net {
85
initial.commit586acc5fe2008-07-26 22:42:5286namespace {
87
[email protected]42cba2fb2013-03-29 19:58:5788const base::string16 kChrome(ASCIIToUTF16("chrome"));
89const base::string16 kSecret(ASCIIToUTF16("secret"));
90const base::string16 kUser(ASCIIToUTF16("user"));
[email protected]13c8a092010-07-29 06:15:4491
[email protected]2bba3252013-04-08 19:50:5992// Tests load timing information in the case a fresh connection was used, with
93// no proxy.
[email protected]58e32bb2013-01-21 18:23:2594void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
95 int connect_timing_flags) {
96 EXPECT_FALSE(load_timing_info.socket_reused);
97 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
98
99 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
100 EXPECT_FALSE(load_timing_info.request_start.is_null());
101
102 EXPECT_LE(load_timing_info.request_start,
103 load_timing_info.connect_timing.connect_start);
104 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
105 connect_timing_flags);
106 EXPECT_LE(load_timing_info.connect_timing.connect_end,
107 load_timing_info.send_start);
108 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
109 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
110
[email protected]58e32bb2013-01-21 18:23:25111 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
112 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
113}
114
[email protected]2bba3252013-04-08 19:50:59115// Same as above, but with proxy times.
116void TestLoadTimingNotReusedWithProxy(
117 const net::LoadTimingInfo& load_timing_info,
118 int connect_timing_flags) {
119 EXPECT_FALSE(load_timing_info.socket_reused);
120 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
121
122 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
123 EXPECT_FALSE(load_timing_info.request_start.is_null());
124
125 EXPECT_LE(load_timing_info.request_start,
126 load_timing_info.proxy_resolve_start);
127 EXPECT_LE(load_timing_info.proxy_resolve_start,
128 load_timing_info.proxy_resolve_end);
129 EXPECT_LE(load_timing_info.proxy_resolve_end,
130 load_timing_info.connect_timing.connect_start);
131 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
132 connect_timing_flags);
133 EXPECT_LE(load_timing_info.connect_timing.connect_end,
134 load_timing_info.send_start);
135 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
136 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
137}
138
139// Same as above, but with a reused socket and proxy times.
140void TestLoadTimingReusedWithProxy(
141 const net::LoadTimingInfo& load_timing_info) {
142 EXPECT_TRUE(load_timing_info.socket_reused);
143 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
144
145 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
146 EXPECT_FALSE(load_timing_info.request_start.is_null());
147
148 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
149
150 EXPECT_LE(load_timing_info.request_start,
151 load_timing_info.proxy_resolve_start);
152 EXPECT_LE(load_timing_info.proxy_resolve_start,
153 load_timing_info.proxy_resolve_end);
154 EXPECT_LE(load_timing_info.proxy_resolve_end,
155 load_timing_info.send_start);
156 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
157 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
158}
159
[email protected]3b23a222013-05-15 21:33:25160// Tests load timing information in the case of a cache hit, when no cache
161// validation request was sent over the wire.
162void TestLoadTimingCacheHitNoNetwork(
163 const net::LoadTimingInfo& load_timing_info) {
164 EXPECT_FALSE(load_timing_info.socket_reused);
165 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
166
167 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
168 EXPECT_FALSE(load_timing_info.request_start.is_null());
169
170 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
171 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
172 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
173 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
174
175 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
176 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
177}
178
179// Tests load timing in the case that there is no HTTP response. This can be
180// used to test in the case of errors or non-HTTP requests.
181void TestLoadTimingNoHttpResponse(
[email protected]58e32bb2013-01-21 18:23:25182 const net::LoadTimingInfo& load_timing_info) {
183 EXPECT_FALSE(load_timing_info.socket_reused);
184 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
185
186 // Only the request times should be non-null.
187 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
188 EXPECT_FALSE(load_timing_info.request_start.is_null());
189
190 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
191
192 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
193 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
194 EXPECT_TRUE(load_timing_info.send_start.is_null());
195 EXPECT_TRUE(load_timing_info.send_end.is_null());
196 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
197}
198
[email protected]8a16266e2009-09-10 21:08:39199base::StringPiece TestNetResourceProvider(int key) {
initial.commit586acc5fe2008-07-26 22:42:52200 return "header";
201}
202
[email protected]71c64f62008-11-15 04:36:51203// Do a case-insensitive search through |haystack| for |needle|.
204bool ContainsString(const std::string& haystack, const char* needle) {
205 std::string::const_iterator it =
206 std::search(haystack.begin(),
207 haystack.end(),
208 needle,
209 needle + strlen(needle),
[email protected]07f1cee2010-11-03 03:53:35210 base::CaseInsensitiveCompare<char>());
[email protected]71c64f62008-11-15 04:36:51211 return it != haystack.end();
212}
213
[email protected]661376a2009-04-29 02:04:23214void FillBuffer(char* buffer, size_t len) {
215 static bool called = false;
216 if (!called) {
217 called = true;
218 int seed = static_cast<int>(Time::Now().ToInternalValue());
219 srand(seed);
220 }
221
222 for (size_t i = 0; i < len; i++) {
223 buffer[i] = static_cast<char>(rand());
224 if (!buffer[i])
225 buffer[i] = 'g';
226 }
227}
228
[email protected]f288ef02012-12-15 20:28:28229UploadDataStream* CreateSimpleUploadData(const char* data) {
230 scoped_ptr<UploadElementReader> reader(
231 new UploadBytesElementReader(data, strlen(data)));
232 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
[email protected]195e77d2009-07-23 19:10:23233}
234
[email protected]96adadb2010-08-28 01:16:17235// Verify that the SSLInfo of a successful SSL connection has valid values.
[email protected]7461a402011-03-24 23:19:51236void CheckSSLInfo(const SSLInfo& ssl_info) {
[email protected]89af3d92010-10-15 20:31:37237 // Allow ChromeFrame fake SSLInfo to get through.
[email protected]c679be22010-08-29 15:20:05238 if (ssl_info.cert.get() &&
[email protected]89af3d92010-10-15 20:31:37239 ssl_info.cert.get()->issuer().GetDisplayName() == "Chrome Internal") {
240 // -1 means unknown.
241 EXPECT_EQ(ssl_info.security_bits, -1);
[email protected]c679be22010-08-29 15:20:05242 return;
[email protected]89af3d92010-10-15 20:31:37243 }
244
[email protected]96adadb2010-08-28 01:16:17245 // -1 means unknown. 0 means no encryption.
246 EXPECT_GT(ssl_info.security_bits, 0);
247
248 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
[email protected]7461a402011-03-24 23:19:51249 int cipher_suite = SSLConnectionStatusToCipherSuite(
[email protected]96adadb2010-08-28 01:16:17250 ssl_info.connection_status);
251 EXPECT_NE(0, cipher_suite);
252}
253
[email protected]79e1fd62013-06-20 06:50:04254void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
255 const GURL& host_url) {
256 std::string sent_value;
257
258 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
259 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
260
261 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
262 EXPECT_EQ("keep-alive", sent_value);
263}
264
[email protected]ede03212012-09-07 12:52:26265bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
[email protected]69d7ff442012-02-13 22:41:27266 size_t size = a.size();
267
268 if (size != b.size())
269 return false;
270
271 for (size_t i = 0; i < size; ++i) {
272 if (!a[i].Equals(b[i]))
273 return false;
274 }
275
276 return true;
277}
278
[email protected]dc5a5cf2012-09-26 02:49:30279// A network delegate that allows the user to choose a subset of request stages
280// to block in. When blocking, the delegate can do one of the following:
281// * synchronously return a pre-specified error code, or
282// * asynchronously return that value via an automatically called callback,
283// or
284// * block and wait for the user to do a callback.
285// Additionally, the user may also specify a redirect URL -- then each request
286// with the current URL different from the redirect target will be redirected
287// to that target, in the on-before-URL-request stage, independent of whether
288// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
[email protected]4c76d7c2011-04-15 19:14:12289class BlockingNetworkDelegate : public TestNetworkDelegate {
290 public:
[email protected]dc5a5cf2012-09-26 02:49:30291 // Stages in which the delegate can block.
292 enum Stage {
[email protected]9045b8822012-01-13 20:35:35293 NOT_BLOCKED = 0,
294 ON_BEFORE_URL_REQUEST = 1 << 0,
295 ON_BEFORE_SEND_HEADERS = 1 << 1,
296 ON_HEADERS_RECEIVED = 1 << 2,
297 ON_AUTH_REQUIRED = 1 << 3
298 };
299
[email protected]dc5a5cf2012-09-26 02:49:30300 // Behavior during blocked stages. During other stages, just
301 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
302 enum BlockMode {
303 SYNCHRONOUS, // No callback, returns specified return values.
304 AUTO_CALLBACK, // |this| posts a task to run the callback using the
305 // specified return codes.
306 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
307 // |auth_retval_| are ignored. In every blocking stage the
308 // message loop is quit.
309 };
310
311 // Creates a delegate which does not block at all.
312 explicit BlockingNetworkDelegate(BlockMode block_mode);
313
314 // For users to trigger a callback returning |response|.
315 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
316 // Only call if |block_mode_| == USER_CALLBACK.
317 void DoCallback(int response);
318 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
319
320 // Setters.
321 void set_retval(int retval) {
322 ASSERT_NE(USER_CALLBACK, block_mode_);
323 ASSERT_NE(ERR_IO_PENDING, retval);
324 ASSERT_NE(OK, retval);
325 retval_ = retval;
[email protected]9045b8822012-01-13 20:35:35326 }
327
[email protected]dc5a5cf2012-09-26 02:49:30328 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
329 // |auth_credentials_| will be passed with the response.
330 void set_auth_retval(AuthRequiredResponse auth_retval) {
331 ASSERT_NE(USER_CALLBACK, block_mode_);
332 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
333 auth_retval_ = auth_retval;
334 }
335 void set_auth_credentials(const AuthCredentials& auth_credentials) {
336 auth_credentials_ = auth_credentials;
[email protected]9045b8822012-01-13 20:35:35337 }
338
[email protected]dc5a5cf2012-09-26 02:49:30339 void set_redirect_url(const GURL& url) {
340 redirect_url_ = url;
[email protected]9045b8822012-01-13 20:35:35341 }
342
[email protected]dc5a5cf2012-09-26 02:49:30343 void set_block_on(int block_on) {
344 block_on_ = block_on;
[email protected]9045b8822012-01-13 20:35:35345 }
346
[email protected]dc5a5cf2012-09-26 02:49:30347 // Allows the user to check in which state did we block.
348 Stage stage_blocked_for_callback() const {
349 EXPECT_EQ(USER_CALLBACK, block_mode_);
350 return stage_blocked_for_callback_;
[email protected]9045b8822012-01-13 20:35:35351 }
352
353 private:
[email protected]dc5a5cf2012-09-26 02:49:30354 void RunCallback(int response, const CompletionCallback& callback);
355 void RunAuthCallback(AuthRequiredResponse response,
356 const AuthCallback& callback);
357
[email protected]9045b8822012-01-13 20:35:35358 // TestNetworkDelegate implementation.
359 virtual int OnBeforeURLRequest(URLRequest* request,
360 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30361 GURL* new_url) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35362
363 virtual int OnBeforeSendHeaders(URLRequest* request,
364 const CompletionCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30365 HttpRequestHeaders* headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35366
367 virtual int OnHeadersReceived(
368 URLRequest* request,
369 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32370 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30371 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35372
373 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
374 URLRequest* request,
375 const AuthChallengeInfo& auth_info,
376 const AuthCallback& callback,
[email protected]dc5a5cf2012-09-26 02:49:30377 AuthCredentials* credentials) OVERRIDE;
[email protected]9045b8822012-01-13 20:35:35378
[email protected]dc5a5cf2012-09-26 02:49:30379 // Resets the callbacks and |stage_blocked_for_callback_|.
380 void Reset();
[email protected]9045b8822012-01-13 20:35:35381
[email protected]dc5a5cf2012-09-26 02:49:30382 // Checks whether we should block in |stage|. If yes, returns an error code
383 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
384 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
385
386 // Configuration parameters, can be adjusted by public methods:
387 const BlockMode block_mode_;
388
389 // Values returned on blocking stages when mode is SYNCHRONOUS or
390 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
391 int retval_; // To be returned in non-auth stages.
392 AuthRequiredResponse auth_retval_;
393
394 GURL redirect_url_; // Used if non-empty.
395 int block_on_; // Bit mask: in which stages to block.
396
397 // |auth_credentials_| will be copied to |*target_auth_credential_| on
398 // callback.
399 AuthCredentials auth_credentials_;
400 AuthCredentials* target_auth_credentials_;
401
402 // Internal variables, not set by not the user:
403 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
404 // USER_CALLBACK).
405 Stage stage_blocked_for_callback_;
406
407 // Callback objects stored during blocking stages.
[email protected]9045b8822012-01-13 20:35:35408 CompletionCallback callback_;
409 AuthCallback auth_callback_;
[email protected]dc5a5cf2012-09-26 02:49:30410
411 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
412
413 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
[email protected]9045b8822012-01-13 20:35:35414};
415
[email protected]dc5a5cf2012-09-26 02:49:30416BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
417 : block_mode_(block_mode),
418 retval_(OK),
419 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
420 block_on_(0),
421 target_auth_credentials_(NULL),
422 stage_blocked_for_callback_(NOT_BLOCKED),
[email protected]aa249b52013-04-30 01:04:32423 weak_factory_(this) {
[email protected]dc5a5cf2012-09-26 02:49:30424}
425
426void BlockingNetworkDelegate::DoCallback(int response) {
427 ASSERT_EQ(USER_CALLBACK, block_mode_);
428 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
429 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
430 CompletionCallback callback = callback_;
431 Reset();
432 RunCallback(response, callback);
433}
434
435void BlockingNetworkDelegate::DoAuthCallback(
436 NetworkDelegate::AuthRequiredResponse response) {
437 ASSERT_EQ(USER_CALLBACK, block_mode_);
438 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
439 AuthCallback auth_callback = auth_callback_;
440 Reset();
441 RunAuthCallback(response, auth_callback);
442}
443
444void BlockingNetworkDelegate::RunCallback(int response,
445 const CompletionCallback& callback) {
446 callback.Run(response);
447}
448
449void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
450 const AuthCallback& callback) {
451 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
452 ASSERT_TRUE(target_auth_credentials_ != NULL);
453 *target_auth_credentials_ = auth_credentials_;
454 }
455 callback.Run(response);
456}
457
458int BlockingNetworkDelegate::OnBeforeURLRequest(
459 URLRequest* request,
460 const CompletionCallback& callback,
461 GURL* new_url) {
462 if (redirect_url_ == request->url())
463 return OK; // We've already seen this request and redirected elsewhere.
464
465 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
466
467 if (!redirect_url_.is_empty())
468 *new_url = redirect_url_;
469
470 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
471}
472
473int BlockingNetworkDelegate::OnBeforeSendHeaders(
474 URLRequest* request,
475 const CompletionCallback& callback,
476 HttpRequestHeaders* headers) {
477 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
478
479 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
480}
481
482int BlockingNetworkDelegate::OnHeadersReceived(
483 URLRequest* request,
484 const CompletionCallback& callback,
[email protected]507af8f2012-10-20 00:42:32485 const HttpResponseHeaders* original_response_headers,
[email protected]dc5a5cf2012-09-26 02:49:30486 scoped_refptr<HttpResponseHeaders>* override_response_headers) {
487 TestNetworkDelegate::OnHeadersReceived(
488 request, callback, original_response_headers,
489 override_response_headers);
490
491 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
492}
493
494NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
495 URLRequest* request,
496 const AuthChallengeInfo& auth_info,
497 const AuthCallback& callback,
498 AuthCredentials* credentials) {
499 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
500 credentials);
501 // Check that the user has provided callback for the previous blocked stage.
502 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
503
504 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
505 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
506 }
507
508 target_auth_credentials_ = credentials;
509
510 switch (block_mode_) {
511 case SYNCHRONOUS:
512 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
513 *target_auth_credentials_ = auth_credentials_;
514 return auth_retval_;
515
516 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34517 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30518 FROM_HERE,
519 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
520 weak_factory_.GetWeakPtr(), auth_retval_, callback));
521 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
522
523 case USER_CALLBACK:
524 auth_callback_ = callback;
525 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
[email protected]2da659e2013-05-23 20:51:34526 base::MessageLoop::current()->PostTask(FROM_HERE,
527 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30528 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
529 }
530 NOTREACHED();
531 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
532}
533
534void BlockingNetworkDelegate::Reset() {
535 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
536 stage_blocked_for_callback_ = NOT_BLOCKED;
537 callback_.Reset();
538 auth_callback_.Reset();
539}
540
541int BlockingNetworkDelegate::MaybeBlockStage(
542 BlockingNetworkDelegate::Stage stage,
543 const CompletionCallback& callback) {
544 // Check that the user has provided callback for the previous blocked stage.
545 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
546
547 if ((block_on_ & stage) == 0) {
548 return OK;
549 }
550
551 switch (block_mode_) {
552 case SYNCHRONOUS:
553 EXPECT_NE(OK, retval_);
554 return retval_;
555
556 case AUTO_CALLBACK:
[email protected]2da659e2013-05-23 20:51:34557 base::MessageLoop::current()->PostTask(
[email protected]dc5a5cf2012-09-26 02:49:30558 FROM_HERE,
559 base::Bind(&BlockingNetworkDelegate::RunCallback,
560 weak_factory_.GetWeakPtr(), retval_, callback));
561 return ERR_IO_PENDING;
562
563 case USER_CALLBACK:
564 callback_ = callback;
565 stage_blocked_for_callback_ = stage;
[email protected]2da659e2013-05-23 20:51:34566 base::MessageLoop::current()->PostTask(FROM_HERE,
567 base::MessageLoop::QuitClosure());
[email protected]dc5a5cf2012-09-26 02:49:30568 return ERR_IO_PENDING;
569 }
570 NOTREACHED();
571 return 0;
572}
573
[email protected]d5a4dd62012-05-23 01:41:04574class TestURLRequestContextWithProxy : public TestURLRequestContext {
575 public:
576 // Does not own |delegate|.
577 TestURLRequestContextWithProxy(const std::string& proxy,
578 NetworkDelegate* delegate)
579 : TestURLRequestContext(true) {
580 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
581 set_network_delegate(delegate);
582 Init();
583 }
584 virtual ~TestURLRequestContextWithProxy() {}
585};
586
587} // namespace
588
[email protected]a592c0432012-12-01 18:10:29589// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
[email protected]7a0bb4bf2008-11-19 21:41:48590class URLRequestTest : public PlatformTest {
[email protected]abb26092010-11-11 22:19:00591 public:
[email protected]ef2bf422012-05-11 03:27:09592 URLRequestTest() : default_context_(true) {
593 default_context_.set_network_delegate(&default_network_delegate_);
[email protected]58e32bb2013-01-21 18:23:25594 default_context_.set_net_log(&net_log_);
[email protected]e0f35c92013-05-08 16:04:34595 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
[email protected]255620da2013-08-19 13:14:29596 job_factory_.SetProtocolHandler(
597 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
[email protected]e0f35c92013-05-08 16:04:34598 default_context_.set_job_factory(&job_factory_);
[email protected]ef2bf422012-05-11 03:27:09599 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:50600 }
[email protected]e4034ad2013-09-20 08:36:18601 virtual ~URLRequestTest() {
602 // URLRequestJobs may post clean-up tasks on destruction.
603 base::RunLoop().RunUntilIdle();
604 }
[email protected]87a09a92011-07-14 15:50:50605
[email protected]3c5ca8c2011-09-29 01:14:51606 // Adds the TestJobInterceptor to the default context.
607 TestJobInterceptor* AddTestInterceptor() {
[email protected]f53b4802012-12-20 17:04:23608 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
[email protected]e0f35c92013-05-08 16:04:34609 job_factory_.SetProtocolHandler("http", NULL);
610 job_factory_.SetProtocolHandler("http", protocol_handler_);
[email protected]f53b4802012-12-20 17:04:23611 return protocol_handler_;
[email protected]3c5ca8c2011-09-29 01:14:51612 }
613
[email protected]87a09a92011-07-14 15:50:50614 protected:
[email protected]58e32bb2013-01-21 18:23:25615 CapturingNetLog net_log_;
[email protected]ceefd7fd2012-11-29 00:36:24616 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]e0f35c92013-05-08 16:04:34617 URLRequestJobFactoryImpl job_factory_;
[email protected]ef2bf422012-05-11 03:27:09618 TestURLRequestContext default_context_;
[email protected]7a0bb4bf2008-11-19 21:41:48619};
620
[email protected]316c1e5e2012-09-12 15:17:44621TEST_F(URLRequestTest, AboutBlankTest) {
622 TestDelegate d;
623 {
624 URLRequest r(GURL("about:blank"), &d, &default_context_);
625
626 r.Start();
627 EXPECT_TRUE(r.is_pending());
628
[email protected]255620da2013-08-19 13:14:29629 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44630
631 EXPECT_TRUE(!r.is_pending());
632 EXPECT_FALSE(d.received_data_before_response());
633 EXPECT_EQ(d.bytes_received(), 0);
634 EXPECT_EQ("", r.GetSocketAddress().host());
635 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04636
637 HttpRequestHeaders headers;
638 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44639 }
640}
641
642TEST_F(URLRequestTest, DataURLImageTest) {
643 TestDelegate d;
644 {
645 // Use our nice little Chrome logo.
646 URLRequest r(GURL(
647 "data:image/png;base64,"
648 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
649 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
650 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
651 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
652 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
653 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
654 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
655 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
656 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
657 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
658 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
659 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
660 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
661 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
662 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
663 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
664 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
665 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
666 &d,
667 &default_context_);
668
669 r.Start();
670 EXPECT_TRUE(r.is_pending());
671
[email protected]255620da2013-08-19 13:14:29672 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44673
674 EXPECT_TRUE(!r.is_pending());
675 EXPECT_FALSE(d.received_data_before_response());
676 EXPECT_EQ(d.bytes_received(), 911);
677 EXPECT_EQ("", r.GetSocketAddress().host());
678 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04679
680 HttpRequestHeaders headers;
681 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44682 }
683}
684
685TEST_F(URLRequestTest, FileTest) {
[email protected]6cdfd7f2013-02-08 20:40:15686 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44687 PathService::Get(base::FILE_EXE, &app_path);
688 GURL app_url = FilePathToFileURL(app_path);
689
690 TestDelegate d;
691 {
692 URLRequest r(app_url, &d, &default_context_);
693
694 r.Start();
695 EXPECT_TRUE(r.is_pending());
696
[email protected]255620da2013-08-19 13:14:29697 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44698
699 int64 file_size = -1;
700 EXPECT_TRUE(file_util::GetFileSize(app_path, &file_size));
701
702 EXPECT_TRUE(!r.is_pending());
703 EXPECT_EQ(1, d.response_started_count());
704 EXPECT_FALSE(d.received_data_before_response());
705 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
706 EXPECT_EQ("", r.GetSocketAddress().host());
707 EXPECT_EQ(0, r.GetSocketAddress().port());
[email protected]79e1fd62013-06-20 06:50:04708
709 HttpRequestHeaders headers;
710 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
[email protected]316c1e5e2012-09-12 15:17:44711 }
712}
713
[email protected]ba40bb762012-12-17 07:11:04714TEST_F(URLRequestTest, FileTestCancel) {
[email protected]6cdfd7f2013-02-08 20:40:15715 base::FilePath app_path;
[email protected]ba40bb762012-12-17 07:11:04716 PathService::Get(base::FILE_EXE, &app_path);
717 GURL app_url = FilePathToFileURL(app_path);
718
719 TestDelegate d;
720 {
721 URLRequest r(app_url, &d, &default_context_);
722
723 r.Start();
724 EXPECT_TRUE(r.is_pending());
725 r.Cancel();
726 }
[email protected]79e1fd62013-06-20 06:50:04727 // Async cancellation should be safe even when URLRequest has been already
[email protected]ba40bb762012-12-17 07:11:04728 // destroyed.
[email protected]255620da2013-08-19 13:14:29729 base::RunLoop().RunUntilIdle();
[email protected]ba40bb762012-12-17 07:11:04730}
731
[email protected]316c1e5e2012-09-12 15:17:44732TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
733 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17734 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44735 FillBuffer(buffer.get(), buffer_size);
736
[email protected]6cdfd7f2013-02-08 20:40:15737 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44738 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
739 GURL temp_url = FilePathToFileURL(temp_path);
740 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
741
742 int64 file_size;
743 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
744
745 const size_t first_byte_position = 500;
746 const size_t last_byte_position = buffer_size - first_byte_position;
747 const size_t content_length = last_byte_position - first_byte_position + 1;
748 std::string partial_buffer_string(buffer.get() + first_byte_position,
749 buffer.get() + last_byte_position + 1);
750
751 TestDelegate d;
752 {
753 URLRequest r(temp_url, &d, &default_context_);
754
755 HttpRequestHeaders headers;
756 headers.SetHeader(HttpRequestHeaders::kRange,
757 base::StringPrintf(
758 "bytes=%" PRIuS "-%" PRIuS,
759 first_byte_position, last_byte_position));
760 r.SetExtraRequestHeaders(headers);
761 r.Start();
762 EXPECT_TRUE(r.is_pending());
763
[email protected]255620da2013-08-19 13:14:29764 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44765 EXPECT_TRUE(!r.is_pending());
766 EXPECT_EQ(1, d.response_started_count());
767 EXPECT_FALSE(d.received_data_before_response());
768 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
769 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
770 EXPECT_TRUE(partial_buffer_string == d.data_received());
771 }
772
[email protected]dd3aa792013-07-16 19:10:23773 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44774}
775
776TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
777 const size_t buffer_size = 4000;
[email protected]4356f0f2013-04-07 00:58:17778 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44779 FillBuffer(buffer.get(), buffer_size);
780
[email protected]6cdfd7f2013-02-08 20:40:15781 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44782 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
783 GURL temp_url = FilePathToFileURL(temp_path);
784 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
785
786 int64 file_size;
787 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
788
789 const size_t first_byte_position = 500;
790 const size_t last_byte_position = buffer_size - 1;
791 const size_t content_length = last_byte_position - first_byte_position + 1;
792 std::string partial_buffer_string(buffer.get() + first_byte_position,
793 buffer.get() + last_byte_position + 1);
794
795 TestDelegate d;
796 {
797 URLRequest r(temp_url, &d, &default_context_);
798
799 HttpRequestHeaders headers;
800 headers.SetHeader(HttpRequestHeaders::kRange,
801 base::StringPrintf("bytes=%" PRIuS "-",
802 first_byte_position));
803 r.SetExtraRequestHeaders(headers);
804 r.Start();
805 EXPECT_TRUE(r.is_pending());
806
[email protected]255620da2013-08-19 13:14:29807 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44808 EXPECT_TRUE(!r.is_pending());
809 EXPECT_EQ(1, d.response_started_count());
810 EXPECT_FALSE(d.received_data_before_response());
811 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
812 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
813 EXPECT_TRUE(partial_buffer_string == d.data_received());
814 }
815
[email protected]dd3aa792013-07-16 19:10:23816 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44817}
818
819TEST_F(URLRequestTest, FileTestMultipleRanges) {
820 const size_t buffer_size = 400000;
[email protected]4356f0f2013-04-07 00:58:17821 scoped_ptr<char[]> buffer(new char[buffer_size]);
[email protected]316c1e5e2012-09-12 15:17:44822 FillBuffer(buffer.get(), buffer_size);
823
[email protected]6cdfd7f2013-02-08 20:40:15824 base::FilePath temp_path;
[email protected]316c1e5e2012-09-12 15:17:44825 EXPECT_TRUE(file_util::CreateTemporaryFile(&temp_path));
826 GURL temp_url = FilePathToFileURL(temp_path);
827 EXPECT_TRUE(file_util::WriteFile(temp_path, buffer.get(), buffer_size));
828
829 int64 file_size;
830 EXPECT_TRUE(file_util::GetFileSize(temp_path, &file_size));
831
832 TestDelegate d;
833 {
834 URLRequest r(temp_url, &d, &default_context_);
835
836 HttpRequestHeaders headers;
837 headers.SetHeader(HttpRequestHeaders::kRange,
838 "bytes=0-0,10-200,200-300");
839 r.SetExtraRequestHeaders(headers);
840 r.Start();
841 EXPECT_TRUE(r.is_pending());
842
[email protected]255620da2013-08-19 13:14:29843 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44844 EXPECT_TRUE(d.request_failed());
845 }
846
[email protected]dd3aa792013-07-16 19:10:23847 EXPECT_TRUE(base::DeleteFile(temp_path, false));
[email protected]316c1e5e2012-09-12 15:17:44848}
849
850TEST_F(URLRequestTest, InvalidUrlTest) {
851 TestDelegate d;
852 {
853 URLRequest r(GURL("invalid url"), &d, &default_context_);
854
855 r.Start();
856 EXPECT_TRUE(r.is_pending());
857
[email protected]255620da2013-08-19 13:14:29858 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44859 EXPECT_TRUE(d.request_failed());
860 }
861}
862
863#if defined(OS_WIN)
864TEST_F(URLRequestTest, ResolveShortcutTest) {
[email protected]6cdfd7f2013-02-08 20:40:15865 base::FilePath app_path;
[email protected]316c1e5e2012-09-12 15:17:44866 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
867 app_path = app_path.AppendASCII("net");
868 app_path = app_path.AppendASCII("data");
869 app_path = app_path.AppendASCII("url_request_unittest");
870 app_path = app_path.AppendASCII("with-headers.html");
871
872 std::wstring lnk_path = app_path.value() + L".lnk";
873
[email protected]451fd902012-10-03 17:14:48874 base::win::ScopedCOMInitializer com_initializer;
[email protected]00d60fa2012-10-01 18:20:17875
[email protected]316c1e5e2012-09-12 15:17:44876 // Temporarily create a shortcut for test
[email protected]aed9efb2013-04-13 01:20:56877 {
878 base::win::ScopedComPtr<IShellLink> shell;
879 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
880 CLSCTX_INPROC_SERVER)));
881 base::win::ScopedComPtr<IPersistFile> persist;
882 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
883 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
884 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
885 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
886 }
[email protected]316c1e5e2012-09-12 15:17:44887
888 TestDelegate d;
889 {
[email protected]6cdfd7f2013-02-08 20:40:15890 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)), &d,
891 &default_context_);
[email protected]316c1e5e2012-09-12 15:17:44892
893 r.Start();
894 EXPECT_TRUE(r.is_pending());
895
[email protected]255620da2013-08-19 13:14:29896 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44897
898 WIN32_FILE_ATTRIBUTE_DATA data;
899 GetFileAttributesEx(app_path.value().c_str(),
900 GetFileExInfoStandard, &data);
901 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
902 FILE_SHARE_READ, NULL, OPEN_EXISTING,
903 FILE_ATTRIBUTE_NORMAL, NULL);
904 EXPECT_NE(INVALID_HANDLE_VALUE, file);
[email protected]ec530c22013-04-11 15:54:04905 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
[email protected]316c1e5e2012-09-12 15:17:44906 DWORD read_size;
907 BOOL result;
908 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
909 &read_size, NULL);
910 std::string content(buffer.get(), read_size);
911 CloseHandle(file);
912
913 EXPECT_TRUE(!r.is_pending());
914 EXPECT_EQ(1, d.received_redirect_count());
915 EXPECT_EQ(content, d.data_received());
916 }
917
918 // Clean the shortcut
919 DeleteFile(lnk_path.c_str());
[email protected]316c1e5e2012-09-12 15:17:44920}
921#endif // defined(OS_WIN)
922
923TEST_F(URLRequestTest, FileDirCancelTest) {
924 // Put in mock resource provider.
925 NetModule::SetResourceProvider(TestNetResourceProvider);
926
927 TestDelegate d;
928 {
[email protected]6cdfd7f2013-02-08 20:40:15929 base::FilePath file_path;
[email protected]316c1e5e2012-09-12 15:17:44930 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
931 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
932 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
933
934 URLRequest req(FilePathToFileURL(file_path), &d, &default_context_);
935 req.Start();
936 EXPECT_TRUE(req.is_pending());
937
938 d.set_cancel_in_received_data_pending(true);
939
[email protected]255620da2013-08-19 13:14:29940 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44941 }
942
943 // Take out mock resource provider.
944 NetModule::SetResourceProvider(NULL);
945}
946
947TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
948 // There is an implicit redirect when loading a file path that matches a
949 // directory and does not end with a slash. Ensure that following such
950 // redirects does not crash. See http://crbug.com/18686.
951
[email protected]6cdfd7f2013-02-08 20:40:15952 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:44953 PathService::Get(base::DIR_SOURCE_ROOT, &path);
954 path = path.Append(FILE_PATH_LITERAL("net"));
955 path = path.Append(FILE_PATH_LITERAL("data"));
956 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
957
958 TestDelegate d;
959 URLRequest req(FilePathToFileURL(path), &d, &default_context_);
960 req.Start();
[email protected]255620da2013-08-19 13:14:29961 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44962
963 ASSERT_EQ(1, d.received_redirect_count());
964 ASSERT_LT(0, d.bytes_received());
965 ASSERT_FALSE(d.request_failed());
966 ASSERT_TRUE(req.status().is_success());
967}
968
969#if defined(OS_WIN)
970// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
971TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
972 TestDelegate d;
973 URLRequest req(GURL("file:///"), &d, &default_context_);
974 req.Start();
[email protected]255620da2013-08-19 13:14:29975 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44976
977 ASSERT_EQ(1, d.received_redirect_count());
978 ASSERT_FALSE(req.status().is_success());
979}
980#endif
981
982// Custom URLRequestJobs for use with interceptor tests
983class RestartTestJob : public URLRequestTestJob {
984 public:
985 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
986 : URLRequestTestJob(request, network_delegate, true) {}
987 protected:
[email protected]46fadfd2013-02-06 09:40:16988 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:44989 this->NotifyRestartRequired();
990 }
991 private:
[email protected]46fadfd2013-02-06 09:40:16992 virtual ~RestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:44993};
994
995class CancelTestJob : public URLRequestTestJob {
996 public:
997 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
998 : URLRequestTestJob(request, network_delegate, true) {}
999 protected:
[email protected]46fadfd2013-02-06 09:40:161000 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441001 request_->Cancel();
1002 }
1003 private:
[email protected]46fadfd2013-02-06 09:40:161004 virtual ~CancelTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441005};
1006
1007class CancelThenRestartTestJob : public URLRequestTestJob {
1008 public:
1009 explicit CancelThenRestartTestJob(URLRequest* request,
1010 NetworkDelegate* network_delegate)
1011 : URLRequestTestJob(request, network_delegate, true) {
1012 }
1013 protected:
[email protected]46fadfd2013-02-06 09:40:161014 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441015 request_->Cancel();
1016 this->NotifyRestartRequired();
1017 }
1018 private:
[email protected]46fadfd2013-02-06 09:40:161019 virtual ~CancelThenRestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441020};
1021
1022// An Interceptor for use with interceptor tests
1023class TestInterceptor : URLRequest::Interceptor {
1024 public:
1025 TestInterceptor()
1026 : intercept_main_request_(false), restart_main_request_(false),
1027 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1028 simulate_main_network_error_(false),
1029 intercept_redirect_(false), cancel_redirect_request_(false),
1030 intercept_final_response_(false), cancel_final_request_(false),
1031 did_intercept_main_(false), did_restart_main_(false),
1032 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1033 did_simulate_error_main_(false),
1034 did_intercept_redirect_(false), did_cancel_redirect_(false),
1035 did_intercept_final_(false), did_cancel_final_(false) {
1036 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1037 }
1038
[email protected]46fadfd2013-02-06 09:40:161039 virtual ~TestInterceptor() {
[email protected]316c1e5e2012-09-12 15:17:441040 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1041 }
1042
[email protected]46fadfd2013-02-06 09:40:161043 virtual URLRequestJob* MaybeIntercept(
1044 URLRequest* request,
1045 NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441046 if (restart_main_request_) {
1047 restart_main_request_ = false;
1048 did_restart_main_ = true;
1049 return new RestartTestJob(request, network_delegate);
1050 }
1051 if (cancel_main_request_) {
1052 cancel_main_request_ = false;
1053 did_cancel_main_ = true;
1054 return new CancelTestJob(request, network_delegate);
1055 }
1056 if (cancel_then_restart_main_request_) {
1057 cancel_then_restart_main_request_ = false;
1058 did_cancel_then_restart_main_ = true;
1059 return new CancelThenRestartTestJob(request, network_delegate);
1060 }
1061 if (simulate_main_network_error_) {
1062 simulate_main_network_error_ = false;
1063 did_simulate_error_main_ = true;
1064 // will error since the requeted url is not one of its canned urls
1065 return new URLRequestTestJob(request, network_delegate, true);
1066 }
1067 if (!intercept_main_request_)
1068 return NULL;
1069 intercept_main_request_ = false;
1070 did_intercept_main_ = true;
[email protected]2bba3252013-04-08 19:50:591071 URLRequestTestJob* job = new URLRequestTestJob(request,
1072 network_delegate,
1073 main_headers_,
1074 main_data_,
1075 true);
1076 job->set_load_timing_info(main_request_load_timing_info_);
1077 return job;
[email protected]316c1e5e2012-09-12 15:17:441078 }
1079
1080 virtual URLRequestJob* MaybeInterceptRedirect(
1081 URLRequest* request,
1082 NetworkDelegate* network_delegate,
[email protected]46fadfd2013-02-06 09:40:161083 const GURL& location) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441084 if (cancel_redirect_request_) {
1085 cancel_redirect_request_ = false;
1086 did_cancel_redirect_ = true;
1087 return new CancelTestJob(request, network_delegate);
1088 }
1089 if (!intercept_redirect_)
1090 return NULL;
1091 intercept_redirect_ = false;
1092 did_intercept_redirect_ = true;
1093 return new URLRequestTestJob(request,
1094 network_delegate,
1095 redirect_headers_,
1096 redirect_data_,
1097 true);
1098 }
1099
1100 virtual URLRequestJob* MaybeInterceptResponse(
[email protected]46fadfd2013-02-06 09:40:161101 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441102 if (cancel_final_request_) {
1103 cancel_final_request_ = false;
1104 did_cancel_final_ = true;
1105 return new CancelTestJob(request, network_delegate);
1106 }
1107 if (!intercept_final_response_)
1108 return NULL;
1109 intercept_final_response_ = false;
1110 did_intercept_final_ = true;
1111 return new URLRequestTestJob(request,
1112 network_delegate,
1113 final_headers_,
1114 final_data_,
1115 true);
1116 }
1117
[email protected]2bba3252013-04-08 19:50:591118 // Whether to intercept the main request, and if so the response to return and
1119 // the LoadTimingInfo to use.
[email protected]316c1e5e2012-09-12 15:17:441120 bool intercept_main_request_;
1121 std::string main_headers_;
1122 std::string main_data_;
[email protected]2bba3252013-04-08 19:50:591123 LoadTimingInfo main_request_load_timing_info_;
[email protected]316c1e5e2012-09-12 15:17:441124
1125 // Other actions we take at MaybeIntercept time
1126 bool restart_main_request_;
1127 bool cancel_main_request_;
1128 bool cancel_then_restart_main_request_;
1129 bool simulate_main_network_error_;
1130
1131 // Whether to intercept redirects, and if so the response to return.
1132 bool intercept_redirect_;
1133 std::string redirect_headers_;
1134 std::string redirect_data_;
1135
1136 // Other actions we can take at MaybeInterceptRedirect time
1137 bool cancel_redirect_request_;
1138
1139 // Whether to intercept final response, and if so the response to return.
1140 bool intercept_final_response_;
1141 std::string final_headers_;
1142 std::string final_data_;
1143
1144 // Other actions we can take at MaybeInterceptResponse time
1145 bool cancel_final_request_;
1146
1147 // If we did something or not
1148 bool did_intercept_main_;
1149 bool did_restart_main_;
1150 bool did_cancel_main_;
1151 bool did_cancel_then_restart_main_;
1152 bool did_simulate_error_main_;
1153 bool did_intercept_redirect_;
1154 bool did_cancel_redirect_;
1155 bool did_intercept_final_;
1156 bool did_cancel_final_;
1157
1158 // Static getters for canned response header and data strings
1159
1160 static std::string ok_data() {
1161 return URLRequestTestJob::test_data_1();
1162 }
1163
1164 static std::string ok_headers() {
1165 return URLRequestTestJob::test_headers();
1166 }
1167
1168 static std::string redirect_data() {
1169 return std::string();
1170 }
1171
1172 static std::string redirect_headers() {
1173 return URLRequestTestJob::test_redirect_headers();
1174 }
1175
1176 static std::string error_data() {
1177 return std::string("ohhh nooooo mr. bill!");
1178 }
1179
1180 static std::string error_headers() {
1181 return URLRequestTestJob::test_error_headers();
1182 }
1183};
1184
1185TEST_F(URLRequestTest, Intercept) {
1186 TestInterceptor interceptor;
1187
1188 // intercept the main request and respond with a simple response
1189 interceptor.intercept_main_request_ = true;
1190 interceptor.main_headers_ = TestInterceptor::ok_headers();
1191 interceptor.main_data_ = TestInterceptor::ok_data();
1192
1193 TestDelegate d;
1194 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1195 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1196 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1197 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1198 req.SetUserData(NULL, user_data0);
1199 req.SetUserData(&user_data1, user_data1);
1200 req.SetUserData(&user_data2, user_data2);
1201 req.set_method("GET");
1202 req.Start();
[email protected]255620da2013-08-19 13:14:291203 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441204
1205 // Make sure we can retrieve our specific user data
1206 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1207 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1208 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1209
1210 // Check the interceptor got called as expected
1211 EXPECT_TRUE(interceptor.did_intercept_main_);
1212
1213 // Check we got one good response
1214 EXPECT_TRUE(req.status().is_success());
1215 EXPECT_EQ(200, req.response_headers()->response_code());
1216 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1217 EXPECT_EQ(1, d.response_started_count());
1218 EXPECT_EQ(0, d.received_redirect_count());
1219}
1220
1221TEST_F(URLRequestTest, InterceptRedirect) {
1222 TestInterceptor interceptor;
1223
1224 // intercept the main request and respond with a redirect
1225 interceptor.intercept_main_request_ = true;
1226 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1227 interceptor.main_data_ = TestInterceptor::redirect_data();
1228
1229 // intercept that redirect and respond a final OK response
1230 interceptor.intercept_redirect_ = true;
1231 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1232 interceptor.redirect_data_ = TestInterceptor::ok_data();
1233
1234 TestDelegate d;
1235 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1236 req.set_method("GET");
1237 req.Start();
[email protected]255620da2013-08-19 13:14:291238 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441239
1240 // Check the interceptor got called as expected
1241 EXPECT_TRUE(interceptor.did_intercept_main_);
1242 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1243
1244 // Check we got one good response
1245 EXPECT_TRUE(req.status().is_success());
1246 if (req.status().is_success()) {
1247 EXPECT_EQ(200, req.response_headers()->response_code());
1248 }
1249 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1250 EXPECT_EQ(1, d.response_started_count());
1251 EXPECT_EQ(0, d.received_redirect_count());
1252}
1253
1254TEST_F(URLRequestTest, InterceptServerError) {
1255 TestInterceptor interceptor;
1256
1257 // intercept the main request to generate a server error response
1258 interceptor.intercept_main_request_ = true;
1259 interceptor.main_headers_ = TestInterceptor::error_headers();
1260 interceptor.main_data_ = TestInterceptor::error_data();
1261
1262 // intercept that error and respond with an OK response
1263 interceptor.intercept_final_response_ = true;
1264 interceptor.final_headers_ = TestInterceptor::ok_headers();
1265 interceptor.final_data_ = TestInterceptor::ok_data();
1266
1267 TestDelegate d;
1268 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1269 req.set_method("GET");
1270 req.Start();
[email protected]255620da2013-08-19 13:14:291271 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441272
1273 // Check the interceptor got called as expected
1274 EXPECT_TRUE(interceptor.did_intercept_main_);
1275 EXPECT_TRUE(interceptor.did_intercept_final_);
1276
1277 // Check we got one good response
1278 EXPECT_TRUE(req.status().is_success());
1279 EXPECT_EQ(200, req.response_headers()->response_code());
1280 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1281 EXPECT_EQ(1, d.response_started_count());
1282 EXPECT_EQ(0, d.received_redirect_count());
1283}
1284
1285TEST_F(URLRequestTest, InterceptNetworkError) {
1286 TestInterceptor interceptor;
1287
1288 // intercept the main request to simulate a network error
1289 interceptor.simulate_main_network_error_ = true;
1290
1291 // intercept that error and respond with an OK response
1292 interceptor.intercept_final_response_ = true;
1293 interceptor.final_headers_ = TestInterceptor::ok_headers();
1294 interceptor.final_data_ = TestInterceptor::ok_data();
1295
1296 TestDelegate d;
1297 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1298 req.set_method("GET");
1299 req.Start();
[email protected]255620da2013-08-19 13:14:291300 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441301
1302 // Check the interceptor got called as expected
1303 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1304 EXPECT_TRUE(interceptor.did_intercept_final_);
1305
1306 // Check we received one good response
1307 EXPECT_TRUE(req.status().is_success());
1308 EXPECT_EQ(200, req.response_headers()->response_code());
1309 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1310 EXPECT_EQ(1, d.response_started_count());
1311 EXPECT_EQ(0, d.received_redirect_count());
1312}
1313
1314TEST_F(URLRequestTest, InterceptRestartRequired) {
1315 TestInterceptor interceptor;
1316
1317 // restart the main request
1318 interceptor.restart_main_request_ = true;
1319
1320 // then intercept the new main request and respond with an OK response
1321 interceptor.intercept_main_request_ = true;
1322 interceptor.main_headers_ = TestInterceptor::ok_headers();
1323 interceptor.main_data_ = TestInterceptor::ok_data();
1324
1325 TestDelegate d;
1326 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1327 req.set_method("GET");
1328 req.Start();
[email protected]255620da2013-08-19 13:14:291329 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441330
1331 // Check the interceptor got called as expected
1332 EXPECT_TRUE(interceptor.did_restart_main_);
1333 EXPECT_TRUE(interceptor.did_intercept_main_);
1334
1335 // Check we received one good response
1336 EXPECT_TRUE(req.status().is_success());
1337 if (req.status().is_success()) {
1338 EXPECT_EQ(200, req.response_headers()->response_code());
1339 }
1340 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1341 EXPECT_EQ(1, d.response_started_count());
1342 EXPECT_EQ(0, d.received_redirect_count());
1343}
1344
1345TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1346 TestInterceptor interceptor;
1347
1348 // intercept the main request and cancel from within the restarted job
1349 interceptor.cancel_main_request_ = true;
1350
1351 // setup to intercept final response and override it with an OK response
1352 interceptor.intercept_final_response_ = true;
1353 interceptor.final_headers_ = TestInterceptor::ok_headers();
1354 interceptor.final_data_ = TestInterceptor::ok_data();
1355
1356 TestDelegate d;
1357 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1358 req.set_method("GET");
1359 req.Start();
[email protected]255620da2013-08-19 13:14:291360 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441361
1362 // Check the interceptor got called as expected
1363 EXPECT_TRUE(interceptor.did_cancel_main_);
1364 EXPECT_FALSE(interceptor.did_intercept_final_);
1365
1366 // Check we see a canceled request
1367 EXPECT_FALSE(req.status().is_success());
1368 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1369}
1370
1371TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1372 TestInterceptor interceptor;
1373
1374 // intercept the main request and respond with a redirect
1375 interceptor.intercept_main_request_ = true;
1376 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1377 interceptor.main_data_ = TestInterceptor::redirect_data();
1378
1379 // intercept the redirect and cancel from within that job
1380 interceptor.cancel_redirect_request_ = true;
1381
1382 // setup to intercept final response and override it with an OK response
1383 interceptor.intercept_final_response_ = true;
1384 interceptor.final_headers_ = TestInterceptor::ok_headers();
1385 interceptor.final_data_ = TestInterceptor::ok_data();
1386
1387 TestDelegate d;
1388 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1389 req.set_method("GET");
1390 req.Start();
[email protected]255620da2013-08-19 13:14:291391 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441392
1393 // Check the interceptor got called as expected
1394 EXPECT_TRUE(interceptor.did_intercept_main_);
1395 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1396 EXPECT_FALSE(interceptor.did_intercept_final_);
1397
1398 // Check we see a canceled request
1399 EXPECT_FALSE(req.status().is_success());
1400 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1401}
1402
1403TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1404 TestInterceptor interceptor;
1405
1406 // intercept the main request to simulate a network error
1407 interceptor.simulate_main_network_error_ = true;
1408
1409 // setup to intercept final response and cancel from within that job
1410 interceptor.cancel_final_request_ = true;
1411
1412 TestDelegate d;
1413 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1414 req.set_method("GET");
1415 req.Start();
[email protected]255620da2013-08-19 13:14:291416 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441417
1418 // Check the interceptor got called as expected
1419 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1420 EXPECT_TRUE(interceptor.did_cancel_final_);
1421
1422 // Check we see a canceled request
1423 EXPECT_FALSE(req.status().is_success());
1424 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1425}
1426
1427TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1428 TestInterceptor interceptor;
1429
1430 // intercept the main request and cancel then restart from within that job
1431 interceptor.cancel_then_restart_main_request_ = true;
1432
1433 // setup to intercept final response and override it with an OK response
1434 interceptor.intercept_final_response_ = true;
1435 interceptor.final_headers_ = TestInterceptor::ok_headers();
1436 interceptor.final_data_ = TestInterceptor::ok_data();
1437
1438 TestDelegate d;
1439 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1440 req.set_method("GET");
1441 req.Start();
[email protected]255620da2013-08-19 13:14:291442 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441443
1444 // Check the interceptor got called as expected
1445 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1446 EXPECT_FALSE(interceptor.did_intercept_final_);
1447
1448 // Check we see a canceled request
1449 EXPECT_FALSE(req.status().is_success());
1450 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1451}
1452
[email protected]2bba3252013-04-08 19:50:591453LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1454 URLRequestContext* context) {
1455 TestInterceptor interceptor;
1456 interceptor.intercept_main_request_ = true;
1457 interceptor.main_request_load_timing_info_ = job_load_timing;
1458 TestDelegate d;
1459 URLRequest req(GURL("http://test_intercept/foo"), &d, context);
1460 req.Start();
[email protected]255620da2013-08-19 13:14:291461 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591462
1463 LoadTimingInfo resulting_load_timing;
1464 req.GetLoadTimingInfo(&resulting_load_timing);
1465
1466 // None of these should be modified by the URLRequest.
1467 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1468 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1469 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1470 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1471 EXPECT_EQ(job_load_timing.receive_headers_end,
1472 resulting_load_timing.receive_headers_end);
1473
1474 return resulting_load_timing;
1475}
1476
1477// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1478// reused. |connect_time_flags| is used to indicate if there should be dns
1479// or SSL times, and |used_proxy| is used for proxy times.
1480LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1481 int connect_time_flags,
1482 bool used_proxy) {
1483 LoadTimingInfo load_timing;
1484 load_timing.socket_log_id = 1;
1485
1486 if (used_proxy) {
1487 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1488 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1489 }
1490
1491 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1492 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1493 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1494 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1495 }
1496 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1497 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1498 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1499 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1500 }
1501 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1502
1503 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1504 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1505 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1506 return load_timing;
1507}
1508
1509// Same as above, but in the case of a reused socket.
1510LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1511 bool used_proxy) {
1512 LoadTimingInfo load_timing;
1513 load_timing.socket_log_id = 1;
1514 load_timing.socket_reused = true;
1515
1516 if (used_proxy) {
1517 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1518 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1519 }
1520
1521 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1522 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1523 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1524 return load_timing;
1525}
1526
1527// Basic test that the intercept + load timing tests work.
1528TEST_F(URLRequestTest, InterceptLoadTiming) {
1529 base::TimeTicks now = base::TimeTicks::Now();
1530 LoadTimingInfo job_load_timing =
1531 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1532
1533 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1534 &default_context_);
1535
1536 // Nothing should have been changed by the URLRequest.
1537 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1538 load_timing_result.proxy_resolve_start);
1539 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1540 load_timing_result.proxy_resolve_end);
1541 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1542 load_timing_result.connect_timing.dns_start);
1543 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1544 load_timing_result.connect_timing.dns_end);
1545 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1546 load_timing_result.connect_timing.connect_start);
1547 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1548 load_timing_result.connect_timing.connect_end);
1549 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1550 load_timing_result.connect_timing.ssl_start);
1551 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1552 load_timing_result.connect_timing.ssl_end);
1553
1554 // Redundant sanity check.
1555 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1556}
1557
1558// Another basic test, with proxy and SSL times, but no DNS times.
1559TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1560 base::TimeTicks now = base::TimeTicks::Now();
1561 LoadTimingInfo job_load_timing =
1562 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1563
1564 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1565 &default_context_);
1566
1567 // Nothing should have been changed by the URLRequest.
1568 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1569 load_timing_result.proxy_resolve_start);
1570 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1571 load_timing_result.proxy_resolve_end);
1572 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1573 load_timing_result.connect_timing.dns_start);
1574 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1575 load_timing_result.connect_timing.dns_end);
1576 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1577 load_timing_result.connect_timing.connect_start);
1578 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1579 load_timing_result.connect_timing.connect_end);
1580 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1581 load_timing_result.connect_timing.ssl_start);
1582 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1583 load_timing_result.connect_timing.ssl_end);
1584
1585 // Redundant sanity check.
1586 TestLoadTimingNotReusedWithProxy(load_timing_result,
1587 CONNECT_TIMING_HAS_SSL_TIMES);
1588}
1589
1590// Make sure that URLRequest correctly adjusts proxy times when they're before
1591// |request_start|, due to already having a connected socket. This happens in
1592// the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1593// not considered reused in this test (May be a preconnect).
1594//
1595// To mix things up from the test above, assumes DNS times but no SSL times.
1596TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1597 base::TimeTicks now = base::TimeTicks::Now();
1598 LoadTimingInfo job_load_timing =
1599 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1600 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1601 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1602 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1603 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1604 job_load_timing.connect_timing.connect_start =
1605 now - base::TimeDelta::FromDays(2);
1606 job_load_timing.connect_timing.connect_end =
1607 now - base::TimeDelta::FromDays(1);
1608
1609 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1610 &default_context_);
1611
1612 // Proxy times, connect times, and DNS times should all be replaced with
1613 // request_start.
1614 EXPECT_EQ(load_timing_result.request_start,
1615 load_timing_result.proxy_resolve_start);
1616 EXPECT_EQ(load_timing_result.request_start,
1617 load_timing_result.proxy_resolve_end);
1618 EXPECT_EQ(load_timing_result.request_start,
1619 load_timing_result.connect_timing.dns_start);
1620 EXPECT_EQ(load_timing_result.request_start,
1621 load_timing_result.connect_timing.dns_end);
1622 EXPECT_EQ(load_timing_result.request_start,
1623 load_timing_result.connect_timing.connect_start);
1624 EXPECT_EQ(load_timing_result.request_start,
1625 load_timing_result.connect_timing.connect_end);
1626
1627 // Other times should have been left null.
1628 TestLoadTimingNotReusedWithProxy(load_timing_result,
1629 CONNECT_TIMING_HAS_DNS_TIMES);
1630}
1631
1632// Same as above, but in the reused case.
1633TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1634 base::TimeTicks now = base::TimeTicks::Now();
1635 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1636 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1637 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1638
1639 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1640 &default_context_);
1641
1642 // Proxy times and connect times should all be replaced with request_start.
1643 EXPECT_EQ(load_timing_result.request_start,
1644 load_timing_result.proxy_resolve_start);
1645 EXPECT_EQ(load_timing_result.request_start,
1646 load_timing_result.proxy_resolve_end);
1647
1648 // Other times should have been left null.
1649 TestLoadTimingReusedWithProxy(load_timing_result);
1650}
1651
1652// Make sure that URLRequest correctly adjusts connect times when they're before
1653// |request_start|, due to reusing a connected socket. The connected socket is
1654// not considered reused in this test (May be a preconnect).
1655//
1656// To mix things up, the request has SSL times, but no DNS times.
1657TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1658 base::TimeTicks now = base::TimeTicks::Now();
1659 LoadTimingInfo job_load_timing =
1660 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1661 job_load_timing.connect_timing.connect_start =
1662 now - base::TimeDelta::FromDays(1);
1663 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1664 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1665 job_load_timing.connect_timing.connect_end =
1666 now - base::TimeDelta::FromDays(4);
1667
1668 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1669 &default_context_);
1670
1671 // Connect times, and SSL times should be replaced with request_start.
1672 EXPECT_EQ(load_timing_result.request_start,
1673 load_timing_result.connect_timing.connect_start);
1674 EXPECT_EQ(load_timing_result.request_start,
1675 load_timing_result.connect_timing.ssl_start);
1676 EXPECT_EQ(load_timing_result.request_start,
1677 load_timing_result.connect_timing.ssl_end);
1678 EXPECT_EQ(load_timing_result.request_start,
1679 load_timing_result.connect_timing.connect_end);
1680
1681 // Other times should have been left null.
1682 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1683}
1684
1685// Make sure that URLRequest correctly adjusts connect times when they're before
1686// |request_start|, due to reusing a connected socket in the case that there
1687// are also proxy times. The connected socket is not considered reused in this
1688// test (May be a preconnect).
1689//
1690// In this test, there are no SSL or DNS times.
1691TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1692 base::TimeTicks now = base::TimeTicks::Now();
1693 LoadTimingInfo job_load_timing =
1694 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1695 job_load_timing.connect_timing.connect_start =
1696 now - base::TimeDelta::FromDays(1);
1697 job_load_timing.connect_timing.connect_end =
1698 now - base::TimeDelta::FromDays(2);
1699
1700 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1701 &default_context_);
1702
1703 // Connect times should be replaced with proxy_resolve_end.
1704 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1705 load_timing_result.connect_timing.connect_start);
1706 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1707 load_timing_result.connect_timing.connect_end);
1708
1709 // Other times should have been left null.
1710 TestLoadTimingNotReusedWithProxy(load_timing_result,
1711 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1712}
1713
[email protected]316c1e5e2012-09-12 15:17:441714// Check that two different URL requests have different identifiers.
1715TEST_F(URLRequestTest, Identifiers) {
1716 TestDelegate d;
1717 TestURLRequestContext context;
[email protected]cc05edc2013-03-08 18:04:411718 TestURLRequest req(GURL("http://example.com"), &d, &context, NULL);
1719 TestURLRequest other_req(GURL("http://example.com"), &d, &context, NULL);
[email protected]316c1e5e2012-09-12 15:17:441720
1721 ASSERT_NE(req.identifier(), other_req.identifier());
1722}
1723
1724// Check that a failure to connect to the proxy is reported to the network
1725// delegate.
1726TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1727 MockHostResolver host_resolver;
1728 host_resolver.rules()->AddSimulatedFailure("*");
1729
[email protected]ceefd7fd2012-11-29 00:36:241730 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:441731 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1732
1733 TestDelegate d;
1734 URLRequest req(GURL("http://example.com"), &d, &context);
1735 req.set_method("GET");
1736
1737 req.Start();
[email protected]255620da2013-08-19 13:14:291738 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441739
1740 // Check we see a failed request.
1741 EXPECT_FALSE(req.status().is_success());
1742 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1743 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1744
1745 EXPECT_EQ(1, network_delegate.error_count());
1746 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1747 EXPECT_EQ(1, network_delegate.completed_requests());
1748}
1749
1750// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1751// content is empty.
1752TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1753 TestDelegate d;
1754 URLRequest req(GURL("data:,"), &d, &default_context_);
1755 req.Start();
[email protected]255620da2013-08-19 13:14:291756 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441757 EXPECT_EQ("", d.data_received());
1758 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1759}
1760
[email protected]5033ab82013-03-22 20:17:461761// Make sure that SetPriority actually sets the URLRequest's priority
1762// correctly, both before and after start.
1763TEST_F(URLRequestTest, SetPriorityBasic) {
1764 TestDelegate d;
1765 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1766 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1767
1768 req.SetPriority(LOW);
1769 EXPECT_EQ(LOW, req.priority());
1770
1771 req.Start();
1772 EXPECT_EQ(LOW, req.priority());
1773
1774 req.SetPriority(MEDIUM);
1775 EXPECT_EQ(MEDIUM, req.priority());
1776}
1777
1778// Make sure that URLRequest calls SetPriority on a job before calling
1779// Start on it.
1780TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1781 TestDelegate d;
1782 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1783 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1784
1785 scoped_refptr<URLRequestTestJob> job =
1786 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501787 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461788 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1789
1790 req.SetPriority(LOW);
1791
1792 req.Start();
1793 EXPECT_EQ(LOW, job->priority());
1794}
1795
1796// Make sure that URLRequest passes on its priority updates to its
1797// job.
1798TEST_F(URLRequestTest, SetJobPriority) {
1799 TestDelegate d;
1800 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1801
1802 scoped_refptr<URLRequestTestJob> job =
1803 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501804 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461805
1806 req.SetPriority(LOW);
1807 req.Start();
1808 EXPECT_EQ(LOW, job->priority());
1809
1810 req.SetPriority(MEDIUM);
1811 EXPECT_EQ(MEDIUM, req.priority());
1812 EXPECT_EQ(MEDIUM, job->priority());
1813}
1814
[email protected]ce7d0cbc2013-05-03 18:57:221815// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:441816#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:221817// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1818// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:441819// http://crbug.com/114369
[email protected]ce7d0cbc2013-05-03 18:57:221820class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:441821 public:
[email protected]6cdfd7f2013-02-08 20:40:151822 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:221823 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1824 ScopedCustomUrlRequestTestHttpHost::value(),
1825 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:441826 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:221827 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1828 ScopedCustomUrlRequestTestHttpHost::value(),
1829 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441830};
1831
[email protected]f2f31b32013-01-16 23:24:091832TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441833 LocalHttpTestServer test_server;
1834 ASSERT_TRUE(test_server.Start());
1835
1836 TestURLRequestContext context;
1837 scoped_refptr<DelayedCookieMonster> delayed_cm =
1838 new DelayedCookieMonster();
1839 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:501840 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:441841
1842 // Set up a cookie.
1843 {
1844 TestNetworkDelegate network_delegate;
1845 context.set_network_delegate(&network_delegate);
1846 TestDelegate d;
1847 URLRequest req(
1848 test_server.GetURL("set-cookie?CookieToNotSend=1"), &d, &context);
1849 req.Start();
[email protected]255620da2013-08-19 13:14:291850 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441851 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1852 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1853 EXPECT_EQ(1, network_delegate.set_cookie_count());
1854 }
1855
1856 // Verify that the cookie is set.
1857 {
1858 TestNetworkDelegate network_delegate;
1859 context.set_network_delegate(&network_delegate);
1860 TestDelegate d;
1861 URLRequest req(test_server.GetURL("echoheader?Cookie"), &d, &context);
1862 req.Start();
[email protected]255620da2013-08-19 13:14:291863 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441864
1865 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1866 != std::string::npos);
1867 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1868 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1869 }
1870}
1871
[email protected]f2f31b32013-01-16 23:24:091872TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:441873 LocalHttpTestServer test_server;
1874 ASSERT_TRUE(test_server.Start());
1875
1876 // Set up a cookie.
1877 {
1878 TestNetworkDelegate network_delegate;
1879 default_context_.set_network_delegate(&network_delegate);
1880 TestDelegate d;
1881 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1882 &d,
1883 &default_context_);
1884 req.Start();
[email protected]255620da2013-08-19 13:14:291885 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441886 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1887 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1888 }
1889
1890 // Verify that the cookie is set.
1891 {
1892 TestNetworkDelegate network_delegate;
1893 default_context_.set_network_delegate(&network_delegate);
1894 TestDelegate d;
1895 URLRequest req(
1896 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1897 req.Start();
[email protected]255620da2013-08-19 13:14:291898 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441899
1900 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1901 != std::string::npos);
1902 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1903 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1904 }
1905
1906 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
1907 {
1908 TestNetworkDelegate network_delegate;
1909 default_context_.set_network_delegate(&network_delegate);
1910 TestDelegate d;
1911 URLRequest req(
1912 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1913 req.set_load_flags(LOAD_DO_NOT_SEND_COOKIES);
1914 req.Start();
[email protected]255620da2013-08-19 13:14:291915 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441916
1917 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
1918 == std::string::npos);
1919
1920 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
1921 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1922 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1923 }
1924}
1925
1926TEST_F(URLRequestTest, DoNotSaveCookies) {
1927 LocalHttpTestServer test_server;
1928 ASSERT_TRUE(test_server.Start());
1929
1930 // Set up a cookie.
1931 {
1932 TestNetworkDelegate network_delegate;
1933 default_context_.set_network_delegate(&network_delegate);
1934 TestDelegate d;
1935 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
1936 &d,
1937 &default_context_);
1938 req.Start();
[email protected]255620da2013-08-19 13:14:291939 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441940
1941 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1942 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1943 EXPECT_EQ(1, network_delegate.set_cookie_count());
1944 }
1945
1946 // Try to set-up another cookie and update the previous cookie.
1947 {
1948 TestNetworkDelegate network_delegate;
1949 default_context_.set_network_delegate(&network_delegate);
1950 TestDelegate d;
1951 URLRequest req(
1952 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
1953 &d,
1954 &default_context_);
1955 req.set_load_flags(LOAD_DO_NOT_SAVE_COOKIES);
1956 req.Start();
1957
[email protected]255620da2013-08-19 13:14:291958 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441959
1960 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
1961 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1962 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1963 EXPECT_EQ(0, network_delegate.set_cookie_count());
1964 }
1965
1966 // Verify the cookies weren't saved or updated.
1967 {
1968 TestNetworkDelegate network_delegate;
1969 default_context_.set_network_delegate(&network_delegate);
1970 TestDelegate d;
1971 URLRequest req(
1972 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1973 req.Start();
[email protected]255620da2013-08-19 13:14:291974 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441975
1976 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
1977 == std::string::npos);
1978 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
1979 != std::string::npos);
1980
1981 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1982 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1983 EXPECT_EQ(0, network_delegate.set_cookie_count());
1984 }
1985}
1986
1987TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
1988 LocalHttpTestServer test_server;
1989 ASSERT_TRUE(test_server.Start());
1990
1991 // Set up a cookie.
1992 {
1993 TestNetworkDelegate network_delegate;
1994 default_context_.set_network_delegate(&network_delegate);
1995 TestDelegate d;
1996 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1997 &d,
1998 &default_context_);
1999 req.Start();
[email protected]255620da2013-08-19 13:14:292000 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442001
2002 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2003 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2004 }
2005
2006 // Verify that the cookie is set.
2007 {
2008 TestNetworkDelegate network_delegate;
2009 default_context_.set_network_delegate(&network_delegate);
2010 TestDelegate d;
2011 URLRequest req(
2012 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2013 req.Start();
[email protected]255620da2013-08-19 13:14:292014 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442015
2016 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2017 != std::string::npos);
2018
2019 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2020 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2021 }
2022
2023 // Verify that the cookie isn't sent.
2024 {
2025 TestNetworkDelegate network_delegate;
2026 default_context_.set_network_delegate(&network_delegate);
2027 TestDelegate d;
2028 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2029 URLRequest req(
2030 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2031 req.Start();
[email protected]255620da2013-08-19 13:14:292032 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442033
2034 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2035 == std::string::npos);
2036
[email protected]22e045f2013-09-20 03:54:032037 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442038 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2039 }
2040}
2041
2042TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2043 LocalHttpTestServer test_server;
2044 ASSERT_TRUE(test_server.Start());
2045
2046 // Set up a cookie.
2047 {
2048 TestNetworkDelegate network_delegate;
2049 default_context_.set_network_delegate(&network_delegate);
2050 TestDelegate d;
2051 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2052 &d,
2053 &default_context_);
2054 req.Start();
[email protected]255620da2013-08-19 13:14:292055 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442056
2057 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2058 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2059 }
2060
2061 // Try to set-up another cookie and update the previous cookie.
2062 {
2063 TestNetworkDelegate network_delegate;
2064 default_context_.set_network_delegate(&network_delegate);
2065 TestDelegate d;
2066 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2067 URLRequest req(
2068 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2069 &d,
2070 &default_context_);
2071 req.Start();
2072
[email protected]255620da2013-08-19 13:14:292073 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442074
2075 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2076 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2077 }
2078
2079 // Verify the cookies weren't saved or updated.
2080 {
2081 TestNetworkDelegate network_delegate;
2082 default_context_.set_network_delegate(&network_delegate);
2083 TestDelegate d;
2084 URLRequest req(
2085 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2086 req.Start();
[email protected]255620da2013-08-19 13:14:292087 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442088
2089 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2090 == std::string::npos);
2091 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2092 != std::string::npos);
2093
2094 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2095 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2096 }
2097}
2098
2099TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2100 LocalHttpTestServer test_server;
2101 ASSERT_TRUE(test_server.Start());
2102
2103 // Set up an empty cookie.
2104 {
2105 TestNetworkDelegate network_delegate;
2106 default_context_.set_network_delegate(&network_delegate);
2107 TestDelegate d;
2108 URLRequest req(test_server.GetURL("set-cookie"), &d, &default_context_);
2109 req.Start();
[email protected]255620da2013-08-19 13:14:292110 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442111
2112 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2113 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2114 EXPECT_EQ(0, network_delegate.set_cookie_count());
2115 }
2116}
2117
2118TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2119 LocalHttpTestServer test_server;
2120 ASSERT_TRUE(test_server.Start());
2121
2122 // Set up a cookie.
2123 {
2124 TestNetworkDelegate network_delegate;
2125 default_context_.set_network_delegate(&network_delegate);
2126 TestDelegate d;
2127 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2128 &d,
2129 &default_context_);
2130 req.Start();
[email protected]255620da2013-08-19 13:14:292131 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442132
2133 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2134 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2135 }
2136
2137 // Verify that the cookie is set.
2138 {
2139 TestNetworkDelegate network_delegate;
2140 default_context_.set_network_delegate(&network_delegate);
2141 TestDelegate d;
2142 URLRequest req(
2143 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2144 req.Start();
[email protected]255620da2013-08-19 13:14:292145 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442146
2147 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2148 != std::string::npos);
2149
2150 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2151 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2152 }
2153
2154 // Verify that the cookie isn't sent.
2155 {
2156 TestNetworkDelegate network_delegate;
2157 default_context_.set_network_delegate(&network_delegate);
2158 TestDelegate d;
2159 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2160 URLRequest req(
2161 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2162 req.Start();
[email protected]255620da2013-08-19 13:14:292163 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442164
2165 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2166 == std::string::npos);
2167
[email protected]22e045f2013-09-20 03:54:032168 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442169 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2170 }
2171}
2172
2173TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2174 LocalHttpTestServer test_server;
2175 ASSERT_TRUE(test_server.Start());
2176
2177 // Set up a cookie.
2178 {
2179 TestNetworkDelegate network_delegate;
2180 default_context_.set_network_delegate(&network_delegate);
2181 TestDelegate d;
2182 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2183 &d,
2184 &default_context_);
2185 req.Start();
[email protected]255620da2013-08-19 13:14:292186 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442187
2188 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2189 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2190 }
2191
2192 // Try to set-up another cookie and update the previous cookie.
2193 {
2194 TestNetworkDelegate network_delegate;
2195 default_context_.set_network_delegate(&network_delegate);
2196 TestDelegate d;
2197 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2198 URLRequest req(
2199 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2200 &d,
2201 &default_context_);
2202 req.Start();
2203
[email protected]255620da2013-08-19 13:14:292204 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442205
2206 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2207 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2208 }
2209
2210 // Verify the cookies weren't saved or updated.
2211 {
2212 TestNetworkDelegate network_delegate;
2213 default_context_.set_network_delegate(&network_delegate);
2214 TestDelegate d;
2215 URLRequest req(
2216 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2217 req.Start();
[email protected]255620da2013-08-19 13:14:292218 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442219
2220 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2221 == std::string::npos);
2222 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2223 != std::string::npos);
2224
2225 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2226 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2227 }
2228}
2229
[email protected]5095cd72012-11-01 10:29:162230// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2231// value for the |fixed_date| argument given to the constructor.
2232class FixedDateNetworkDelegate : public TestNetworkDelegate {
2233 public:
2234 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2235 : fixed_date_(fixed_date) {}
2236 virtual ~FixedDateNetworkDelegate() {}
2237
2238 // net::NetworkDelegate implementation
2239 virtual int OnHeadersReceived(
2240 net::URLRequest* request,
2241 const net::CompletionCallback& callback,
2242 const net::HttpResponseHeaders* original_response_headers,
2243 scoped_refptr<net::HttpResponseHeaders>* override_response_headers)
2244 OVERRIDE;
2245
2246 private:
2247 std::string fixed_date_;
2248
2249 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2250};
2251
2252int FixedDateNetworkDelegate::OnHeadersReceived(
2253 net::URLRequest* request,
2254 const net::CompletionCallback& callback,
2255 const net::HttpResponseHeaders* original_response_headers,
2256 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
2257 net::HttpResponseHeaders* new_response_headers =
2258 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2259
2260 new_response_headers->RemoveHeader("Date");
2261 new_response_headers->AddHeader("Date: " + fixed_date_);
2262
2263 *override_response_headers = new_response_headers;
2264 return TestNetworkDelegate::OnHeadersReceived(request,
2265 callback,
2266 original_response_headers,
2267 override_response_headers);
2268}
2269
2270// Test that cookie expiration times are adjusted for server/client clock
2271// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2272// headers by defaulting to GMT. (crbug.com/135131)
2273TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2274 LocalHttpTestServer test_server;
2275 ASSERT_TRUE(test_server.Start());
2276
2277 // Set up an expired cookie.
2278 {
2279 TestNetworkDelegate network_delegate;
2280 default_context_.set_network_delegate(&network_delegate);
2281 TestDelegate d;
2282 URLRequest req(test_server.GetURL(
2283 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2284 &d,
2285 &default_context_);
2286 req.Start();
[email protected]255620da2013-08-19 13:14:292287 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162288 }
2289 // Verify that the cookie is not set.
2290 {
2291 TestNetworkDelegate network_delegate;
2292 default_context_.set_network_delegate(&network_delegate);
2293 TestDelegate d;
2294 URLRequest req(
2295 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2296 req.Start();
[email protected]255620da2013-08-19 13:14:292297 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162298
2299 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2300 }
2301 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2302 {
2303 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2304 default_context_.set_network_delegate(&network_delegate);
2305 TestDelegate d;
2306 URLRequest req(test_server.GetURL(
2307 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2308 &d,
2309 &default_context_);
2310 req.Start();
[email protected]255620da2013-08-19 13:14:292311 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162312 }
2313 // Verify that the cookie is set.
2314 {
2315 TestNetworkDelegate network_delegate;
2316 default_context_.set_network_delegate(&network_delegate);
2317 TestDelegate d;
2318 URLRequest req(
2319 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2320 req.Start();
[email protected]255620da2013-08-19 13:14:292321 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162322
2323 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2324 }
2325}
2326
2327
[email protected]316c1e5e2012-09-12 15:17:442328// Check that it is impossible to change the referrer in the extra headers of
2329// an URLRequest.
2330TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2331 LocalHttpTestServer test_server;
2332 ASSERT_TRUE(test_server.Start());
2333
2334 // If extra headers contain referer and the request contains a referer,
2335 // only the latter shall be respected.
2336 {
2337 TestDelegate d;
2338 URLRequest req(
2339 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:132340 req.SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442341
2342 HttpRequestHeaders headers;
2343 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2344 req.SetExtraRequestHeaders(headers);
2345
2346 req.Start();
[email protected]255620da2013-08-19 13:14:292347 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442348
2349 EXPECT_EQ("http://foo.com/", d.data_received());
2350 }
2351
2352 // If extra headers contain a referer but the request does not, no referer
2353 // shall be sent in the header.
2354 {
2355 TestDelegate d;
2356 URLRequest req(
2357 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
2358
2359 HttpRequestHeaders headers;
2360 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2361 req.SetExtraRequestHeaders(headers);
2362 req.set_load_flags(LOAD_VALIDATE_CACHE);
2363
2364 req.Start();
[email protected]255620da2013-08-19 13:14:292365 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442366
2367 EXPECT_EQ("None", d.data_received());
2368 }
2369}
2370
[email protected]b89290212009-08-14 22:37:352371class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112372 public:
2373 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152374 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112375 "net/data/url_request_unittest"))) {
2376 }
2377
[email protected]b89290212009-08-14 22:37:352378 protected:
[email protected]21184962011-10-26 00:50:302379 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2380 // |request_method| is the method to use for the initial request.
2381 // |redirect_method| is the method that is expected to be used for the second
2382 // request, after redirection.
2383 // If |include_data| is true, data is uploaded with the request. The
2384 // response body is expected to match it exactly, if and only if
2385 // |request_method| == |redirect_method|.
2386 void HTTPRedirectMethodTest(const GURL& redirect_url,
2387 const std::string& request_method,
2388 const std::string& redirect_method,
2389 bool include_data) {
2390 static const char kData[] = "hello world";
2391 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:132392 URLRequest req(redirect_url, &d, &default_context_);
[email protected]21184962011-10-26 00:50:302393 req.set_method(request_method);
2394 if (include_data) {
[email protected]f288ef02012-12-15 20:28:282395 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:302396 HttpRequestHeaders headers;
2397 headers.SetHeader(HttpRequestHeaders::kContentLength,
2398 base::UintToString(arraysize(kData) - 1));
2399 req.SetExtraRequestHeaders(headers);
2400 }
2401 req.Start();
[email protected]255620da2013-08-19 13:14:292402 base::RunLoop().Run();
[email protected]21184962011-10-26 00:50:302403 EXPECT_EQ(redirect_method, req.method());
2404 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2405 EXPECT_EQ(OK, req.status().error());
2406 if (include_data) {
2407 if (request_method == redirect_method) {
2408 EXPECT_EQ(kData, d.data_received());
2409 } else {
2410 EXPECT_NE(kData, d.data_received());
2411 }
2412 }
2413 if (HasFailure())
2414 LOG(WARNING) << "Request method was: " << request_method;
2415 }
2416
[email protected]762d2db2010-01-11 19:03:012417 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012418 const int kMsgSize = 20000; // multiple of 10
2419 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482420 char* uploadBytes = new char[kMsgSize+1];
2421 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012422 char marker = 'a';
2423 for (int idx = 0; idx < kMsgSize/10; idx++) {
2424 memcpy(ptr, "----------", 10);
2425 ptr += 10;
2426 if (idx % 100 == 0) {
2427 ptr--;
2428 *ptr++ = marker;
2429 if (++marker > 'z')
2430 marker = 'a';
2431 }
2432 }
2433 uploadBytes[kMsgSize] = '\0';
2434
[email protected]762d2db2010-01-11 19:03:012435 for (int i = 0; i < kIterations; ++i) {
2436 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:132437 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012438 r.set_method(method.c_str());
2439
[email protected]f288ef02012-12-15 20:28:282440 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012441
2442 r.Start();
2443 EXPECT_TRUE(r.is_pending());
2444
[email protected]255620da2013-08-19 13:14:292445 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012446
[email protected]329b68b2012-11-14 17:54:272447 ASSERT_EQ(1, d.response_started_count())
2448 << "request failed: " << r.status().status()
2449 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012450
2451 EXPECT_FALSE(d.received_data_before_response());
2452 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012453 }
2454 delete[] uploadBytes;
2455 }
2456
[email protected]ef2bf422012-05-11 03:27:092457 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222458 r->AppendChunkToUpload("a", 1, false);
2459 r->AppendChunkToUpload("bcd", 3, false);
2460 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2461 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2462 r->AppendChunkToUpload("0", 1, false);
2463 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112464 }
2465
[email protected]ef2bf422012-05-11 03:27:092466 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112467 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272468 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112469 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2470
[email protected]329b68b2012-11-14 17:54:272471 ASSERT_EQ(1, d->response_started_count())
2472 << "request failed: " << r->status().status()
2473 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112474
2475 EXPECT_FALSE(d->received_data_before_response());
2476
[email protected]329b68b2012-11-14 17:54:272477 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2478 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112479 }
2480
[email protected]ede03212012-09-07 12:52:262481 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342482 TestDelegate d;
2483 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2484 base::IntToString(num_cookies)),
[email protected]94e2bbe2012-06-22 15:26:132485 &d,
2486 &default_context_);
[email protected]263163f2012-06-14 22:40:342487
2488 r.Start();
2489 EXPECT_TRUE(r.is_pending());
2490
[email protected]255620da2013-08-19 13:14:292491 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342492
2493 bool is_success = r.status().is_success();
2494
[email protected]ede03212012-09-07 12:52:262495 if (!is_success) {
[email protected]263163f2012-06-14 22:40:342496 // Requests handled by ChromeFrame send a less precise error message,
2497 // ERR_CONNECTION_ABORTED.
2498 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG ||
2499 r.status().error() == ERR_CONNECTION_ABORTED);
2500 // The test server appears to be unable to handle subsequent requests
2501 // after this error is triggered. Force it to restart.
2502 EXPECT_TRUE(test_server_.Stop());
2503 EXPECT_TRUE(test_server_.Start());
2504 }
2505
2506 return is_success;
2507 }
2508
[email protected]1700c6a2012-02-22 18:07:072509 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352510};
2511
[email protected]95409e12010-08-17 20:07:112512// In this unit test, we're using the HTTPTestServer as a proxy server and
2513// issuing a CONNECT request with the magic host name "www.redirect.com".
2514// The HTTPTestServer will return a 302 response, which we should not
2515// follow.
[email protected]f2f31b32013-01-16 23:24:092516TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112517 ASSERT_TRUE(test_server_.Start());
2518
[email protected]ceefd7fd2012-11-29 00:36:242519 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042520 TestURLRequestContextWithProxy context(
2521 test_server_.host_port_pair().ToString(),
2522 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502523
[email protected]d1ec59082009-02-11 02:48:152524 TestDelegate d;
2525 {
[email protected]94e2bbe2012-06-22 15:26:132526 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]d1ec59082009-02-11 02:48:152527 r.Start();
2528 EXPECT_TRUE(r.is_pending());
2529
[email protected]255620da2013-08-19 13:14:292530 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152531
[email protected]7461a402011-03-24 23:19:512532 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052533 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082534 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152535 // We should not have followed the redirect.
2536 EXPECT_EQ(0, d.received_redirect_count());
2537 }
2538}
2539
[email protected]8202d0c2011-02-23 08:31:142540// This is the same as the previous test, but checks that the network delegate
2541// registers the error.
[email protected]c044616e2013-02-20 02:01:262542TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142543 ASSERT_TRUE(test_server_.Start());
2544
[email protected]ceefd7fd2012-11-29 00:36:242545 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042546 TestURLRequestContextWithProxy context(
2547 test_server_.host_port_pair().ToString(),
2548 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502549
[email protected]8202d0c2011-02-23 08:31:142550 TestDelegate d;
2551 {
[email protected]94e2bbe2012-06-22 15:26:132552 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]8202d0c2011-02-23 08:31:142553 r.Start();
2554 EXPECT_TRUE(r.is_pending());
2555
[email protected]255620da2013-08-19 13:14:292556 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142557
[email protected]7461a402011-03-24 23:19:512558 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052559 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142560 EXPECT_EQ(1, d.response_started_count());
2561 // We should not have followed the redirect.
2562 EXPECT_EQ(0, d.received_redirect_count());
2563
2564 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052565 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142566 }
2567}
2568
[email protected]dc5a5cf2012-09-26 02:49:302569// Tests that we can block and asynchronously return OK in various stages.
2570TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2571 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2572 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2573 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2574 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2575 };
2576 static const size_t blocking_stages_length = arraysize(blocking_stages);
2577
2578 ASSERT_TRUE(test_server_.Start());
2579
2580 TestDelegate d;
2581 BlockingNetworkDelegate network_delegate(
2582 BlockingNetworkDelegate::USER_CALLBACK);
2583 network_delegate.set_block_on(
2584 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2585 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2586 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2587
2588 TestURLRequestContext context(true);
2589 context.set_network_delegate(&network_delegate);
2590 context.Init();
2591
2592 {
2593 URLRequest r(test_server_.GetURL("empty.html"), &d, &context);
2594
2595 r.Start();
2596 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292597 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302598 EXPECT_EQ(blocking_stages[i],
2599 network_delegate.stage_blocked_for_callback());
2600 network_delegate.DoCallback(OK);
2601 }
[email protected]255620da2013-08-19 13:14:292602 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302603 EXPECT_EQ(200, r.GetResponseCode());
2604 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2605 EXPECT_EQ(1, network_delegate.created_requests());
2606 EXPECT_EQ(0, network_delegate.destroyed_requests());
2607 }
2608 EXPECT_EQ(1, network_delegate.destroyed_requests());
2609}
2610
[email protected]4c76d7c2011-04-15 19:14:122611// Tests that the network delegate can block and cancel a request.
2612TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2613 ASSERT_TRUE(test_server_.Start());
2614
2615 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302616 BlockingNetworkDelegate network_delegate(
2617 BlockingNetworkDelegate::AUTO_CALLBACK);
2618 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2619 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122620
[email protected]d5a4dd62012-05-23 01:41:042621 TestURLRequestContextWithProxy context(
2622 test_server_.host_port_pair().ToString(),
2623 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502624
[email protected]4c76d7c2011-04-15 19:14:122625 {
[email protected]007b3f82013-04-09 08:46:452626 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122627
2628 r.Start();
[email protected]255620da2013-08-19 13:14:292629 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122630
2631 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052632 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122633 EXPECT_EQ(1, network_delegate.created_requests());
2634 EXPECT_EQ(0, network_delegate.destroyed_requests());
2635 }
2636 EXPECT_EQ(1, network_delegate.destroyed_requests());
2637}
2638
[email protected]b4438d32012-09-27 06:15:302639// Helper function for NetworkDelegateCancelRequestAsynchronously and
2640// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2641// delegate operating in |block_mode| and a request for |url|. It blocks the
2642// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2643void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2644 BlockingNetworkDelegate::Stage stage,
2645 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362646 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302647 BlockingNetworkDelegate network_delegate(block_mode);
2648 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2649 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362650
[email protected]b4438d32012-09-27 06:15:302651 TestURLRequestContext context(true);
2652 context.set_network_delegate(&network_delegate);
2653 context.Init();
[email protected]3cd384c602011-08-31 16:12:362654
2655 {
[email protected]b4438d32012-09-27 06:15:302656 URLRequest r(url, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362657
2658 r.Start();
[email protected]255620da2013-08-19 13:14:292659 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362660
2661 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]b4438d32012-09-27 06:15:302662 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362663 EXPECT_EQ(1, network_delegate.created_requests());
2664 EXPECT_EQ(0, network_delegate.destroyed_requests());
2665 }
2666 EXPECT_EQ(1, network_delegate.destroyed_requests());
2667}
2668
[email protected]b4438d32012-09-27 06:15:302669// The following 3 tests check that the network delegate can cancel a request
2670// synchronously in various stages of the request.
2671TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2672 ASSERT_TRUE(test_server_.Start());
2673 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2674 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452675 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302676}
2677
2678TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2679 ASSERT_TRUE(test_server_.Start());
2680 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2681 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452682 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302683}
2684
2685TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2686 ASSERT_TRUE(test_server_.Start());
2687 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2688 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452689 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302690}
2691
2692// The following 3 tests check that the network delegate can cancel a request
2693// asynchronously in various stages of the request.
2694TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2695 ASSERT_TRUE(test_server_.Start());
2696 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2697 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452698 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302699}
2700
2701TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2702 ASSERT_TRUE(test_server_.Start());
2703 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2704 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452705 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302706}
2707
2708TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2709 ASSERT_TRUE(test_server_.Start());
2710 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2711 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452712 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302713}
2714
[email protected]4c76d7c2011-04-15 19:14:122715// Tests that the network delegate can block and redirect a request to a new
2716// URL.
2717TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2718 ASSERT_TRUE(test_server_.Start());
2719
2720 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302721 BlockingNetworkDelegate network_delegate(
2722 BlockingNetworkDelegate::AUTO_CALLBACK);
2723 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122724 GURL redirect_url(test_server_.GetURL("simple.html"));
2725 network_delegate.set_redirect_url(redirect_url);
2726
[email protected]d5a4dd62012-05-23 01:41:042727 TestURLRequestContextWithProxy context(
2728 test_server_.host_port_pair().ToString(),
2729 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502730
[email protected]4c76d7c2011-04-15 19:14:122731 {
[email protected]8f1ac082011-04-19 21:14:132732 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132733 URLRequest r(original_url, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122734
2735 r.Start();
[email protected]255620da2013-08-19 13:14:292736 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122737
2738 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052739 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122740 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132741 EXPECT_EQ(original_url, r.original_url());
2742 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122743 EXPECT_EQ(1, network_delegate.created_requests());
2744 EXPECT_EQ(0, network_delegate.destroyed_requests());
2745 }
2746 EXPECT_EQ(1, network_delegate.destroyed_requests());
2747}
2748
[email protected]b813ed72012-04-05 08:21:362749// Tests that the network delegate can block and redirect a request to a new
2750// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2751TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2752 ASSERT_TRUE(test_server_.Start());
2753
2754 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302755 BlockingNetworkDelegate network_delegate(
2756 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362757 GURL redirect_url(test_server_.GetURL("simple.html"));
2758 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362759
[email protected]d5a4dd62012-05-23 01:41:042760 TestURLRequestContextWithProxy context(
2761 test_server_.host_port_pair().ToString(),
2762 &network_delegate);
[email protected]b813ed72012-04-05 08:21:362763
2764 {
2765 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132766 URLRequest r(original_url, &d, &context);
[email protected]b813ed72012-04-05 08:21:362767
2768 r.Start();
[email protected]255620da2013-08-19 13:14:292769 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:362770
2771 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2772 EXPECT_EQ(0, r.status().error());
2773 EXPECT_EQ(redirect_url, r.url());
2774 EXPECT_EQ(original_url, r.original_url());
2775 EXPECT_EQ(2U, r.url_chain().size());
2776 EXPECT_EQ(1, network_delegate.created_requests());
2777 EXPECT_EQ(0, network_delegate.destroyed_requests());
2778 }
2779 EXPECT_EQ(1, network_delegate.destroyed_requests());
2780}
2781
[email protected]3c5ca8c2011-09-29 01:14:512782// Tests that redirects caused by the network delegate preserve POST data.
2783TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2784 ASSERT_TRUE(test_server_.Start());
2785
2786 const char kData[] = "hello world";
2787
2788 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302789 BlockingNetworkDelegate network_delegate(
2790 BlockingNetworkDelegate::AUTO_CALLBACK);
2791 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:512792 GURL redirect_url(test_server_.GetURL("echo"));
2793 network_delegate.set_redirect_url(redirect_url);
2794
[email protected]ef2bf422012-05-11 03:27:092795 TestURLRequestContext context(true);
2796 context.set_network_delegate(&network_delegate);
2797 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:512798
2799 {
2800 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132801 URLRequest r(original_url, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:512802 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:282803 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:512804 HttpRequestHeaders headers;
2805 headers.SetHeader(HttpRequestHeaders::kContentLength,
2806 base::UintToString(arraysize(kData) - 1));
2807 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:512808 r.Start();
[email protected]255620da2013-08-19 13:14:292809 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:512810
2811 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2812 EXPECT_EQ(0, r.status().error());
2813 EXPECT_EQ(redirect_url, r.url());
2814 EXPECT_EQ(original_url, r.original_url());
2815 EXPECT_EQ(2U, r.url_chain().size());
2816 EXPECT_EQ(1, network_delegate.created_requests());
2817 EXPECT_EQ(0, network_delegate.destroyed_requests());
2818 EXPECT_EQ("POST", r.method());
2819 EXPECT_EQ(kData, d.data_received());
2820 }
2821 EXPECT_EQ(1, network_delegate.destroyed_requests());
2822}
2823
[email protected]c2911d72011-10-03 22:16:362824// Tests that the network delegate can synchronously complete OnAuthRequired
2825// by taking no action. This indicates that the NetworkDelegate does not want to
2826// handle the challenge, and is passing the buck along to the
2827// URLRequest::Delegate.
2828TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
2829 ASSERT_TRUE(test_server_.Start());
2830
2831 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302832 BlockingNetworkDelegate network_delegate(
2833 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:362834
[email protected]ef2bf422012-05-11 03:27:092835 TestURLRequestContext context(true);
2836 context.set_network_delegate(&network_delegate);
2837 context.Init();
[email protected]c2911d72011-10-03 22:16:362838
[email protected]f3cf9802011-10-28 18:44:582839 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362840
2841 {
2842 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132843 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362844 r.Start();
[email protected]79e1fd62013-06-20 06:50:042845
[email protected]255620da2013-08-19 13:14:292846 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:042847
2848 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2849 EXPECT_EQ(0, r.status().error());
2850 EXPECT_EQ(200, r.GetResponseCode());
2851 EXPECT_TRUE(d.auth_required_called());
2852 EXPECT_EQ(1, network_delegate.created_requests());
2853 EXPECT_EQ(0, network_delegate.destroyed_requests());
2854 }
2855 EXPECT_EQ(1, network_delegate.destroyed_requests());
2856}
2857
2858TEST_F(URLRequestTestHTTP,
2859 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
2860 ASSERT_TRUE(test_server_.Start());
2861
2862 TestDelegate d;
2863 BlockingNetworkDelegate network_delegate(
2864 BlockingNetworkDelegate::SYNCHRONOUS);
2865
2866 TestURLRequestContext context(true);
2867 context.set_network_delegate(&network_delegate);
2868 context.Init();
2869
2870 d.set_credentials(AuthCredentials(kUser, kSecret));
2871
2872 {
2873 GURL url(test_server_.GetURL("auth-basic"));
2874 URLRequest r(url, &d, &context);
2875 r.Start();
2876
2877 {
2878 HttpRequestHeaders headers;
2879 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
2880 EXPECT_FALSE(headers.HasHeader("Authorization"));
2881 }
2882
[email protected]255620da2013-08-19 13:14:292883 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:362884
2885 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2886 EXPECT_EQ(0, r.status().error());
2887 EXPECT_EQ(200, r.GetResponseCode());
2888 EXPECT_TRUE(d.auth_required_called());
2889 EXPECT_EQ(1, network_delegate.created_requests());
2890 EXPECT_EQ(0, network_delegate.destroyed_requests());
2891 }
2892 EXPECT_EQ(1, network_delegate.destroyed_requests());
2893}
2894
2895// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:402896// by setting credentials.
[email protected]c2911d72011-10-03 22:16:362897TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
2898 ASSERT_TRUE(test_server_.Start());
2899
2900 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302901 BlockingNetworkDelegate network_delegate(
2902 BlockingNetworkDelegate::SYNCHRONOUS);
2903 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362904 network_delegate.set_auth_retval(
2905 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2906
[email protected]f3cf9802011-10-28 18:44:582907 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362908
[email protected]ef2bf422012-05-11 03:27:092909 TestURLRequestContext context(true);
2910 context.set_network_delegate(&network_delegate);
2911 context.Init();
[email protected]c2911d72011-10-03 22:16:362912
2913 {
2914 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132915 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362916 r.Start();
[email protected]255620da2013-08-19 13:14:292917 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:362918
2919 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2920 EXPECT_EQ(0, r.status().error());
2921 EXPECT_EQ(200, r.GetResponseCode());
2922 EXPECT_FALSE(d.auth_required_called());
2923 EXPECT_EQ(1, network_delegate.created_requests());
2924 EXPECT_EQ(0, network_delegate.destroyed_requests());
2925 }
2926 EXPECT_EQ(1, network_delegate.destroyed_requests());
2927}
2928
[email protected]79e1fd62013-06-20 06:50:042929// Same as above, but also tests that GetFullRequestHeaders returns the proper
2930// headers (for the first or second request) when called at the proper times.
2931TEST_F(URLRequestTestHTTP,
2932 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
2933 ASSERT_TRUE(test_server_.Start());
2934
2935 TestDelegate d;
2936 BlockingNetworkDelegate network_delegate(
2937 BlockingNetworkDelegate::SYNCHRONOUS);
2938 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
2939 network_delegate.set_auth_retval(
2940 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2941
2942 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
2943
2944 TestURLRequestContext context(true);
2945 context.set_network_delegate(&network_delegate);
2946 context.Init();
2947
2948 {
2949 GURL url(test_server_.GetURL("auth-basic"));
2950 URLRequest r(url, &d, &context);
2951 r.Start();
[email protected]255620da2013-08-19 13:14:292952 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:042953
2954 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2955 EXPECT_EQ(0, r.status().error());
2956 EXPECT_EQ(200, r.GetResponseCode());
2957 EXPECT_FALSE(d.auth_required_called());
2958 EXPECT_EQ(1, network_delegate.created_requests());
2959 EXPECT_EQ(0, network_delegate.destroyed_requests());
2960
2961 {
2962 HttpRequestHeaders headers;
2963 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
2964 EXPECT_TRUE(headers.HasHeader("Authorization"));
2965 }
2966 }
2967 EXPECT_EQ(1, network_delegate.destroyed_requests());
2968}
2969
[email protected]c2911d72011-10-03 22:16:362970// Tests that the network delegate can synchronously complete OnAuthRequired
2971// by cancelling authentication.
2972TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
2973 ASSERT_TRUE(test_server_.Start());
2974
2975 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302976 BlockingNetworkDelegate network_delegate(
2977 BlockingNetworkDelegate::SYNCHRONOUS);
2978 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362979 network_delegate.set_auth_retval(
2980 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
2981
[email protected]ef2bf422012-05-11 03:27:092982 TestURLRequestContext context(true);
2983 context.set_network_delegate(&network_delegate);
2984 context.Init();
[email protected]c2911d72011-10-03 22:16:362985
2986 {
2987 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132988 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362989 r.Start();
[email protected]255620da2013-08-19 13:14:292990 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:362991
2992 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2993 EXPECT_EQ(OK, r.status().error());
2994 EXPECT_EQ(401, r.GetResponseCode());
2995 EXPECT_FALSE(d.auth_required_called());
2996 EXPECT_EQ(1, network_delegate.created_requests());
2997 EXPECT_EQ(0, network_delegate.destroyed_requests());
2998 }
2999 EXPECT_EQ(1, network_delegate.destroyed_requests());
3000}
3001
3002// Tests that the network delegate can asynchronously complete OnAuthRequired
3003// by taking no action. This indicates that the NetworkDelegate does not want
3004// to handle the challenge, and is passing the buck along to the
3005// URLRequest::Delegate.
3006TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3007 ASSERT_TRUE(test_server_.Start());
3008
3009 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303010 BlockingNetworkDelegate network_delegate(
3011 BlockingNetworkDelegate::AUTO_CALLBACK);
3012 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363013
[email protected]ef2bf422012-05-11 03:27:093014 TestURLRequestContext context(true);
3015 context.set_network_delegate(&network_delegate);
3016 context.Init();
[email protected]c2911d72011-10-03 22:16:363017
[email protected]f3cf9802011-10-28 18:44:583018 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363019
3020 {
3021 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133022 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363023 r.Start();
[email protected]255620da2013-08-19 13:14:293024 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363025
3026 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3027 EXPECT_EQ(0, r.status().error());
3028 EXPECT_EQ(200, r.GetResponseCode());
3029 EXPECT_TRUE(d.auth_required_called());
3030 EXPECT_EQ(1, network_delegate.created_requests());
3031 EXPECT_EQ(0, network_delegate.destroyed_requests());
3032 }
3033 EXPECT_EQ(1, network_delegate.destroyed_requests());
3034}
3035
3036// Tests that the network delegate can asynchronously complete OnAuthRequired
3037// by setting credentials.
3038TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3039 ASSERT_TRUE(test_server_.Start());
3040
3041 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303042 BlockingNetworkDelegate network_delegate(
3043 BlockingNetworkDelegate::AUTO_CALLBACK);
3044 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363045 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363046 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3047
[email protected]f3cf9802011-10-28 18:44:583048 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363049 network_delegate.set_auth_credentials(auth_credentials);
3050
[email protected]ef2bf422012-05-11 03:27:093051 TestURLRequestContext context(true);
3052 context.set_network_delegate(&network_delegate);
3053 context.Init();
[email protected]c2911d72011-10-03 22:16:363054
3055 {
3056 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133057 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363058 r.Start();
[email protected]255620da2013-08-19 13:14:293059 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363060
3061 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3062 EXPECT_EQ(0, r.status().error());
3063
3064 EXPECT_EQ(200, r.GetResponseCode());
3065 EXPECT_FALSE(d.auth_required_called());
3066 EXPECT_EQ(1, network_delegate.created_requests());
3067 EXPECT_EQ(0, network_delegate.destroyed_requests());
3068 }
3069 EXPECT_EQ(1, network_delegate.destroyed_requests());
3070}
3071
3072// Tests that the network delegate can asynchronously complete OnAuthRequired
3073// by cancelling authentication.
3074TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3075 ASSERT_TRUE(test_server_.Start());
3076
3077 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303078 BlockingNetworkDelegate network_delegate(
3079 BlockingNetworkDelegate::AUTO_CALLBACK);
3080 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363081 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363082 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3083
[email protected]ef2bf422012-05-11 03:27:093084 TestURLRequestContext context(true);
3085 context.set_network_delegate(&network_delegate);
3086 context.Init();
[email protected]c2911d72011-10-03 22:16:363087
3088 {
3089 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133090 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363091 r.Start();
[email protected]255620da2013-08-19 13:14:293092 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363093
3094 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3095 EXPECT_EQ(OK, r.status().error());
3096 EXPECT_EQ(401, r.GetResponseCode());
3097 EXPECT_FALSE(d.auth_required_called());
3098 EXPECT_EQ(1, network_delegate.created_requests());
3099 EXPECT_EQ(0, network_delegate.destroyed_requests());
3100 }
3101 EXPECT_EQ(1, network_delegate.destroyed_requests());
3102}
3103
[email protected]9045b8822012-01-13 20:35:353104// Tests that we can handle when a network request was canceled while we were
3105// waiting for the network delegate.
3106// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3107TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3108 ASSERT_TRUE(test_server_.Start());
3109
3110 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303111 BlockingNetworkDelegate network_delegate(
3112 BlockingNetworkDelegate::USER_CALLBACK);
3113 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353114
[email protected]ef2bf422012-05-11 03:27:093115 TestURLRequestContext context(true);
3116 context.set_network_delegate(&network_delegate);
3117 context.Init();
[email protected]9045b8822012-01-13 20:35:353118
3119 {
[email protected]007b3f82013-04-09 08:46:453120 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353121
3122 r.Start();
[email protected]255620da2013-08-19 13:14:293123 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303124 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3125 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353126 EXPECT_EQ(0, network_delegate.completed_requests());
3127 // Cancel before callback.
3128 r.Cancel();
3129 // Ensure that network delegate is notified.
3130 EXPECT_EQ(1, network_delegate.completed_requests());
3131 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3132 EXPECT_EQ(ERR_ABORTED, r.status().error());
3133 EXPECT_EQ(1, network_delegate.created_requests());
3134 EXPECT_EQ(0, network_delegate.destroyed_requests());
3135 }
3136 EXPECT_EQ(1, network_delegate.destroyed_requests());
3137}
3138
3139// Tests that we can handle when a network request was canceled while we were
3140// waiting for the network delegate.
3141// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3142TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3143 ASSERT_TRUE(test_server_.Start());
3144
3145 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303146 BlockingNetworkDelegate network_delegate(
3147 BlockingNetworkDelegate::USER_CALLBACK);
3148 network_delegate.set_block_on(
3149 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353150
[email protected]ef2bf422012-05-11 03:27:093151 TestURLRequestContext context(true);
3152 context.set_network_delegate(&network_delegate);
3153 context.Init();
[email protected]9045b8822012-01-13 20:35:353154
3155 {
[email protected]007b3f82013-04-09 08:46:453156 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353157
3158 r.Start();
[email protected]255620da2013-08-19 13:14:293159 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303160 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3161 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353162 EXPECT_EQ(0, network_delegate.completed_requests());
3163 // Cancel before callback.
3164 r.Cancel();
3165 // Ensure that network delegate is notified.
3166 EXPECT_EQ(1, network_delegate.completed_requests());
3167 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3168 EXPECT_EQ(ERR_ABORTED, r.status().error());
3169 EXPECT_EQ(1, network_delegate.created_requests());
3170 EXPECT_EQ(0, network_delegate.destroyed_requests());
3171 }
3172 EXPECT_EQ(1, network_delegate.destroyed_requests());
3173}
3174
3175// Tests that we can handle when a network request was canceled while we were
3176// waiting for the network delegate.
3177// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3178TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3179 ASSERT_TRUE(test_server_.Start());
3180
3181 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303182 BlockingNetworkDelegate network_delegate(
3183 BlockingNetworkDelegate::USER_CALLBACK);
3184 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353185
[email protected]ef2bf422012-05-11 03:27:093186 TestURLRequestContext context(true);
3187 context.set_network_delegate(&network_delegate);
3188 context.Init();
[email protected]9045b8822012-01-13 20:35:353189
3190 {
[email protected]007b3f82013-04-09 08:46:453191 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353192
3193 r.Start();
[email protected]255620da2013-08-19 13:14:293194 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303195 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3196 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353197 EXPECT_EQ(0, network_delegate.completed_requests());
3198 // Cancel before callback.
3199 r.Cancel();
3200 // Ensure that network delegate is notified.
3201 EXPECT_EQ(1, network_delegate.completed_requests());
3202 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3203 EXPECT_EQ(ERR_ABORTED, r.status().error());
3204 EXPECT_EQ(1, network_delegate.created_requests());
3205 EXPECT_EQ(0, network_delegate.destroyed_requests());
3206 }
3207 EXPECT_EQ(1, network_delegate.destroyed_requests());
3208}
3209
3210// Tests that we can handle when a network request was canceled while we were
3211// waiting for the network delegate.
3212// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023213TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353214 ASSERT_TRUE(test_server_.Start());
3215
3216 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303217 BlockingNetworkDelegate network_delegate(
3218 BlockingNetworkDelegate::USER_CALLBACK);
3219 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353220
[email protected]ef2bf422012-05-11 03:27:093221 TestURLRequestContext context(true);
3222 context.set_network_delegate(&network_delegate);
3223 context.Init();
[email protected]9045b8822012-01-13 20:35:353224
3225 {
[email protected]94e2bbe2012-06-22 15:26:133226 URLRequest r(test_server_.GetURL("auth-basic"), &d, &context);
[email protected]9045b8822012-01-13 20:35:353227
3228 r.Start();
[email protected]255620da2013-08-19 13:14:293229 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303230 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3231 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353232 EXPECT_EQ(0, network_delegate.completed_requests());
3233 // Cancel before callback.
3234 r.Cancel();
3235 // Ensure that network delegate is notified.
3236 EXPECT_EQ(1, network_delegate.completed_requests());
3237 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3238 EXPECT_EQ(ERR_ABORTED, r.status().error());
3239 EXPECT_EQ(1, network_delegate.created_requests());
3240 EXPECT_EQ(0, network_delegate.destroyed_requests());
3241 }
3242 EXPECT_EQ(1, network_delegate.destroyed_requests());
3243}
3244
[email protected]95409e12010-08-17 20:07:113245// In this unit test, we're using the HTTPTestServer as a proxy server and
3246// issuing a CONNECT request with the magic host name "www.server-auth.com".
3247// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353248TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113249 ASSERT_TRUE(test_server_.Start());
3250
[email protected]ceefd7fd2012-11-29 00:36:243251 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043252 TestURLRequestContextWithProxy context(
3253 test_server_.host_port_pair().ToString(),
3254 &network_delegate);
[email protected]87a09a92011-07-14 15:50:503255
[email protected]dc651782009-02-14 01:45:083256 TestDelegate d;
3257 {
[email protected]94e2bbe2012-06-22 15:26:133258 URLRequest r(GURL("https://www.server-auth.com/"), &d, &context);
[email protected]dc651782009-02-14 01:45:083259
3260 r.Start();
3261 EXPECT_TRUE(r.is_pending());
3262
[email protected]255620da2013-08-19 13:14:293263 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083264
[email protected]7461a402011-03-24 23:19:513265 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:053266 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:083267 }
3268}
3269
[email protected]b89290212009-08-14 22:37:353270TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113271 ASSERT_TRUE(test_server_.Start());
3272
initial.commit586acc5fe2008-07-26 22:42:523273 TestDelegate d;
3274 {
[email protected]007b3f82013-04-09 08:46:453275 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523276
3277 r.Start();
3278 EXPECT_TRUE(r.is_pending());
3279
[email protected]255620da2013-08-19 13:14:293280 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523281
3282 EXPECT_EQ(1, d.response_started_count());
3283 EXPECT_FALSE(d.received_data_before_response());
3284 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193285 EXPECT_EQ(test_server_.host_port_pair().host(),
3286 r.GetSocketAddress().host());
3287 EXPECT_EQ(test_server_.host_port_pair().port(),
3288 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163289
[email protected]9e743cd2010-03-16 07:03:533290 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523291 }
initial.commit586acc5fe2008-07-26 22:42:523292}
3293
[email protected]263163f2012-06-14 22:40:343294// This test has the server send a large number of cookies to the client.
3295// To ensure that no number of cookies causes a crash, a galloping binary
3296// search is used to estimate that maximum number of cookies that are accepted
3297// by the browser. Beyond the maximum number, the request will fail with
3298// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303299#if defined(OS_WIN)
3300// http://crbug.com/177916
3301#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3302#else
3303#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3304#endif // defined(OS_WIN)
3305TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343306 ASSERT_TRUE(test_server_.Start());
3307
3308 int lower_bound = 0;
3309 int upper_bound = 1;
3310
3311 // Double the number of cookies until the response header limits are
3312 // exceeded.
3313 while (DoManyCookiesRequest(upper_bound)) {
3314 lower_bound = upper_bound;
3315 upper_bound *= 2;
3316 ASSERT_LT(upper_bound, 1000000);
3317 }
3318
3319 int tolerance = upper_bound * 0.005;
3320 if (tolerance < 2)
3321 tolerance = 2;
3322
3323 // Perform a binary search to find the highest possible number of cookies,
3324 // within the desired tolerance.
3325 while (upper_bound - lower_bound >= tolerance) {
3326 int num_cookies = (lower_bound + upper_bound) / 2;
3327
3328 if (DoManyCookiesRequest(num_cookies))
3329 lower_bound = num_cookies;
3330 else
3331 upper_bound = num_cookies;
3332 }
3333 // Success: the test did not crash.
3334}
3335
[email protected]b89290212009-08-14 22:37:353336TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113337 ASSERT_TRUE(test_server_.Start());
3338
initial.commit586acc5fe2008-07-26 22:42:523339 TestDelegate d;
3340 {
[email protected]1e110eae2013-05-10 22:02:403341 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523342
3343 r.Start();
3344 EXPECT_TRUE(r.is_pending());
3345
[email protected]255620da2013-08-19 13:14:293346 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523347
3348 EXPECT_EQ(1, d.response_started_count());
3349 EXPECT_FALSE(d.received_data_before_response());
3350 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193351 EXPECT_EQ(test_server_.host_port_pair().host(),
3352 r.GetSocketAddress().host());
3353 EXPECT_EQ(test_server_.host_port_pair().port(),
3354 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523355 }
[email protected]5d7b373e2009-09-02 07:19:033356}
3357
[email protected]79e1fd62013-06-20 06:50:043358TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3359 ASSERT_TRUE(test_server_.Start());
3360
3361 TestDelegate d;
3362 {
3363 GURL test_url(test_server_.GetURL(std::string()));
3364 URLRequest r(test_url, &d, &default_context_);
3365
3366 HttpRequestHeaders headers;
3367 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3368
3369 r.Start();
3370 EXPECT_TRUE(r.is_pending());
3371
[email protected]255620da2013-08-19 13:14:293372 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043373
3374 EXPECT_EQ(1, d.response_started_count());
3375 EXPECT_FALSE(d.received_data_before_response());
3376 EXPECT_NE(0, d.bytes_received());
3377 EXPECT_EQ(test_server_.host_port_pair().host(),
3378 r.GetSocketAddress().host());
3379 EXPECT_EQ(test_server_.host_port_pair().port(),
3380 r.GetSocketAddress().port());
3381
3382 EXPECT_TRUE(d.have_full_request_headers());
3383 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3384 }
3385}
3386
[email protected]58e32bb2013-01-21 18:23:253387TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3388 ASSERT_TRUE(test_server_.Start());
3389
3390 TestDelegate d;
3391 {
[email protected]007b3f82013-04-09 08:46:453392 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]58e32bb2013-01-21 18:23:253393
3394 r.Start();
3395 EXPECT_TRUE(r.is_pending());
3396
[email protected]255620da2013-08-19 13:14:293397 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253398
3399 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173400 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253401 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3402
3403 EXPECT_EQ(1, d.response_started_count());
3404 EXPECT_FALSE(d.received_data_before_response());
3405 EXPECT_NE(0, d.bytes_received());
3406 EXPECT_EQ(test_server_.host_port_pair().host(),
3407 r.GetSocketAddress().host());
3408 EXPECT_EQ(test_server_.host_port_pair().port(),
3409 r.GetSocketAddress().port());
3410 }
3411}
3412
[email protected]aad63572011-05-24 20:14:393413TEST_F(URLRequestTestHTTP, GetZippedTest) {
3414 ASSERT_TRUE(test_server_.Start());
3415
3416 // Parameter that specifies the Content-Length field in the response:
3417 // C - Compressed length.
3418 // U - Uncompressed length.
3419 // L - Large length (larger than both C & U).
3420 // M - Medium length (between C & U).
3421 // S - Small length (smaller than both C & U).
3422 const char test_parameters[] = "CULMS";
3423 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3424 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443425 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393426 // S has too little data, but we seem to accept it.
3427 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373428 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393429
3430 for (int i = 0; i < num_tests ; i++) {
3431 TestDelegate d;
3432 {
3433 std::string test_file =
3434 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3435 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393436
[email protected]ceefd7fd2012-11-29 00:36:243437 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093438 TestURLRequestContext context(true);
3439 context.set_network_delegate(&network_delegate);
3440 context.Init();
[email protected]87a09a92011-07-14 15:50:503441
[email protected]94e2bbe2012-06-22 15:26:133442 URLRequest r(test_server_.GetURL(test_file), &d, &context);
[email protected]aad63572011-05-24 20:14:393443 r.Start();
3444 EXPECT_TRUE(r.is_pending());
3445
[email protected]255620da2013-08-19 13:14:293446 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393447
3448 EXPECT_EQ(1, d.response_started_count());
3449 EXPECT_FALSE(d.received_data_before_response());
3450 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3451 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:053452 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:393453 if (test_expect_success[i]) {
3454 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3455 << " Parameter = \"" << test_file << "\"";
3456 } else {
3457 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:233458 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:393459 << " Parameter = \"" << test_file << "\"";
3460 }
3461 }
3462 }
3463}
3464
[email protected]c044616e2013-02-20 02:01:263465TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:113466 ASSERT_TRUE(test_server_.Start());
3467
[email protected]ce7d0cbc2013-05-03 18:57:223468 SpawnedTestServer https_test_server(
3469 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:153470 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:113471 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:583472
3473 // An https server is sent a request with an https referer,
3474 // and responds with a redirect to an http url. The http
3475 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:453476 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:583477 TestDelegate d;
[email protected]ef2bf422012-05-11 03:27:093478 URLRequest req(https_test_server.GetURL(
[email protected]94e2bbe2012-06-22 15:26:133479 "server-redirect?" + http_destination.spec()), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:133480 req.SetReferrer("https://www.referrer.com/");
[email protected]7844480a2009-12-16 21:18:583481 req.Start();
[email protected]255620da2013-08-19 13:14:293482 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:583483
3484 EXPECT_EQ(1, d.response_started_count());
3485 EXPECT_EQ(1, d.received_redirect_count());
3486 EXPECT_EQ(http_destination, req.url());
3487 EXPECT_EQ(std::string(), req.referrer());
3488}
3489
[email protected]58e32bb2013-01-21 18:23:253490TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3491 ASSERT_TRUE(test_server_.Start());
3492
[email protected]007b3f82013-04-09 08:46:453493 GURL destination_url = test_server_.GetURL(std::string());
3494 GURL original_url =
3495 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253496 TestDelegate d;
3497 URLRequest req(original_url, &d, &default_context_);
3498 req.Start();
[email protected]255620da2013-08-19 13:14:293499 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253500
3501 EXPECT_EQ(1, d.response_started_count());
3502 EXPECT_EQ(1, d.received_redirect_count());
3503 EXPECT_EQ(destination_url, req.url());
3504 EXPECT_EQ(original_url, req.original_url());
3505 ASSERT_EQ(2U, req.url_chain().size());
3506 EXPECT_EQ(original_url, req.url_chain()[0]);
3507 EXPECT_EQ(destination_url, req.url_chain()[1]);
3508
3509 LoadTimingInfo load_timing_info_before_redirect;
3510 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3511 &load_timing_info_before_redirect));
3512 TestLoadTimingNotReused(load_timing_info_before_redirect,
3513 CONNECT_TIMING_HAS_DNS_TIMES);
3514
3515 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173516 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253517 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3518
3519 // Check that a new socket was used on redirect, since the server does not
3520 // supposed keep-alive sockets, and that the times before the redirect are
3521 // before the ones recorded for the second request.
3522 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3523 load_timing_info.socket_log_id);
3524 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3525 load_timing_info.connect_timing.connect_start);
3526}
3527
[email protected]8f1ac082011-04-19 21:14:133528TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3529 ASSERT_TRUE(test_server_.Start());
3530
[email protected]007b3f82013-04-09 08:46:453531 GURL destination_url = test_server_.GetURL(std::string());
3532 GURL middle_redirect_url =
3533 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133534 GURL original_url = test_server_.GetURL(
3535 "server-redirect?" + middle_redirect_url.spec());
3536 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:133537 URLRequest req(original_url, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133538 req.Start();
[email protected]255620da2013-08-19 13:14:293539 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133540
3541 EXPECT_EQ(1, d.response_started_count());
3542 EXPECT_EQ(2, d.received_redirect_count());
3543 EXPECT_EQ(destination_url, req.url());
3544 EXPECT_EQ(original_url, req.original_url());
3545 ASSERT_EQ(3U, req.url_chain().size());
3546 EXPECT_EQ(original_url, req.url_chain()[0]);
3547 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3548 EXPECT_EQ(destination_url, req.url_chain()[2]);
3549}
3550
[email protected]847c0fa92012-11-06 16:37:423551namespace {
3552
3553const char kExtraHeader[] = "Allow-Snafu";
3554const char kExtraValue[] = "fubar";
3555
3556class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:163557 virtual void OnReceivedRedirect(net::URLRequest* request,
3558 const GURL& new_url,
3559 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:423560 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
3561 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
3562 }
3563};
3564
3565} // namespace
3566
3567TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
3568 ASSERT_TRUE(test_server_.Start());
3569
3570 GURL destination_url = test_server_.GetURL(
3571 "echoheader?" + std::string(kExtraHeader));
3572 GURL original_url = test_server_.GetURL(
3573 "server-redirect?" + destination_url.spec());
3574 RedirectWithAdditionalHeadersDelegate d;
3575 URLRequest req(original_url, &d, &default_context_);
3576 req.Start();
[email protected]255620da2013-08-19 13:14:293577 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:423578
3579 std::string value;
3580 const HttpRequestHeaders& headers = req.extra_request_headers();
3581 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
3582 EXPECT_EQ(kExtraValue, value);
3583 EXPECT_FALSE(req.is_pending());
3584 EXPECT_FALSE(req.is_redirecting());
3585 EXPECT_EQ(kExtraValue, d.data_received());
3586}
3587
[email protected]251a1b92012-11-13 11:01:093588namespace {
3589
3590const char kExtraHeaderToRemove[] = "To-Be-Removed";
3591
3592class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:163593 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:093594 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:163595 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:093596 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
3597 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
3598 }
3599};
3600
3601} // namespace
3602
3603TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
3604 ASSERT_TRUE(test_server_.Start());
3605
3606 GURL destination_url = test_server_.GetURL(
3607 "echoheader?" + std::string(kExtraHeaderToRemove));
3608 GURL original_url = test_server_.GetURL(
3609 "server-redirect?" + destination_url.spec());
3610 RedirectWithHeaderRemovalDelegate d;
3611 URLRequest req(original_url, &d, &default_context_);
3612 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
3613 req.Start();
[email protected]255620da2013-08-19 13:14:293614 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:093615
3616 std::string value;
3617 const HttpRequestHeaders& headers = req.extra_request_headers();
3618 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
3619 EXPECT_FALSE(req.is_pending());
3620 EXPECT_FALSE(req.is_redirecting());
3621 EXPECT_EQ("None", d.data_received());
3622}
3623
[email protected]316c1e5e2012-09-12 15:17:443624TEST_F(URLRequestTestHTTP, CancelTest) {
3625 TestDelegate d;
3626 {
3627 URLRequest r(GURL("http://www.google.com/"), &d, &default_context_);
3628
3629 r.Start();
3630 EXPECT_TRUE(r.is_pending());
3631
3632 r.Cancel();
3633
[email protected]255620da2013-08-19 13:14:293634 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443635
3636 // We expect to receive OnResponseStarted even though the request has been
3637 // cancelled.
3638 EXPECT_EQ(1, d.response_started_count());
3639 EXPECT_EQ(0, d.bytes_received());
3640 EXPECT_FALSE(d.received_data_before_response());
3641 }
3642}
3643
3644TEST_F(URLRequestTestHTTP, CancelTest2) {
3645 ASSERT_TRUE(test_server_.Start());
3646
3647 TestDelegate d;
3648 {
[email protected]007b3f82013-04-09 08:46:453649 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:443650
3651 d.set_cancel_in_response_started(true);
3652
3653 r.Start();
3654 EXPECT_TRUE(r.is_pending());
3655
[email protected]255620da2013-08-19 13:14:293656 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443657
3658 EXPECT_EQ(1, d.response_started_count());
3659 EXPECT_EQ(0, d.bytes_received());
3660 EXPECT_FALSE(d.received_data_before_response());
3661 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3662 }
3663}
3664
3665TEST_F(URLRequestTestHTTP, CancelTest3) {
3666 ASSERT_TRUE(test_server_.Start());
3667
3668 TestDelegate d;
3669 {
[email protected]007b3f82013-04-09 08:46:453670 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:443671
3672 d.set_cancel_in_received_data(true);
3673
3674 r.Start();
3675 EXPECT_TRUE(r.is_pending());
3676
[email protected]255620da2013-08-19 13:14:293677 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443678
3679 EXPECT_EQ(1, d.response_started_count());
3680 // There is no guarantee about how much data was received
3681 // before the cancel was issued. It could have been 0 bytes,
3682 // or it could have been all the bytes.
3683 // EXPECT_EQ(0, d.bytes_received());
3684 EXPECT_FALSE(d.received_data_before_response());
3685 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3686 }
3687}
3688
3689TEST_F(URLRequestTestHTTP, CancelTest4) {
3690 ASSERT_TRUE(test_server_.Start());
3691
3692 TestDelegate d;
3693 {
[email protected]007b3f82013-04-09 08:46:453694 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:443695
3696 r.Start();
3697 EXPECT_TRUE(r.is_pending());
3698
3699 // The request will be implicitly canceled when it is destroyed. The
3700 // test delegate must not post a quit message when this happens because
3701 // this test doesn't actually have a message loop. The quit message would
3702 // get put on this thread's message queue and the next test would exit
3703 // early, causing problems.
3704 d.set_quit_on_complete(false);
3705 }
3706 // expect things to just cleanup properly.
3707
3708 // we won't actually get a received reponse here because we've never run the
3709 // message loop
3710 EXPECT_FALSE(d.received_data_before_response());
3711 EXPECT_EQ(0, d.bytes_received());
3712}
3713
3714TEST_F(URLRequestTestHTTP, CancelTest5) {
3715 ASSERT_TRUE(test_server_.Start());
3716
3717 // populate cache
3718 {
3719 TestDelegate d;
3720 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
3721 r.Start();
[email protected]255620da2013-08-19 13:14:293722 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443723 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3724 }
3725
3726 // cancel read from cache (see bug 990242)
3727 {
3728 TestDelegate d;
3729 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
3730 r.Start();
3731 r.Cancel();
[email protected]255620da2013-08-19 13:14:293732 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443733
3734 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3735 EXPECT_EQ(1, d.response_started_count());
3736 EXPECT_EQ(0, d.bytes_received());
3737 EXPECT_FALSE(d.received_data_before_response());
3738 }
3739}
3740
3741TEST_F(URLRequestTestHTTP, PostTest) {
3742 ASSERT_TRUE(test_server_.Start());
3743 HTTPUploadDataOperationTest("POST");
3744}
3745
3746TEST_F(URLRequestTestHTTP, PutTest) {
3747 ASSERT_TRUE(test_server_.Start());
3748 HTTPUploadDataOperationTest("PUT");
3749}
3750
3751TEST_F(URLRequestTestHTTP, PostEmptyTest) {
3752 ASSERT_TRUE(test_server_.Start());
3753
3754 TestDelegate d;
3755 {
3756 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3757 r.set_method("POST");
3758
3759 r.Start();
3760 EXPECT_TRUE(r.is_pending());
3761
[email protected]255620da2013-08-19 13:14:293762 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443763
[email protected]329b68b2012-11-14 17:54:273764 ASSERT_EQ(1, d.response_started_count())
3765 << "request failed: " << r.status().status()
3766 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:443767
3768 EXPECT_FALSE(d.received_data_before_response());
3769 EXPECT_TRUE(d.data_received().empty());
3770 }
3771}
3772
3773TEST_F(URLRequestTestHTTP, PostFileTest) {
3774 ASSERT_TRUE(test_server_.Start());
3775
3776 TestDelegate d;
3777 {
3778 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3779 r.set_method("POST");
3780
[email protected]6cdfd7f2013-02-08 20:40:153781 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:443782 PathService::Get(base::DIR_EXE, &dir);
3783 file_util::SetCurrentDirectory(dir);
3784
[email protected]f288ef02012-12-15 20:28:283785 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:443786
[email protected]6cdfd7f2013-02-08 20:40:153787 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:443788 PathService::Get(base::DIR_SOURCE_ROOT, &path);
3789 path = path.Append(FILE_PATH_LITERAL("net"));
3790 path = path.Append(FILE_PATH_LITERAL("data"));
3791 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
3792 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:363793 element_readers.push_back(
3794 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
3795 path,
3796 0,
3797 kuint64max,
3798 base::Time()));
[email protected]316c1e5e2012-09-12 15:17:443799
3800 // This file should just be ignored in the upload stream.
[email protected]f288ef02012-12-15 20:28:283801 element_readers.push_back(new UploadFileElementReader(
[email protected]cadac622013-06-11 16:46:363802 base::MessageLoopProxy::current().get(),
[email protected]6cdfd7f2013-02-08 20:40:153803 base::FilePath(FILE_PATH_LITERAL(
[email protected]316c1e5e2012-09-12 15:17:443804 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
[email protected]cadac622013-06-11 16:46:363805 0,
3806 kuint64max,
3807 base::Time()));
[email protected]96c77a72013-09-24 09:49:203808 r.set_upload(make_scoped_ptr(
3809 new UploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:443810
3811 r.Start();
3812 EXPECT_TRUE(r.is_pending());
3813
[email protected]255620da2013-08-19 13:14:293814 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443815
[email protected]329b68b2012-11-14 17:54:273816 int64 size = 0;
3817 ASSERT_EQ(true, file_util::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:173818 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:443819
[email protected]329b68b2012-11-14 17:54:273820 ASSERT_EQ(size, file_util::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:443821
[email protected]329b68b2012-11-14 17:54:273822 ASSERT_EQ(1, d.response_started_count())
3823 << "request failed: " << r.status().status()
3824 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:443825
3826 EXPECT_FALSE(d.received_data_before_response());
3827
[email protected]329b68b2012-11-14 17:54:273828 EXPECT_EQ(size, d.bytes_received());
3829 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:443830 }
3831}
3832
3833TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
3834 ASSERT_TRUE(test_server_.Start());
3835
3836 TestDelegate d;
3837 {
3838 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3839 r.EnableChunkedUpload();
3840 r.set_method("POST");
3841 AddChunksToUpload(&r);
3842 r.Start();
3843 EXPECT_TRUE(r.is_pending());
3844
[email protected]255620da2013-08-19 13:14:293845 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443846
3847 VerifyReceivedDataMatchesChunks(&r, &d);
3848 }
3849}
3850
[email protected]329b68b2012-11-14 17:54:273851TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
3852 ASSERT_TRUE(test_server_.Start());
3853
3854 TestDelegate d;
3855 {
3856 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3857 r.EnableChunkedUpload();
3858 r.set_method("POST");
3859 r.Start();
3860 EXPECT_TRUE(r.is_pending());
3861 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:293862 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:273863
3864 VerifyReceivedDataMatchesChunks(&r, &d);
3865 }
3866}
3867
[email protected]316c1e5e2012-09-12 15:17:443868TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
3869 ASSERT_TRUE(test_server_.Start());
3870
3871 TestDelegate d;
3872 {
3873 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
3874 r.EnableChunkedUpload();
3875 r.set_method("POST");
3876 r.Start();
3877 EXPECT_TRUE(r.is_pending());
3878
[email protected]255620da2013-08-19 13:14:293879 base::RunLoop().RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:443880 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:293881 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443882
3883 VerifyReceivedDataMatchesChunks(&r, &d);
3884 }
3885}
3886
3887TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
3888 ASSERT_TRUE(test_server_.Start());
3889
3890 TestDelegate d;
3891 URLRequest req(
3892 test_server_.GetURL("files/with-headers.html"), &d, &default_context_);
3893 req.Start();
[email protected]255620da2013-08-19 13:14:293894 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:443895
3896 const HttpResponseHeaders* headers = req.response_headers();
3897
3898 // Simple sanity check that response_info() accesses the same data.
3899 EXPECT_EQ(headers, req.response_info().headers.get());
3900
3901 std::string header;
3902 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
3903 EXPECT_EQ("private", header);
3904
3905 header.clear();
3906 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
3907 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
3908
3909 // The response has two "X-Multiple-Entries" headers.
3910 // This verfies our output has them concatenated together.
3911 header.clear();
3912 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
3913 EXPECT_EQ("a, b", header);
3914}
3915
[email protected]242d8562012-10-30 21:20:463916TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:223917 SpawnedTestServer::SSLOptions ssl_options;
3918 SpawnedTestServer https_test_server(
3919 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:463920 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:153921 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:463922 ASSERT_TRUE(https_test_server.Start());
3923
3924 TestDelegate d;
3925 URLRequest request(
3926 https_test_server.GetURL("files/hsts-headers.html"),
3927 &d,
3928 &default_context_);
3929 request.Start();
[email protected]255620da2013-08-19 13:14:293930 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:463931
3932 TransportSecurityState* security_state =
3933 default_context_.transport_security_state();
3934 bool sni_available = true;
3935 TransportSecurityState::DomainState domain_state;
3936 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:033937 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:463938 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
3939 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:053940 EXPECT_TRUE(domain_state.sts_include_subdomains);
[email protected]22e045f2013-09-20 03:54:033941 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:273942#if defined(OS_ANDROID)
3943 // Android's CertVerifyProc does not (yet) handle pins.
3944#else
3945 EXPECT_FALSE(domain_state.HasPublicKeyPins());
3946#endif
3947}
3948
3949// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
3950// reject HPKP headers, and a test setting only HPKP headers will fail (no
3951// DomainState present because header rejected).
3952#if defined(OS_ANDROID)
3953#define MAYBE_ProcessPKP DISABLED_ProcessPKP
3954#else
3955#define MAYBE_ProcessPKP ProcessPKP
3956#endif
3957
3958// Tests that enabling HPKP on a domain does not affect the HSTS
3959// validity/expiration.
3960TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
3961 SpawnedTestServer::SSLOptions ssl_options;
3962 SpawnedTestServer https_test_server(
3963 SpawnedTestServer::TYPE_HTTPS,
3964 ssl_options,
3965 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
3966 ASSERT_TRUE(https_test_server.Start());
3967
3968 TestDelegate d;
3969 URLRequest request(
3970 https_test_server.GetURL("files/hpkp-headers.html"),
3971 &d,
3972 &default_context_);
3973 request.Start();
[email protected]255620da2013-08-19 13:14:293974 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:273975
3976 TransportSecurityState* security_state =
3977 default_context_.transport_security_state();
3978 bool sni_available = true;
3979 TransportSecurityState::DomainState domain_state;
3980 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:033981 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:273982 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
3983 domain_state.upgrade_mode);
3984 EXPECT_FALSE(domain_state.sts_include_subdomains);
3985 EXPECT_FALSE(domain_state.pkp_include_subdomains);
3986 EXPECT_TRUE(domain_state.HasPublicKeyPins());
3987 EXPECT_NE(domain_state.upgrade_expiry,
3988 domain_state.dynamic_spki_hashes_expiry);
[email protected]242d8562012-10-30 21:20:463989}
3990
3991TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:223992 SpawnedTestServer::SSLOptions ssl_options;
3993 SpawnedTestServer https_test_server(
3994 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:463995 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:153996 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:463997 ASSERT_TRUE(https_test_server.Start());
3998
3999 TestDelegate d;
4000 URLRequest request(
4001 https_test_server.GetURL("files/hsts-multiple-headers.html"),
4002 &d,
4003 &default_context_);
4004 request.Start();
[email protected]255620da2013-08-19 13:14:294005 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464006
4007 // We should have set parameters from the first header, not the second.
4008 TransportSecurityState* security_state =
4009 default_context_.transport_security_state();
4010 bool sni_available = true;
4011 TransportSecurityState::DomainState domain_state;
4012 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034013 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:464014 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4015 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:054016 EXPECT_FALSE(domain_state.sts_include_subdomains);
4017 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]242d8562012-10-30 21:20:464018}
4019
[email protected]9f972ec2013-04-10 20:24:364020TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:224021 SpawnedTestServer::SSLOptions ssl_options;
4022 SpawnedTestServer https_test_server(
4023 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:364024 ssl_options,
4025 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4026 ASSERT_TRUE(https_test_server.Start());
4027
4028 TestDelegate d;
4029 URLRequest request(
4030 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
4031 &d,
4032 &default_context_);
4033 request.Start();
[email protected]255620da2013-08-19 13:14:294034 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:364035
4036 // We should have set parameters from the first header, not the second.
4037 TransportSecurityState* security_state =
4038 default_context_.transport_security_state();
4039 bool sni_available = true;
4040 TransportSecurityState::DomainState domain_state;
4041 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034042 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]9f972ec2013-04-10 20:24:364043 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4044 domain_state.upgrade_mode);
4045#if defined(OS_ANDROID)
4046 // Android's CertVerifyProc does not (yet) handle pins.
4047#else
4048 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4049#endif
4050 EXPECT_NE(domain_state.upgrade_expiry,
4051 domain_state.dynamic_spki_hashes_expiry);
4052
[email protected]a165f092013-06-12 16:10:054053 // Even though there is an HSTS header asserting includeSubdomains, it is
4054 // the *second* such header, and we MUST process only the first.
4055 EXPECT_FALSE(domain_state.sts_include_subdomains);
4056 // includeSubdomains does not occur in the test HPKP header.
4057 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]9f972ec2013-04-10 20:24:364058}
4059
[email protected]37fd55fb2013-06-29 13:13:274060// Tests that when multiple HPKP headers are present, asserting different
4061// policies, that only the first such policy is processed.
4062TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
4063 SpawnedTestServer::SSLOptions ssl_options;
4064 SpawnedTestServer https_test_server(
4065 SpawnedTestServer::TYPE_HTTPS,
4066 ssl_options,
4067 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4068 ASSERT_TRUE(https_test_server.Start());
4069
4070 TestDelegate d;
4071 URLRequest request(
4072 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
4073 &d,
4074 &default_context_);
4075 request.Start();
[email protected]255620da2013-08-19 13:14:294076 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:274077
4078 TransportSecurityState* security_state =
4079 default_context_.transport_security_state();
4080 bool sni_available = true;
4081 TransportSecurityState::DomainState domain_state;
4082 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034083 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:274084 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4085 domain_state.upgrade_mode);
4086#if defined(OS_ANDROID)
4087 // Android's CertVerifyProc does not (yet) handle pins.
4088#else
4089 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4090#endif
4091 EXPECT_NE(domain_state.upgrade_expiry,
4092 domain_state.dynamic_spki_hashes_expiry);
4093
4094 EXPECT_TRUE(domain_state.sts_include_subdomains);
4095 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4096}
4097
[email protected]316c1e5e2012-09-12 15:17:444098TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
4099 ASSERT_TRUE(test_server_.Start());
4100
4101 TestDelegate d;
4102 URLRequest req(test_server_.GetURL(
4103 "files/content-type-normalization.html"), &d, &default_context_);
4104 req.Start();
[email protected]255620da2013-08-19 13:14:294105 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444106
4107 std::string mime_type;
4108 req.GetMimeType(&mime_type);
4109 EXPECT_EQ("text/html", mime_type);
4110
4111 std::string charset;
4112 req.GetCharset(&charset);
4113 EXPECT_EQ("utf-8", charset);
4114 req.Cancel();
4115}
4116
[email protected]e0f35c92013-05-08 16:04:344117TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) {
4118 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
4119 GURL file_url("file:///foo.txt");
4120 GURL data_url("data:,foo");
[email protected]255620da2013-08-19 13:14:294121 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
[email protected]e0f35c92013-05-08 16:04:344122 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
4123 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:024124 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:344125
4126 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
4127 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
[email protected]588614c22013-08-16 00:09:024128 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:344129}
4130
[email protected]588614c22013-08-16 00:09:024131TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:444132 ASSERT_TRUE(test_server_.Start());
4133
4134 TestDelegate d;
4135 URLRequest req(test_server_.GetURL(
4136 "files/redirect-to-file.html"), &d, &default_context_);
4137 req.Start();
[email protected]255620da2013-08-19 13:14:294138 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444139
4140 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4141 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
4142}
4143
[email protected]588614c22013-08-16 00:09:024144TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
4145 ASSERT_TRUE(test_server_.Start());
4146
4147 TestDelegate d;
4148 URLRequest req(test_server_.GetURL(
4149 "files/redirect-to-data.html"), &d, &default_context_);
4150 req.Start();
4151 base::MessageLoop::current()->Run();
4152
4153 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4154 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
4155}
4156
[email protected]316c1e5e2012-09-12 15:17:444157TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
4158 ASSERT_TRUE(test_server_.Start());
4159
4160 TestDelegate d;
4161 URLRequest req(test_server_.GetURL(
4162 "files/redirect-to-invalid-url.html"), &d, &default_context_);
4163 req.Start();
[email protected]255620da2013-08-19 13:14:294164 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444165
4166 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4167 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
4168}
4169
4170TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
4171 ASSERT_TRUE(test_server_.Start());
4172
4173 TestDelegate d;
4174 URLRequest req(
4175 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:134176 req.SetReferrer("http://user:[email protected]/");
[email protected]316c1e5e2012-09-12 15:17:444177 req.Start();
[email protected]255620da2013-08-19 13:14:294178 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444179
4180 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
4181}
4182
[email protected]99ecf6e2013-04-10 22:46:134183TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
4184 ASSERT_TRUE(test_server_.Start());
4185
4186 TestDelegate d;
4187 URLRequest req(
4188 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
4189 req.SetReferrer("http://foo.com/test#fragment");
4190 req.Start();
[email protected]255620da2013-08-19 13:14:294191 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:134192
4193 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
4194}
4195
4196TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
4197 ASSERT_TRUE(test_server_.Start());
4198
4199 TestDelegate d;
4200 URLRequest req(
4201 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
4202 req.SetReferrer("http://foo.com/test#fragment");
4203 req.SetReferrer("");
4204 req.Start();
[email protected]255620da2013-08-19 13:14:294205 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:134206
4207 EXPECT_EQ(std::string("None"), d.data_received());
4208}
4209
[email protected]316c1e5e2012-09-12 15:17:444210TEST_F(URLRequestTestHTTP, CancelRedirect) {
4211 ASSERT_TRUE(test_server_.Start());
4212
4213 TestDelegate d;
4214 {
4215 d.set_cancel_in_received_redirect(true);
4216 URLRequest req(
4217 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
4218 req.Start();
[email protected]255620da2013-08-19 13:14:294219 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444220
4221 EXPECT_EQ(1, d.response_started_count());
4222 EXPECT_EQ(0, d.bytes_received());
4223 EXPECT_FALSE(d.received_data_before_response());
4224 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
4225 }
4226}
4227
4228TEST_F(URLRequestTestHTTP, DeferredRedirect) {
4229 ASSERT_TRUE(test_server_.Start());
4230
4231 TestDelegate d;
4232 {
4233 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:044234 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
4235 URLRequest req(test_url, &d, &default_context_);
4236
[email protected]316c1e5e2012-09-12 15:17:444237 req.Start();
[email protected]255620da2013-08-19 13:14:294238 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444239
4240 EXPECT_EQ(1, d.received_redirect_count());
4241
4242 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:294243 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444244
4245 EXPECT_EQ(1, d.response_started_count());
4246 EXPECT_FALSE(d.received_data_before_response());
4247 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
4248
[email protected]6cdfd7f2013-02-08 20:40:154249 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444250 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4251 path = path.Append(FILE_PATH_LITERAL("net"));
4252 path = path.Append(FILE_PATH_LITERAL("data"));
4253 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4254 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4255
4256 std::string contents;
[email protected]82f84b92013-08-30 18:23:504257 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:444258 EXPECT_EQ(contents, d.data_received());
4259 }
4260}
4261
[email protected]79e1fd62013-06-20 06:50:044262TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
4263 ASSERT_TRUE(test_server_.Start());
4264
4265 TestDelegate d;
4266 {
4267 d.set_quit_on_redirect(true);
4268 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
4269 URLRequest req(test_url, &d, &default_context_);
4270
4271 EXPECT_FALSE(d.have_full_request_headers());
4272
4273 req.Start();
[email protected]255620da2013-08-19 13:14:294274 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044275
4276 EXPECT_EQ(1, d.received_redirect_count());
4277 EXPECT_TRUE(d.have_full_request_headers());
4278 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4279 d.ClearFullRequestHeaders();
4280
4281 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:294282 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044283
4284 GURL target_url(test_server_.GetURL("files/with-headers.html"));
4285 EXPECT_EQ(1, d.response_started_count());
4286 EXPECT_TRUE(d.have_full_request_headers());
4287 CheckFullRequestHeaders(d.full_request_headers(), target_url);
4288 EXPECT_FALSE(d.received_data_before_response());
4289 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
4290
4291 base::FilePath path;
4292 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4293 path = path.Append(FILE_PATH_LITERAL("net"));
4294 path = path.Append(FILE_PATH_LITERAL("data"));
4295 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4296 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4297
4298 std::string contents;
[email protected]82f84b92013-08-30 18:23:504299 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:044300 EXPECT_EQ(contents, d.data_received());
4301 }
4302}
4303
[email protected]316c1e5e2012-09-12 15:17:444304TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
4305 ASSERT_TRUE(test_server_.Start());
4306
4307 TestDelegate d;
4308 {
4309 d.set_quit_on_redirect(true);
4310 URLRequest req(
4311 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
4312 req.Start();
[email protected]255620da2013-08-19 13:14:294313 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444314
4315 EXPECT_EQ(1, d.received_redirect_count());
4316
4317 req.Cancel();
[email protected]255620da2013-08-19 13:14:294318 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444319
4320 EXPECT_EQ(1, d.response_started_count());
4321 EXPECT_EQ(0, d.bytes_received());
4322 EXPECT_FALSE(d.received_data_before_response());
4323 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
4324 }
4325}
4326
4327TEST_F(URLRequestTestHTTP, VaryHeader) {
4328 ASSERT_TRUE(test_server_.Start());
4329
[email protected]3b23a222013-05-15 21:33:254330 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:444331 {
4332 TestDelegate d;
4333 URLRequest req(
4334 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
4335 HttpRequestHeaders headers;
4336 headers.SetHeader("foo", "1");
4337 req.SetExtraRequestHeaders(headers);
4338 req.Start();
[email protected]255620da2013-08-19 13:14:294339 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:254340
4341 LoadTimingInfo load_timing_info;
4342 req.GetLoadTimingInfo(&load_timing_info);
4343 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:444344 }
4345
[email protected]3b23a222013-05-15 21:33:254346 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:444347 {
4348 TestDelegate d;
4349 URLRequest req(
4350 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
4351 HttpRequestHeaders headers;
4352 headers.SetHeader("foo", "1");
4353 req.SetExtraRequestHeaders(headers);
4354 req.Start();
[email protected]255620da2013-08-19 13:14:294355 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444356
4357 EXPECT_TRUE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:254358
4359 LoadTimingInfo load_timing_info;
4360 req.GetLoadTimingInfo(&load_timing_info);
4361 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:444362 }
4363
[email protected]3b23a222013-05-15 21:33:254364 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:444365 {
4366 TestDelegate d;
4367 URLRequest req(
4368 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
4369 HttpRequestHeaders headers;
4370 headers.SetHeader("foo", "2");
4371 req.SetExtraRequestHeaders(headers);
4372 req.Start();
[email protected]255620da2013-08-19 13:14:294373 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444374
4375 EXPECT_FALSE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:254376
4377 LoadTimingInfo load_timing_info;
4378 req.GetLoadTimingInfo(&load_timing_info);
4379 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:444380 }
4381}
4382
4383TEST_F(URLRequestTestHTTP, BasicAuth) {
4384 ASSERT_TRUE(test_server_.Start());
4385
4386 // populate the cache
4387 {
4388 TestDelegate d;
4389 d.set_credentials(AuthCredentials(kUser, kSecret));
4390
4391 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
4392 r.Start();
4393
[email protected]255620da2013-08-19 13:14:294394 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444395
4396 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
4397 }
4398
4399 // repeat request with end-to-end validation. since auth-basic results in a
4400 // cachable page, we expect this test to result in a 304. in which case, the
4401 // response should be fetched from the cache.
4402 {
4403 TestDelegate d;
4404 d.set_credentials(AuthCredentials(kUser, kSecret));
4405
4406 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
4407 r.set_load_flags(LOAD_VALIDATE_CACHE);
4408 r.Start();
4409
[email protected]255620da2013-08-19 13:14:294410 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444411
4412 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
4413
4414 // Should be the same cached document.
4415 EXPECT_TRUE(r.was_cached());
4416 }
4417}
4418
4419// Check that Set-Cookie headers in 401 responses are respected.
4420// http://crbug.com/6450
4421TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
4422 ASSERT_TRUE(test_server_.Start());
4423
4424 GURL url_requiring_auth =
4425 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
4426
4427 // Request a page that will give a 401 containing a Set-Cookie header.
4428 // Verify that when the transaction is restarted, it includes the new cookie.
4429 {
[email protected]ceefd7fd2012-11-29 00:36:244430 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:444431 TestURLRequestContext context(true);
4432 context.set_network_delegate(&network_delegate);
4433 context.Init();
4434
4435 TestDelegate d;
4436 d.set_credentials(AuthCredentials(kUser, kSecret));
4437
4438 URLRequest r(url_requiring_auth, &d, &context);
4439 r.Start();
4440
[email protected]255620da2013-08-19 13:14:294441 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444442
4443 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
4444
4445 // Make sure we sent the cookie in the restarted transaction.
4446 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
4447 != std::string::npos);
4448 }
4449
4450 // Same test as above, except this time the restart is initiated earlier
4451 // (without user intervention since identity is embedded in the URL).
4452 {
[email protected]ceefd7fd2012-11-29 00:36:244453 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:444454 TestURLRequestContext context(true);
4455 context.set_network_delegate(&network_delegate);
4456 context.Init();
4457
4458 TestDelegate d;
4459
4460 GURL::Replacements replacements;
4461 std::string username("user2");
4462 std::string password("secret");
4463 replacements.SetUsernameStr(username);
4464 replacements.SetPasswordStr(password);
4465 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
4466
4467 URLRequest r(url_with_identity, &d, &context);
4468 r.Start();
4469
[email protected]255620da2013-08-19 13:14:294470 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444471
4472 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
4473
4474 // Make sure we sent the cookie in the restarted transaction.
4475 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
4476 != std::string::npos);
4477 }
4478}
4479
[email protected]58e32bb2013-01-21 18:23:254480// Tests that load timing works as expected with auth and the cache.
4481TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
4482 ASSERT_TRUE(test_server_.Start());
4483
4484 // populate the cache
4485 {
4486 TestDelegate d;
4487 d.set_credentials(AuthCredentials(kUser, kSecret));
4488
4489 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
4490 r.Start();
4491
[email protected]255620da2013-08-19 13:14:294492 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254493
4494 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
4495
4496 LoadTimingInfo load_timing_info_before_auth;
4497 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
4498 &load_timing_info_before_auth));
4499 TestLoadTimingNotReused(load_timing_info_before_auth,
4500 CONNECT_TIMING_HAS_DNS_TIMES);
4501
4502 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:174503 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:254504 // The test server does not support keep alive sockets, so the second
4505 // request with auth should use a new socket.
4506 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
4507 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
4508 load_timing_info.socket_log_id);
4509 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
4510 load_timing_info.connect_timing.connect_start);
4511 }
4512
[email protected]3b23a222013-05-15 21:33:254513 // Repeat request with end-to-end validation. Since auth-basic results in a
4514 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:254515 // response should be fetched from the cache.
4516 {
4517 TestDelegate d;
4518 d.set_credentials(AuthCredentials(kUser, kSecret));
4519
4520 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
4521 r.set_load_flags(LOAD_VALIDATE_CACHE);
4522 r.Start();
4523
[email protected]255620da2013-08-19 13:14:294524 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:254525
4526 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
4527
4528 // Should be the same cached document.
4529 EXPECT_TRUE(r.was_cached());
4530
[email protected]3b23a222013-05-15 21:33:254531 // Since there was a request that went over the wire, the load timing
4532 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:254533 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:174534 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:254535 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:254536 }
4537}
4538
[email protected]316c1e5e2012-09-12 15:17:444539// In this test, we do a POST which the server will 302 redirect.
4540// The subsequent transaction should use GET, and should not send the
4541// Content-Type header.
4542// http://code.google.com/p/chromium/issues/detail?id=843
4543TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
4544 ASSERT_TRUE(test_server_.Start());
4545
4546 const char kData[] = "hello world";
4547
4548 TestDelegate d;
4549 URLRequest req(
4550 test_server_.GetURL("files/redirect-to-echoall"), &d, &default_context_);
4551 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:284552 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:444553
4554 // Set headers (some of which are specific to the POST).
4555 HttpRequestHeaders headers;
4556 headers.AddHeadersFromString(
4557 "Content-Type: multipart/form-data; "
4558 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
4559 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
4560 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
4561 "Accept-Language: en-US,en\r\n"
4562 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
4563 "Content-Length: 11\r\n"
4564 "Origin: http://localhost:1337/");
4565 req.SetExtraRequestHeaders(headers);
4566 req.Start();
[email protected]255620da2013-08-19 13:14:294567 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444568
4569 std::string mime_type;
4570 req.GetMimeType(&mime_type);
4571 EXPECT_EQ("text/html", mime_type);
4572
4573 const std::string& data = d.data_received();
4574
4575 // Check that the post-specific headers were stripped:
4576 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
4577 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
4578 EXPECT_FALSE(ContainsString(data, "Origin:"));
4579
4580 // These extra request headers should not have been stripped.
4581 EXPECT_TRUE(ContainsString(data, "Accept:"));
4582 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
4583 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
4584}
4585
4586// The following tests check that we handle mutating the request method for
4587// HTTP redirects as expected.
4588// See http://crbug.com/56373 and http://crbug.com/102130.
4589
4590TEST_F(URLRequestTestHTTP, Redirect301Tests) {
4591 ASSERT_TRUE(test_server_.Start());
4592
4593 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
4594
4595 HTTPRedirectMethodTest(url, "POST", "GET", true);
4596 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
4597 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
4598}
4599
4600TEST_F(URLRequestTestHTTP, Redirect302Tests) {
4601 ASSERT_TRUE(test_server_.Start());
4602
4603 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
4604
4605 HTTPRedirectMethodTest(url, "POST", "GET", true);
4606 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
4607 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
4608}
4609
4610TEST_F(URLRequestTestHTTP, Redirect303Tests) {
4611 ASSERT_TRUE(test_server_.Start());
4612
4613 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
4614
4615 HTTPRedirectMethodTest(url, "POST", "GET", true);
4616 HTTPRedirectMethodTest(url, "PUT", "GET", true);
4617 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
4618}
4619
4620TEST_F(URLRequestTestHTTP, Redirect307Tests) {
4621 ASSERT_TRUE(test_server_.Start());
4622
4623 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
4624
4625 HTTPRedirectMethodTest(url, "POST", "POST", true);
4626 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
4627 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
4628}
4629
4630TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
4631 ASSERT_TRUE(test_server_.Start());
4632
4633 const char kData[] = "hello world";
4634
4635 TestDelegate d;
4636 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
4637 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:284638 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:444639 HttpRequestHeaders headers;
4640 headers.SetHeader(HttpRequestHeaders::kContentLength,
4641 base::UintToString(arraysize(kData) - 1));
4642 req.SetExtraRequestHeaders(headers);
4643
4644 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:414645 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]8ccc69f2012-11-28 19:52:144646 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]316c1e5e2012-09-12 15:17:444647 AddTestInterceptor()->set_main_intercept_job(job);
4648
4649 req.Start();
[email protected]255620da2013-08-19 13:14:294650 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444651 EXPECT_EQ("GET", req.method());
4652}
4653
4654TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
4655 ASSERT_TRUE(test_server_.Start());
4656
4657 const char kData[] = "hello world";
4658
4659 TestDelegate d;
4660 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
4661 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:284662 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:444663 HttpRequestHeaders headers;
4664 headers.SetHeader(HttpRequestHeaders::kContentLength,
4665 base::UintToString(arraysize(kData) - 1));
4666 req.SetExtraRequestHeaders(headers);
4667
4668 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:414669 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]316c1e5e2012-09-12 15:17:444670 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT);
4671 AddTestInterceptor()->set_main_intercept_job(job);
4672
4673 req.Start();
[email protected]255620da2013-08-19 13:14:294674 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444675 EXPECT_EQ("POST", req.method());
4676 EXPECT_EQ(kData, d.data_received());
4677}
4678
4679// Check that default A-L header is sent.
4680TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
4681 ASSERT_TRUE(test_server_.Start());
4682
[email protected]84f05432013-03-15 01:00:124683 StaticHttpUserAgentSettings settings("en", EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:244684 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:444685 TestURLRequestContext context(true);
4686 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:434687 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:444688 context.Init();
4689
4690 TestDelegate d;
4691 URLRequest req(
4692 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
4693 req.Start();
[email protected]255620da2013-08-19 13:14:294694 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444695 EXPECT_EQ("en", d.data_received());
4696}
4697
4698// Check that an empty A-L header is not sent. http://crbug.com/77365.
4699TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
4700 ASSERT_TRUE(test_server_.Start());
4701
[email protected]84f05432013-03-15 01:00:124702 StaticHttpUserAgentSettings settings(EmptyString(), EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:244703 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:444704 TestURLRequestContext context(true);
4705 context.set_network_delegate(&network_delegate);
4706 context.Init();
4707 // We override the language after initialization because empty entries
4708 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:434709 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:444710
4711 TestDelegate d;
4712 URLRequest req(
4713 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
4714 req.Start();
[email protected]255620da2013-08-19 13:14:294715 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444716 EXPECT_EQ("None", d.data_received());
4717}
4718
4719// Check that if request overrides the A-L header, the default is not appended.
4720// See http://crbug.com/20894
4721TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
4722 ASSERT_TRUE(test_server_.Start());
4723
4724 TestDelegate d;
4725 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
4726 &d,
4727 &default_context_);
4728 HttpRequestHeaders headers;
4729 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
4730 req.SetExtraRequestHeaders(headers);
4731 req.Start();
[email protected]255620da2013-08-19 13:14:294732 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444733 EXPECT_EQ(std::string("ru"), d.data_received());
4734}
4735
4736// Check that default A-E header is sent.
4737TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
4738 ASSERT_TRUE(test_server_.Start());
4739
4740 TestDelegate d;
4741 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
4742 &d,
4743 &default_context_);
4744 HttpRequestHeaders headers;
4745 req.SetExtraRequestHeaders(headers);
4746 req.Start();
[email protected]255620da2013-08-19 13:14:294747 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444748 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
4749}
4750
4751// Check that if request overrides the A-E header, the default is not appended.
4752// See http://crbug.com/47381
4753TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
4754 ASSERT_TRUE(test_server_.Start());
4755
4756 TestDelegate d;
4757 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
4758 &d,
4759 &default_context_);
4760 HttpRequestHeaders headers;
4761 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
4762 req.SetExtraRequestHeaders(headers);
4763 req.Start();
[email protected]255620da2013-08-19 13:14:294764 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444765 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
4766 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
4767}
4768
[email protected]84f05432013-03-15 01:00:124769// Check that setting the A-C header sends the proper header.
4770TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:444771 ASSERT_TRUE(test_server_.Start());
4772
4773 TestDelegate d;
4774 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
4775 &d,
4776 &default_context_);
4777 HttpRequestHeaders headers;
4778 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
4779 req.SetExtraRequestHeaders(headers);
4780 req.Start();
[email protected]255620da2013-08-19 13:14:294781 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444782 EXPECT_EQ(std::string("koi-8r"), d.data_received());
4783}
4784
4785// Check that default User-Agent header is sent.
4786TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
4787 ASSERT_TRUE(test_server_.Start());
4788
4789 TestDelegate d;
4790 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
4791 &d,
4792 &default_context_);
4793 req.Start();
[email protected]255620da2013-08-19 13:14:294794 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444795 EXPECT_EQ(req.context()->GetUserAgent(req.url()), d.data_received());
4796}
4797
4798// Check that if request overrides the User-Agent header,
4799// the default is not appended.
4800TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
4801 ASSERT_TRUE(test_server_.Start());
4802
4803 TestDelegate d;
4804 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
4805 &d,
4806 &default_context_);
4807 HttpRequestHeaders headers;
4808 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
4809 req.SetExtraRequestHeaders(headers);
4810 req.Start();
[email protected]255620da2013-08-19 13:14:294811 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444812 // If the net tests are being run with ChromeFrame then we need to allow for
4813 // the 'chromeframe' suffix which is added to the user agent before the
4814 // closing parentheses.
4815 EXPECT_TRUE(StartsWithASCII(d.data_received(), "Lynx (textmode", true));
4816}
4817
[email protected]ee4c30d2012-11-07 15:08:434818// Check that a NULL HttpUserAgentSettings causes the corresponding empty
4819// User-Agent header to be sent but does not send the Accept-Language and
4820// Accept-Charset headers.
4821TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
4822 ASSERT_TRUE(test_server_.Start());
4823
[email protected]ceefd7fd2012-11-29 00:36:244824 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:434825 TestURLRequestContext context(true);
4826 context.set_network_delegate(&network_delegate);
4827 context.Init();
4828 // We override the HttpUserAgentSettings after initialization because empty
4829 // entries get overridden by Init().
4830 context.set_http_user_agent_settings(NULL);
4831
4832 struct {
4833 const char* request;
4834 const char* expected_response;
4835 } tests[] = { { "echoheader?Accept-Language", "None" },
4836 { "echoheader?Accept-Charset", "None" },
4837 { "echoheader?User-Agent", "" } };
4838
4839 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
4840 TestDelegate d;
4841 URLRequest req(test_server_.GetURL(tests[i].request), &d, &context);
4842 req.Start();
[email protected]255620da2013-08-19 13:14:294843 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:434844 EXPECT_EQ(tests[i].expected_response, d.data_received())
4845 << " Request = \"" << tests[i].request << "\"";
4846 }
4847}
4848
[email protected]5033ab82013-03-22 20:17:464849// Make sure that URLRequest passes on its priority updates to
4850// newly-created jobs after the first one.
4851TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
4852 ASSERT_TRUE(test_server_.Start());
4853
4854 TestDelegate d;
4855 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
4856 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
4857
4858 scoped_refptr<URLRequestRedirectJob> redirect_job =
4859 new URLRequestRedirectJob(
4860 &req, &default_network_delegate_, test_server_.GetURL("echo"),
4861 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]90499482013-06-01 00:39:504862 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:464863
4864 req.SetPriority(LOW);
4865 req.Start();
4866 EXPECT_TRUE(req.is_pending());
4867
4868 scoped_refptr<URLRequestTestJob> job =
4869 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:504870 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:464871
4872 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:294873 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:464874 EXPECT_EQ(LOW, job->priority());
4875}
4876
[email protected]73e0bba2009-02-19 22:57:094877class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:504878 public:
[email protected]ef2bf422012-05-11 03:27:094879 HTTPSRequestTest() : default_context_(true) {
4880 default_context_.set_network_delegate(&default_network_delegate_);
4881 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:504882 }
4883 virtual ~HTTPSRequestTest() {}
4884
4885 protected:
[email protected]ceefd7fd2012-11-29 00:36:244886 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:094887 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:464888};
4889
[email protected]c044616e2013-02-20 02:01:264890TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:224891 SpawnedTestServer test_server(
4892 SpawnedTestServer::TYPE_HTTPS,
4893 SpawnedTestServer::kLocalhost,
4894 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114895 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:464896
[email protected]ea224582008-12-07 20:25:464897 TestDelegate d;
4898 {
[email protected]007b3f82013-04-09 08:46:454899 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]ea224582008-12-07 20:25:464900 r.Start();
4901 EXPECT_TRUE(r.is_pending());
4902
[email protected]255620da2013-08-19 13:14:294903 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:464904
4905 EXPECT_EQ(1, d.response_started_count());
4906 EXPECT_FALSE(d.received_data_before_response());
4907 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174908 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:194909 EXPECT_EQ(test_server.host_port_pair().host(),
4910 r.GetSocketAddress().host());
4911 EXPECT_EQ(test_server.host_port_pair().port(),
4912 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:464913 }
[email protected]ea224582008-12-07 20:25:464914}
4915
[email protected]5774ada2010-07-15 06:30:544916TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:224917 SpawnedTestServer::SSLOptions ssl_options(
4918 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
4919 SpawnedTestServer test_server(
4920 SpawnedTestServer::TYPE_HTTPS,
4921 ssl_options,
4922 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114923 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:334924
4925 bool err_allowed = true;
4926 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
4927 TestDelegate d;
4928 {
4929 d.set_allow_certificate_errors(err_allowed);
[email protected]007b3f82013-04-09 08:46:454930 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:334931
4932 r.Start();
4933 EXPECT_TRUE(r.is_pending());
4934
[email protected]255620da2013-08-19 13:14:294935 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:334936
4937 EXPECT_EQ(1, d.response_started_count());
4938 EXPECT_FALSE(d.received_data_before_response());
4939 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:174940 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:334941 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174942 CheckSSLInfo(r.ssl_info());
4943 } else {
[email protected]bacff652009-03-31 17:50:334944 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174945 }
[email protected]bacff652009-03-31 17:50:334946 }
4947 }
4948}
4949
[email protected]5774ada2010-07-15 06:30:544950TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:224951 SpawnedTestServer::SSLOptions ssl_options(
4952 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
4953 SpawnedTestServer test_server(
4954 SpawnedTestServer::TYPE_HTTPS,
4955 ssl_options,
4956 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:114957 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:334958
4959 // Iterate from false to true, just so that we do the opposite of the
4960 // previous test in order to increase test coverage.
4961 bool err_allowed = false;
4962 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
4963 TestDelegate d;
4964 {
4965 d.set_allow_certificate_errors(err_allowed);
[email protected]007b3f82013-04-09 08:46:454966 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:334967
4968 r.Start();
4969 EXPECT_TRUE(r.is_pending());
4970
[email protected]255620da2013-08-19 13:14:294971 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:334972
4973 EXPECT_EQ(1, d.response_started_count());
4974 EXPECT_FALSE(d.received_data_before_response());
4975 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:174976 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:334977 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174978 CheckSSLInfo(r.ssl_info());
4979 } else {
[email protected]bacff652009-03-31 17:50:334980 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:174981 }
[email protected]bacff652009-03-31 17:50:334982 }
4983 }
4984}
[email protected]73e0bba2009-02-19 22:57:094985
[email protected]316c1e5e2012-09-12 15:17:444986// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
4987// than necessary.
4988TEST_F(HTTPSRequestTest, TLSv1Fallback) {
4989 uint16 default_version_max = SSLConfigService::default_version_max();
4990 // The OpenSSL library in use may not support TLS 1.1.
4991#if !defined(USE_OPENSSL)
4992 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1);
4993#endif
4994 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1)
4995 return;
4996
[email protected]ce7d0cbc2013-05-03 18:57:224997 SpawnedTestServer::SSLOptions ssl_options(
4998 SpawnedTestServer::SSLOptions::CERT_OK);
[email protected]316c1e5e2012-09-12 15:17:444999 ssl_options.tls_intolerant =
[email protected]ce7d0cbc2013-05-03 18:57:225000 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
5001 SpawnedTestServer test_server(
5002 SpawnedTestServer::TYPE_HTTPS,
5003 ssl_options,
5004 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445005 ASSERT_TRUE(test_server.Start());
5006
5007 TestDelegate d;
5008 TestURLRequestContext context(true);
5009 context.Init();
5010 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:455011 URLRequest r(test_server.GetURL(std::string()), &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445012 r.Start();
5013
[email protected]255620da2013-08-19 13:14:295014 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445015
5016 EXPECT_EQ(1, d.response_started_count());
5017 EXPECT_NE(0, d.bytes_received());
5018 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
5019 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
5020 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
5021}
5022
5023// This tests that a load of www.google.com with a certificate error sets
5024// the |certificate_errors_are_fatal| flag correctly. This flag will cause
5025// the interstitial to be fatal.
5026TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225027 SpawnedTestServer::SSLOptions ssl_options(
5028 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5029 SpawnedTestServer test_server(
5030 SpawnedTestServer::TYPE_HTTPS,
5031 ssl_options,
5032 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445033 ASSERT_TRUE(test_server.Start());
5034
5035 // We require that the URL be www.google.com in order to pick up the
5036 // preloaded HSTS entries in the TransportSecurityState. This means that we
5037 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:245038 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:445039
5040 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:245041 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445042 TestURLRequestContext context(true);
5043 context.set_network_delegate(&network_delegate);
5044 context.set_host_resolver(&host_resolver);
5045 TransportSecurityState transport_security_state;
5046 context.set_transport_security_state(&transport_security_state);
5047 context.Init();
5048
5049 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:045050 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
5051 test_server.host_port_pair().port())),
[email protected]316c1e5e2012-09-12 15:17:445052 &d,
5053 &context);
5054
5055 r.Start();
5056 EXPECT_TRUE(r.is_pending());
5057
[email protected]255620da2013-08-19 13:14:295058 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445059
5060 EXPECT_EQ(1, d.response_started_count());
5061 EXPECT_FALSE(d.received_data_before_response());
5062 EXPECT_TRUE(d.have_certificate_errors());
5063 EXPECT_TRUE(d.certificate_errors_are_fatal());
5064}
5065
5066// This tests that cached HTTPS page loads do not cause any updates to the
5067// TransportSecurityState.
5068TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
5069 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
5070 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:225071 SpawnedTestServer::SSLOptions ssl_options(
5072 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5073 SpawnedTestServer test_server(
5074 SpawnedTestServer::TYPE_HTTPS,
5075 ssl_options,
5076 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445077 ASSERT_TRUE(test_server.Start());
5078
5079 // We require that the URL be www.google.com in order to pick up the
5080 // preloaded and dynamic HSTS and public key pin entries in the
5081 // TransportSecurityState. This means that we have to use a
5082 // MockHostResolver in order to direct www.google.com to the testserver.
[email protected]ceefd7fd2012-11-29 00:36:245083 // By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:445084
5085 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:245086 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445087 TestURLRequestContext context(true);
5088 context.set_network_delegate(&network_delegate);
5089 context.set_host_resolver(&host_resolver);
5090 TransportSecurityState transport_security_state;
5091 TransportSecurityState::DomainState domain_state;
[email protected]22e045f2013-09-20 03:54:035092 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
5093 &domain_state));
[email protected]316c1e5e2012-09-12 15:17:445094 context.set_transport_security_state(&transport_security_state);
5095 context.Init();
5096
5097 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:045098 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
5099 test_server.host_port_pair().port())),
[email protected]316c1e5e2012-09-12 15:17:445100 &d,
5101 &context);
5102
5103 r.Start();
5104 EXPECT_TRUE(r.is_pending());
5105
[email protected]255620da2013-08-19 13:14:295106 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445107
5108 EXPECT_EQ(1, d.response_started_count());
5109 EXPECT_FALSE(d.received_data_before_response());
5110 EXPECT_TRUE(d.have_certificate_errors());
5111 EXPECT_TRUE(d.certificate_errors_are_fatal());
5112
5113 // Get a fresh copy of the state, and check that it hasn't been updated.
5114 TransportSecurityState::DomainState new_domain_state;
[email protected]22e045f2013-09-20 03:54:035115 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
5116 &new_domain_state));
[email protected]316c1e5e2012-09-12 15:17:445117 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:055118 EXPECT_EQ(new_domain_state.sts_include_subdomains,
5119 domain_state.sts_include_subdomains);
5120 EXPECT_EQ(new_domain_state.pkp_include_subdomains,
5121 domain_state.pkp_include_subdomains);
[email protected]316c1e5e2012-09-12 15:17:445122 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
5123 domain_state.static_spki_hashes));
5124 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
5125 domain_state.dynamic_spki_hashes));
5126 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
5127 domain_state.bad_static_spki_hashes));
5128}
5129
[email protected]8ccc69f2012-11-28 19:52:145130// Make sure HSTS preserves a POST request's method and body.
5131TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
5132 static const char kData[] = "hello world";
5133
[email protected]ce7d0cbc2013-05-03 18:57:225134 SpawnedTestServer::SSLOptions ssl_options(
5135 SpawnedTestServer::SSLOptions::CERT_OK);
5136 SpawnedTestServer test_server(
5137 SpawnedTestServer::TYPE_HTTPS,
5138 ssl_options,
5139 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:145140 ASSERT_TRUE(test_server.Start());
5141
5142
5143 // Per spec, TransportSecurityState expects a domain name, rather than an IP
5144 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:225145 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
5146 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:145147 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:145148
5149 // Force https for www.somewhere.com.
5150 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:205151 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
5152 bool include_subdomains = false;
5153 transport_security_state.AddHSTS("www.somewhere.com", expiry,
5154 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:145155
5156 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5157
5158 TestURLRequestContext context(true);
5159 context.set_host_resolver(&host_resolver);
5160 context.set_transport_security_state(&transport_security_state);
5161 context.set_network_delegate(&network_delegate);
5162 context.Init();
5163
5164 TestDelegate d;
5165 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
5166 // cause a certificate error. Ignore the error.
5167 d.set_allow_certificate_errors(true);
5168
[email protected]7d3cbc92013-03-18 22:33:045169 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
5170 test_server.host_port_pair().port())),
[email protected]8ccc69f2012-11-28 19:52:145171 &d,
5172 &context);
5173 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285174 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:145175
5176 req.Start();
[email protected]255620da2013-08-19 13:14:295177 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:145178
5179 EXPECT_EQ("https", req.url().scheme());
5180 EXPECT_EQ("POST", req.method());
5181 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:405182
5183 LoadTimingInfo load_timing_info;
5184 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
5185 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
5186 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:145187}
5188
[email protected]316c1e5e2012-09-12 15:17:445189TEST_F(HTTPSRequestTest, SSLv3Fallback) {
[email protected]ce7d0cbc2013-05-03 18:57:225190 SpawnedTestServer::SSLOptions ssl_options(
5191 SpawnedTestServer::SSLOptions::CERT_OK);
5192 ssl_options.tls_intolerant =
5193 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
5194 SpawnedTestServer test_server(
5195 SpawnedTestServer::TYPE_HTTPS,
5196 ssl_options,
5197 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445198 ASSERT_TRUE(test_server.Start());
5199
5200 TestDelegate d;
5201 TestURLRequestContext context(true);
5202 context.Init();
5203 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:455204 URLRequest r(test_server.GetURL(std::string()), &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445205 r.Start();
5206
[email protected]255620da2013-08-19 13:14:295207 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445208
5209 EXPECT_EQ(1, d.response_started_count());
5210 EXPECT_NE(0, d.bytes_received());
5211 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
5212 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
5213 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
5214}
5215
5216namespace {
5217
5218class SSLClientAuthTestDelegate : public TestDelegate {
5219 public:
5220 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
5221 }
5222 virtual void OnCertificateRequested(
5223 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:165224 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:445225 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:345226 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:445227 }
5228 int on_certificate_requested_count() {
5229 return on_certificate_requested_count_;
5230 }
5231 private:
5232 int on_certificate_requested_count_;
5233};
5234
5235} // namespace
5236
5237// TODO(davidben): Test the rest of the code. Specifically,
5238// - Filtering which certificates to select.
5239// - Sending a certificate back.
5240// - Getting a certificate request in an SSL renegotiation sending the
5241// HTTP request.
5242TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225243 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:445244 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:225245 SpawnedTestServer test_server(
5246 SpawnedTestServer::TYPE_HTTPS,
5247 ssl_options,
5248 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445249 ASSERT_TRUE(test_server.Start());
5250
5251 SSLClientAuthTestDelegate d;
5252 {
[email protected]007b3f82013-04-09 08:46:455253 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445254
5255 r.Start();
5256 EXPECT_TRUE(r.is_pending());
5257
[email protected]255620da2013-08-19 13:14:295258 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445259
5260 EXPECT_EQ(1, d.on_certificate_requested_count());
5261 EXPECT_FALSE(d.received_data_before_response());
5262 EXPECT_EQ(0, d.bytes_received());
5263
5264 // Send no certificate.
5265 // TODO(davidben): Get temporary client cert import (with keys) working on
5266 // all platforms so we can test sending a cert as well.
5267 r.ContinueWithCertificate(NULL);
5268
[email protected]255620da2013-08-19 13:14:295269 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445270
5271 EXPECT_EQ(1, d.response_started_count());
5272 EXPECT_FALSE(d.received_data_before_response());
5273 EXPECT_NE(0, d.bytes_received());
5274 }
5275}
5276
5277TEST_F(HTTPSRequestTest, ResumeTest) {
5278 // Test that we attempt a session resume when making two connections to the
5279 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:225280 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:445281 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:225282 SpawnedTestServer test_server(
5283 SpawnedTestServer::TYPE_HTTPS,
5284 ssl_options,
5285 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445286 ASSERT_TRUE(test_server.Start());
5287
5288 SSLClientSocket::ClearSessionCache();
5289
5290 {
5291 TestDelegate d;
5292 URLRequest r(
5293 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
5294
5295 r.Start();
5296 EXPECT_TRUE(r.is_pending());
5297
[email protected]255620da2013-08-19 13:14:295298 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445299
5300 EXPECT_EQ(1, d.response_started_count());
5301 }
5302
5303 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
5304 CloseAllConnections();
5305
5306 {
5307 TestDelegate d;
5308 URLRequest r(
5309 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
5310
5311 r.Start();
5312 EXPECT_TRUE(r.is_pending());
5313
[email protected]255620da2013-08-19 13:14:295314 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445315
5316 // The response will look like;
5317 // insert abc
5318 // lookup abc
5319 // insert xyz
5320 //
5321 // With a newline at the end which makes the split think that there are
5322 // four lines.
5323
5324 EXPECT_EQ(1, d.response_started_count());
5325 std::vector<std::string> lines;
5326 base::SplitString(d.data_received(), '\n', &lines);
5327 ASSERT_EQ(4u, lines.size()) << d.data_received();
5328
5329 std::string session_id;
5330
5331 for (size_t i = 0; i < 2; i++) {
5332 std::vector<std::string> parts;
5333 base::SplitString(lines[i], '\t', &parts);
5334 ASSERT_EQ(2u, parts.size());
5335 if (i == 0) {
5336 EXPECT_EQ("insert", parts[0]);
5337 session_id = parts[1];
5338 } else {
5339 EXPECT_EQ("lookup", parts[0]);
5340 EXPECT_EQ(session_id, parts[1]);
5341 }
5342 }
5343 }
5344}
5345
5346TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
5347 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
5348 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:225349 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:445350 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:225351 SpawnedTestServer test_server(
5352 SpawnedTestServer::TYPE_HTTPS,
5353 ssl_options,
5354 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445355 ASSERT_TRUE(test_server.Start());
5356
5357 SSLClientSocket::ClearSessionCache();
5358
5359 {
5360 TestDelegate d;
5361 URLRequest r(
5362 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
5363
5364 r.Start();
5365 EXPECT_TRUE(r.is_pending());
5366
[email protected]255620da2013-08-19 13:14:295367 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445368
5369 EXPECT_EQ(1, d.response_started_count());
5370 }
5371
5372 // Now create a new HttpCache with a different ssl_session_cache_shard value.
5373 HttpNetworkSession::Params params;
5374 params.host_resolver = default_context_.host_resolver();
5375 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:115376 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:445377 params.proxy_service = default_context_.proxy_service();
5378 params.ssl_config_service = default_context_.ssl_config_service();
5379 params.http_auth_handler_factory =
5380 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:415381 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:445382 params.http_server_properties = default_context_.http_server_properties();
5383 params.ssl_session_cache_shard = "alternate";
5384
5385 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
5386 new net::HttpNetworkSession(params),
5387 net::HttpCache::DefaultBackend::InMemory(0)));
5388
5389 default_context_.set_http_transaction_factory(cache.get());
5390
5391 {
5392 TestDelegate d;
5393 URLRequest r(
5394 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
5395
5396 r.Start();
5397 EXPECT_TRUE(r.is_pending());
5398
[email protected]255620da2013-08-19 13:14:295399 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445400
5401 // The response will look like;
5402 // insert abc
5403 // insert xyz
5404 //
5405 // With a newline at the end which makes the split think that there are
5406 // three lines.
5407
5408 EXPECT_EQ(1, d.response_started_count());
5409 std::vector<std::string> lines;
5410 base::SplitString(d.data_received(), '\n', &lines);
5411 ASSERT_EQ(3u, lines.size());
5412
5413 std::string session_id;
5414 for (size_t i = 0; i < 2; i++) {
5415 std::vector<std::string> parts;
5416 base::SplitString(lines[i], '\t', &parts);
5417 ASSERT_EQ(2u, parts.size());
5418 EXPECT_EQ("insert", parts[0]);
5419 if (i == 0) {
5420 session_id = parts[1];
5421 } else {
5422 EXPECT_NE(session_id, parts[1]);
5423 }
5424 }
5425 }
5426}
5427
[email protected]a13234c2012-03-20 21:45:025428class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:275429 public:
[email protected]3a86a712013-07-30 07:16:205430 TestSSLConfigService(bool ev_enabled,
5431 bool online_rev_checking,
5432 bool rev_checking_required_local_anchors)
[email protected]a13234c2012-03-20 21:45:025433 : ev_enabled_(ev_enabled),
[email protected]3a86a712013-07-30 07:16:205434 online_rev_checking_(online_rev_checking),
5435 rev_checking_required_local_anchors_(
5436 rev_checking_required_local_anchors) {}
[email protected]a13234c2012-03-20 21:45:025437
[email protected]a9813302012-04-28 09:29:285438 // SSLConfigService:
5439 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:275440 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:025441 config->rev_checking_enabled = online_rev_checking_;
5442 config->verify_ev_cert = ev_enabled_;
[email protected]3a86a712013-07-30 07:16:205443 config->rev_checking_required_local_anchors =
5444 rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:275445 }
[email protected]a13234c2012-03-20 21:45:025446
[email protected]a9813302012-04-28 09:29:285447 protected:
5448 virtual ~TestSSLConfigService() {}
5449
[email protected]a13234c2012-03-20 21:45:025450 private:
5451 const bool ev_enabled_;
5452 const bool online_rev_checking_;
[email protected]3a86a712013-07-30 07:16:205453 const bool rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:275454};
5455
5456// This the fingerprint of the "Testing CA" certificate used by the testserver.
5457// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:265458static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:275459 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
5460 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
5461
[email protected]51523f52013-07-31 21:57:285462// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
5463// testserver.
5464static const SHA256HashValue kOCSPTestCertSPKI = { {
5465 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
5466 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
5467 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
5468 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
5469} };
5470
[email protected]dffe8242012-03-20 15:14:275471// This is the policy OID contained in the certificates that testserver
5472// generates.
5473static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
5474
5475class HTTPSOCSPTest : public HTTPSRequestTest {
5476 public:
5477 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:095478 : context_(true),
[email protected]b6f2de32012-08-17 04:35:085479 ev_test_policy_(
5480 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
5481 kOCSPTestCertFingerprint,
5482 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:025483 }
5484
5485 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:095486 SetupContext(&context_);
5487 context_.Init();
[email protected]dffe8242012-03-20 15:14:275488
5489 scoped_refptr<net::X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:205490 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
[email protected]dffe8242012-03-20 15:14:275491 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
[email protected]90499482013-06-01 00:39:505492 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:275493
[email protected]a592c0432012-12-01 18:10:295494#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:095495 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:275496 EnsureNSSHttpIOInit();
5497#endif
5498 }
5499
[email protected]ce7d0cbc2013-05-03 18:57:225500 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:275501 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:535502 // We always overwrite out_cert_status.
5503 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:225504 SpawnedTestServer test_server(
5505 SpawnedTestServer::TYPE_HTTPS,
5506 ssl_options,
5507 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:275508 ASSERT_TRUE(test_server.Start());
5509
5510 TestDelegate d;
5511 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:455512 URLRequest r(test_server.GetURL(std::string()), &d, &context_);
[email protected]dffe8242012-03-20 15:14:275513 r.Start();
5514
[email protected]255620da2013-08-19 13:14:295515 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:275516
5517 EXPECT_EQ(1, d.response_started_count());
5518 *out_cert_status = r.ssl_info().cert_status;
5519 }
5520
[email protected]46fadfd2013-02-06 09:40:165521 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:295522#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:275523 ShutdownNSSHttpIO();
5524#endif
5525 }
5526
[email protected]a13234c2012-03-20 21:45:025527 protected:
5528 // SetupContext configures the URLRequestContext that will be used for making
5529 // connetions to testserver. This can be overridden in test subclasses for
5530 // different behaviour.
5531 virtual void SetupContext(URLRequestContext* context) {
5532 context->set_ssl_config_service(
5533 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:205534 true /* online revocation checking */,
5535 false /* require rev. checking for local
5536 anchors */));
[email protected]a13234c2012-03-20 21:45:025537 }
5538
[email protected]dffe8242012-03-20 15:14:275539 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:095540 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:085541 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:275542};
5543
[email protected]a13234c2012-03-20 21:45:025544static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:015545#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:025546 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
5547 // have that ability on other platforms.
5548 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
5549#else
5550 return 0;
5551#endif
5552}
5553
[email protected]3a86a712013-07-30 07:16:205554// SystemSupportsHardFailRevocationChecking returns true iff the current
5555// operating system supports revocation checking and can distinguish between
5556// situations where a given certificate lacks any revocation information (eg:
5557// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
5558// revocation information cannot be obtained (eg: the CRL was unreachable).
5559// If it does not, then tests which rely on 'hard fail' behaviour should be
5560// skipped.
5561static bool SystemSupportsHardFailRevocationChecking() {
5562#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
5563 return true;
5564#else
5565 return false;
5566#endif
5567}
5568
[email protected]a13234c2012-03-20 21:45:025569// SystemUsesChromiumEVMetadata returns true iff the current operating system
5570// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
5571// several tests are effected because our testing EV certificate won't be
5572// recognised as EV.
5573static bool SystemUsesChromiumEVMetadata() {
[email protected]5c504192012-03-27 19:00:575574#if defined(USE_OPENSSL)
5575 // http://crbug.com/117478 - OpenSSL does not support EV validation.
5576 return false;
[email protected]a592c0432012-12-01 18:10:295577#elif defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]a13234c2012-03-20 21:45:025578 // On OS X, we use the system to tell us whether a certificate is EV or not
5579 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:015580 return false;
5581#else
5582 return true;
5583#endif
5584}
5585
[email protected]b6f2de32012-08-17 04:35:085586static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:575587#if defined(USE_OPENSSL)
5588 // http://crbug.com/117478 - OpenSSL does not support OCSP.
5589 return false;
5590#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:025591 return base::win::GetVersion() >= base::win::VERSION_VISTA;
5592#elif defined(OS_ANDROID)
5593 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
5594 return false;
5595#else
5596 return true;
5597#endif
5598}
5599
[email protected]dffe8242012-03-20 15:14:275600TEST_F(HTTPSOCSPTest, Valid) {
5601 if (!SystemSupportsOCSP()) {
5602 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5603 return;
5604 }
5605
[email protected]ce7d0cbc2013-05-03 18:57:225606 SpawnedTestServer::SSLOptions ssl_options(
5607 SpawnedTestServer::SSLOptions::CERT_AUTO);
5608 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:275609
[email protected]924e9f92012-12-16 22:00:535610 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125611 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:275612
5613 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5614
[email protected]a13234c2012-03-20 21:45:025615 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5616 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:275617
5618 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5619}
5620
5621TEST_F(HTTPSOCSPTest, Revoked) {
5622 if (!SystemSupportsOCSP()) {
5623 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5624 return;
5625 }
5626
[email protected]ce7d0cbc2013-05-03 18:57:225627 SpawnedTestServer::SSLOptions ssl_options(
5628 SpawnedTestServer::SSLOptions::CERT_AUTO);
5629 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:275630
5631 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125632 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:275633
[email protected]a592c0432012-12-01 18:10:295634#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:275635 // Doesn't pass on OS X yet for reasons that need to be investigated.
5636 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
5637#endif
5638 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5639 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5640}
5641
5642TEST_F(HTTPSOCSPTest, Invalid) {
5643 if (!SystemSupportsOCSP()) {
5644 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5645 return;
5646 }
5647
[email protected]ce7d0cbc2013-05-03 18:57:225648 SpawnedTestServer::SSLOptions ssl_options(
5649 SpawnedTestServer::SSLOptions::CERT_AUTO);
5650 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:275651
[email protected]924e9f92012-12-16 22:00:535652 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125653 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:275654
[email protected]a13234c2012-03-20 21:45:025655 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:275656 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:275657
5658 // Without a positive OCSP response, we shouldn't show the EV status.
5659 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5660 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5661}
[email protected]a13234c2012-03-20 21:45:025662
[email protected]3a86a712013-07-30 07:16:205663class HTTPSHardFailTest : public HTTPSOCSPTest {
5664 protected:
5665 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
5666 context->set_ssl_config_service(
5667 new TestSSLConfigService(false /* check for EV */,
5668 false /* online revocation checking */,
5669 true /* require rev. checking for local
5670 anchors */));
5671 }
5672};
5673
5674
5675TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
5676 if (!SystemSupportsOCSP()) {
5677 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5678 return;
5679 }
5680
5681 if (!SystemSupportsHardFailRevocationChecking()) {
5682 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
5683 << "revocation checking";
5684 return;
5685 }
5686
5687 SpawnedTestServer::SSLOptions ssl_options(
5688 SpawnedTestServer::SSLOptions::CERT_AUTO);
5689 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
5690
5691 CertStatus cert_status;
5692 DoConnection(ssl_options, &cert_status);
5693
5694 EXPECT_EQ(CERT_STATUS_REVOKED,
5695 cert_status & CERT_STATUS_REVOKED);
5696
5697 // Without a positive OCSP response, we shouldn't show the EV status.
5698 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5699}
5700
[email protected]a13234c2012-03-20 21:45:025701class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
5702 protected:
5703 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
5704 context->set_ssl_config_service(
5705 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:205706 false /* online revocation checking */,
5707 false /* require rev. checking for local
5708 anchors */));
[email protected]a13234c2012-03-20 21:45:025709 }
5710};
5711
5712TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
5713 if (!SystemSupportsOCSP()) {
5714 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5715 return;
5716 }
5717
[email protected]ce7d0cbc2013-05-03 18:57:225718 SpawnedTestServer::SSLOptions ssl_options(
5719 SpawnedTestServer::SSLOptions::CERT_AUTO);
5720 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:025721 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
5722
[email protected]924e9f92012-12-16 22:00:535723 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125724 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:025725
5726 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
5727 cert_status & CERT_STATUS_ALL_ERRORS);
5728
5729 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:085730 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5731 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:025732}
5733
[email protected]be0fff62013-08-29 23:37:485734TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
5735 if (!SystemSupportsOCSP()) {
5736 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5737 return;
5738 }
5739
5740 SpawnedTestServer::SSLOptions ssl_options(
5741 SpawnedTestServer::SSLOptions::CERT_AUTO);
5742 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
5743 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
5744
5745 CertStatus cert_status;
5746 DoConnection(ssl_options, &cert_status);
5747
5748 // Currently only works for Windows. When using NSS or OS X, it's not
5749 // possible to determine whether the check failed because of actual
5750 // revocation or because there was an OCSP failure.
5751#if defined(OS_WIN)
5752 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
5753#else
5754 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5755#endif
5756
5757 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5758 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5759 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
5760}
5761
[email protected]a13234c2012-03-20 21:45:025762TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
5763 if (!SystemSupportsOCSP()) {
5764 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5765 return;
5766 }
5767
[email protected]ce7d0cbc2013-05-03 18:57:225768 SpawnedTestServer::SSLOptions ssl_options(
5769 SpawnedTestServer::SSLOptions::CERT_AUTO);
5770 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:025771 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
5772
5773 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125774 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:025775
5776 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5777
5778 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5779 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:085780 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5781 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:025782}
5783
5784TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
5785 if (!SystemSupportsOCSP()) {
5786 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5787 return;
5788 }
5789
[email protected]ce7d0cbc2013-05-03 18:57:225790 SpawnedTestServer::SSLOptions ssl_options(
5791 SpawnedTestServer::SSLOptions::CERT_AUTO);
5792 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:025793 SSLConfigService::SetCRLSet(
5794 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
5795
5796 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125797 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:025798
5799 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
5800 cert_status & CERT_STATUS_ALL_ERRORS);
5801
5802 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:085803 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5804 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:025805}
5806
[email protected]51523f52013-07-31 21:57:285807TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
5808 if (!SystemSupportsOCSP()) {
5809 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5810 return;
5811 }
5812
5813 SpawnedTestServer::SSLOptions ssl_options(
5814 SpawnedTestServer::SSLOptions::CERT_AUTO);
5815 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
5816 SSLConfigService::SetCRLSet(
5817 scoped_refptr<CRLSet>(CRLSet::ForTesting(
5818 false, &kOCSPTestCertSPKI, "")));
5819
5820 CertStatus cert_status;
5821 DoConnection(ssl_options, &cert_status);
5822
5823 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
5824 // revocation check for EV.
5825 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5826 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
5827 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
5828 EXPECT_FALSE(
5829 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
5830}
5831
5832TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
5833 if (!SystemSupportsOCSP()) {
5834 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5835 return;
5836 }
5837
[email protected]ce7d0cbc2013-05-03 18:57:225838 SpawnedTestServer::SSLOptions ssl_options(
5839 SpawnedTestServer::SSLOptions::CERT_AUTO);
5840 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:025841 SSLConfigService::SetCRLSet(
5842 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
5843
[email protected]51523f52013-07-31 21:57:285844 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:125845 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:025846
[email protected]51523f52013-07-31 21:57:285847 // Even with a fresh CRLSet, we should still do online revocation checks when
5848 // the certificate chain isn't covered by the CRLSet, which it isn't in this
5849 // test.
5850 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
5851 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:025852
[email protected]51523f52013-07-31 21:57:285853 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:025854 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:285855 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:025856}
5857
[email protected]b6f2de32012-08-17 04:35:085858TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
5859 // Test that when EV verification is requested, but online revocation
5860 // checking is disabled, and the leaf certificate is not in fact EV, that
5861 // no revocation checking actually happens.
5862 if (!SystemSupportsOCSP()) {
5863 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
5864 return;
5865 }
5866
5867 // Unmark the certificate's OID as EV, which should disable revocation
5868 // checking (as per the user preference)
5869 ev_test_policy_.reset();
5870
[email protected]ce7d0cbc2013-05-03 18:57:225871 SpawnedTestServer::SSLOptions ssl_options(
5872 SpawnedTestServer::SSLOptions::CERT_AUTO);
5873 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:085874 SSLConfigService::SetCRLSet(
5875 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
5876
5877 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125878 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:085879
5880 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5881
5882 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5883 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5884}
5885
[email protected]a13234c2012-03-20 21:45:025886class HTTPSCRLSetTest : public HTTPSOCSPTest {
5887 protected:
5888 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
5889 context->set_ssl_config_service(
5890 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:205891 false /* online revocation checking */,
5892 false /* require rev. checking for local
5893 anchors */));
[email protected]a13234c2012-03-20 21:45:025894 }
5895};
5896
5897TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:225898 SpawnedTestServer::SSLOptions ssl_options(
5899 SpawnedTestServer::SSLOptions::CERT_AUTO);
5900 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:025901 SSLConfigService::SetCRLSet(
5902 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
5903
[email protected]924e9f92012-12-16 22:00:535904 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:125905 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:025906
5907 // If we're not trying EV verification then, even if the CRLSet has expired,
5908 // we don't fall back to online revocation checks.
5909 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
5910 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5911 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
5912}
[email protected]51523f52013-07-31 21:57:285913
5914TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
5915#if defined(USE_OPENSSL)
5916 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
5917 return;
5918#endif
5919
5920 SpawnedTestServer::SSLOptions ssl_options(
5921 SpawnedTestServer::SSLOptions::CERT_AUTO);
5922 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
5923 ssl_options.cert_serial = 10;
5924 SSLConfigService::SetCRLSet(
5925 scoped_refptr<CRLSet>(CRLSet::ForTesting(
5926 false, &kOCSPTestCertSPKI, "\x0a")));
5927
5928 CertStatus cert_status = 0;
5929 DoConnection(ssl_options, &cert_status);
5930
5931 // If the certificate is recorded as revoked in the CRLSet, that should be
5932 // reflected without online revocation checking.
5933 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
5934 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
5935 EXPECT_FALSE(
5936 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
5937}
[email protected]316c1e5e2012-09-12 15:17:445938#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:275939
[email protected]316c1e5e2012-09-12 15:17:445940#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:315941class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:115942 public:
[email protected]d9fca99a2012-02-24 16:16:205943 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:225944 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:155945 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:115946 }
5947
[email protected]b89ca032009-08-31 21:41:315948 protected:
[email protected]ce7d0cbc2013-05-03 18:57:225949 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:315950};
5951
[email protected]d2a133182012-08-05 16:44:085952// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:095953TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:085954 ASSERT_TRUE(test_server_.Start());
5955
[email protected]9d5730b2012-08-24 17:42:495956 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:345957 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:085958
5959 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:085960 job_factory.SetProtocolHandler(
5961 "ftp",
[email protected]e0f35c92013-05-08 16:04:345962 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:085963 default_context_.set_job_factory(&job_factory);
5964
5965 TestDelegate d;
5966 {
5967 URLRequest r(url, &d, &default_context_);
5968 r.Start();
5969 EXPECT_TRUE(r.is_pending());
5970
[email protected]255620da2013-08-19 13:14:295971 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:085972
5973 EXPECT_FALSE(r.is_pending());
5974 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5975 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
5976 }
5977}
5978
[email protected]5accf7332009-11-24 03:41:385979// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:125980TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:115981 ASSERT_TRUE(test_server_.Start());
5982
[email protected]a25e90e2009-09-09 17:05:375983 TestDelegate d;
5984 {
[email protected]94e2bbe2012-06-22 15:26:135985 URLRequest r(test_server_.GetURL("/"), &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:375986 r.Start();
5987 EXPECT_TRUE(r.is_pending());
5988
[email protected]255620da2013-08-19 13:14:295989 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:375990
5991 EXPECT_FALSE(r.is_pending());
5992 EXPECT_EQ(1, d.response_started_count());
5993 EXPECT_FALSE(d.received_data_before_response());
5994 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:195995 EXPECT_EQ(test_server_.host_port_pair().host(),
5996 r.GetSocketAddress().host());
5997 EXPECT_EQ(test_server_.host_port_pair().port(),
5998 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:375999 }
6000}
6001
[email protected]7df70012010-02-04 00:09:556002// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126003TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:116004 ASSERT_TRUE(test_server_.Start());
6005
[email protected]6cdfd7f2013-02-08 20:40:156006 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276007 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026008 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276009 TestDelegate d;
6010 {
[email protected]94e2bbe2012-06-22 15:26:136011 URLRequest r(test_server_.GetURL("/LICENSE"), &d, &default_context_);
[email protected]dd265012009-01-08 20:45:276012 r.Start();
6013 EXPECT_TRUE(r.is_pending());
6014
[email protected]255620da2013-08-19 13:14:296015 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276016
6017 int64 file_size = 0;
6018 file_util::GetFileSize(app_path, &file_size);
6019
[email protected]ba2f3342009-07-30 18:08:426020 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276021 EXPECT_EQ(1, d.response_started_count());
6022 EXPECT_FALSE(d.received_data_before_response());
6023 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:196024 EXPECT_EQ(test_server_.host_port_pair().host(),
6025 r.GetSocketAddress().host());
6026 EXPECT_EQ(test_server_.host_port_pair().port(),
6027 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:276028 }
6029}
6030
[email protected]e9ecbd12009-12-20 18:44:406031// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126032TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:116033 ASSERT_TRUE(test_server_.Start());
6034
[email protected]6cdfd7f2013-02-08 20:40:156035 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276036 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026037 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276038 TestDelegate d;
6039 {
[email protected]ef2bf422012-05-11 03:27:096040 URLRequest r(
[email protected]95409e12010-08-17 20:07:116041 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136042 &d,
6043 &default_context_);
[email protected]dd265012009-01-08 20:45:276044 r.Start();
6045 EXPECT_TRUE(r.is_pending());
6046
[email protected]255620da2013-08-19 13:14:296047 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276048
6049 int64 file_size = 0;
6050 file_util::GetFileSize(app_path, &file_size);
6051
[email protected]ba2f3342009-07-30 18:08:426052 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:196053 EXPECT_EQ(test_server_.host_port_pair().host(),
6054 r.GetSocketAddress().host());
6055 EXPECT_EQ(test_server_.host_port_pair().port(),
6056 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:276057 EXPECT_EQ(1, d.response_started_count());
6058 EXPECT_FALSE(d.received_data_before_response());
6059 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:256060
6061 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:176062 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256063 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:276064 }
6065}
6066
[email protected]49abd652010-08-05 05:04:536067// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126068TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:116069 ASSERT_TRUE(test_server_.Start());
6070
[email protected]6cdfd7f2013-02-08 20:40:156071 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276072 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026073 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276074 TestDelegate d;
6075 {
[email protected]ef2bf422012-05-11 03:27:096076 URLRequest r(
[email protected]95409e12010-08-17 20:07:116077 test_server_.GetURLWithUserAndPassword("/LICENSE",
6078 "chrome",
6079 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136080 &d,
6081 &default_context_);
[email protected]dd265012009-01-08 20:45:276082 r.Start();
6083 EXPECT_TRUE(r.is_pending());
6084
[email protected]255620da2013-08-19 13:14:296085 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276086
6087 int64 file_size = 0;
6088 file_util::GetFileSize(app_path, &file_size);
6089
[email protected]ba2f3342009-07-30 18:08:426090 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276091 EXPECT_EQ(1, d.response_started_count());
6092 EXPECT_FALSE(d.received_data_before_response());
6093 EXPECT_EQ(d.bytes_received(), 0);
6094 }
6095}
6096
[email protected]cde4e80d2009-10-16 19:58:156097// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126098TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:116099 ASSERT_TRUE(test_server_.Start());
6100
[email protected]6cdfd7f2013-02-08 20:40:156101 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:586102 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6103 app_path = app_path.AppendASCII("LICENSE");
6104 TestDelegate d;
6105 // Set correct login credentials. The delegate will be asked for them when
6106 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586107 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:586108 {
[email protected]ef2bf422012-05-11 03:27:096109 URLRequest r(
[email protected]95409e12010-08-17 20:07:116110 test_server_.GetURLWithUserAndPassword("/LICENSE",
6111 "chrome",
6112 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136113 &d,
6114 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:586115 r.Start();
6116 EXPECT_TRUE(r.is_pending());
6117
[email protected]255620da2013-08-19 13:14:296118 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:586119
6120 int64 file_size = 0;
6121 file_util::GetFileSize(app_path, &file_size);
6122
6123 EXPECT_FALSE(r.is_pending());
6124 EXPECT_EQ(1, d.response_started_count());
6125 EXPECT_FALSE(d.received_data_before_response());
6126 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
6127 }
6128}
6129
[email protected]49abd652010-08-05 05:04:536130// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126131TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:116132 ASSERT_TRUE(test_server_.Start());
6133
[email protected]6cdfd7f2013-02-08 20:40:156134 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276135 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026136 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276137 TestDelegate d;
6138 {
[email protected]ef2bf422012-05-11 03:27:096139 URLRequest r(
[email protected]95409e12010-08-17 20:07:116140 test_server_.GetURLWithUserAndPassword("/LICENSE",
6141 "wrong_user",
6142 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136143 &d,
6144 &default_context_);
[email protected]dd265012009-01-08 20:45:276145 r.Start();
6146 EXPECT_TRUE(r.is_pending());
6147
[email protected]255620da2013-08-19 13:14:296148 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276149
6150 int64 file_size = 0;
6151 file_util::GetFileSize(app_path, &file_size);
6152
[email protected]ba2f3342009-07-30 18:08:426153 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276154 EXPECT_EQ(1, d.response_started_count());
6155 EXPECT_FALSE(d.received_data_before_response());
6156 EXPECT_EQ(d.bytes_received(), 0);
6157 }
6158}
[email protected]8b8a197d2009-08-26 15:57:586159
[email protected]cde4e80d2009-10-16 19:58:156160// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126161TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:116162 ASSERT_TRUE(test_server_.Start());
6163
[email protected]6cdfd7f2013-02-08 20:40:156164 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:586165 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6166 app_path = app_path.AppendASCII("LICENSE");
6167 TestDelegate d;
6168 // Set correct login credentials. The delegate will be asked for them when
6169 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586170 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:586171 {
[email protected]ef2bf422012-05-11 03:27:096172 URLRequest r(
[email protected]95409e12010-08-17 20:07:116173 test_server_.GetURLWithUserAndPassword("/LICENSE",
6174 "wrong_user",
6175 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136176 &d,
6177 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:586178 r.Start();
6179 EXPECT_TRUE(r.is_pending());
6180
[email protected]255620da2013-08-19 13:14:296181 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:586182
6183 int64 file_size = 0;
6184 file_util::GetFileSize(app_path, &file_size);
6185
6186 EXPECT_FALSE(r.is_pending());
6187 EXPECT_EQ(1, d.response_started_count());
6188 EXPECT_FALSE(d.received_data_before_response());
6189 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
6190 }
6191}
[email protected]60a3df52009-09-22 16:13:246192
[email protected]cde4e80d2009-10-16 19:58:156193// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126194TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:116195 ASSERT_TRUE(test_server_.Start());
6196
[email protected]6cdfd7f2013-02-08 20:40:156197 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:246198 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6199 app_path = app_path.AppendASCII("LICENSE");
6200
6201 scoped_ptr<TestDelegate> d(new TestDelegate);
6202 {
6203 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:096204 URLRequest r(
[email protected]95409e12010-08-17 20:07:116205 test_server_.GetURLWithUserAndPassword("/LICENSE",
6206 "chrome",
6207 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136208 d.get(),
6209 &default_context_);
[email protected]60a3df52009-09-22 16:13:246210 r.Start();
6211 EXPECT_TRUE(r.is_pending());
6212
[email protected]255620da2013-08-19 13:14:296213 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246214
6215 int64 file_size = 0;
6216 file_util::GetFileSize(app_path, &file_size);
6217
6218 EXPECT_FALSE(r.is_pending());
6219 EXPECT_EQ(1, d->response_started_count());
6220 EXPECT_FALSE(d->received_data_before_response());
6221 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6222 }
6223
6224 d.reset(new TestDelegate);
6225 {
6226 // This request should use cached identity from previous request.
[email protected]94e2bbe2012-06-22 15:26:136227 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:246228 r.Start();
6229 EXPECT_TRUE(r.is_pending());
6230
[email protected]255620da2013-08-19 13:14:296231 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246232
6233 int64 file_size = 0;
6234 file_util::GetFileSize(app_path, &file_size);
6235
6236 EXPECT_FALSE(r.is_pending());
6237 EXPECT_EQ(1, d->response_started_count());
6238 EXPECT_FALSE(d->received_data_before_response());
6239 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6240 }
6241}
6242
[email protected]cde4e80d2009-10-16 19:58:156243// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126244TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:116245 ASSERT_TRUE(test_server_.Start());
6246
[email protected]6cdfd7f2013-02-08 20:40:156247 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:246248 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6249 app_path = app_path.AppendASCII("LICENSE");
6250
6251 scoped_ptr<TestDelegate> d(new TestDelegate);
6252 // Set correct login credentials. The delegate will be asked for them when
6253 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586254 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:246255 {
[email protected]ef2bf422012-05-11 03:27:096256 URLRequest r(
[email protected]95409e12010-08-17 20:07:116257 test_server_.GetURLWithUserAndPassword("/LICENSE",
6258 "chrome",
6259 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136260 d.get(),
6261 &default_context_);
[email protected]60a3df52009-09-22 16:13:246262 r.Start();
6263 EXPECT_TRUE(r.is_pending());
6264
[email protected]255620da2013-08-19 13:14:296265 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246266
6267 int64 file_size = 0;
6268 file_util::GetFileSize(app_path, &file_size);
6269
6270 EXPECT_FALSE(r.is_pending());
6271 EXPECT_EQ(1, d->response_started_count());
6272 EXPECT_FALSE(d->received_data_before_response());
6273 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6274 }
6275
6276 // Use a new delegate without explicit credentials. The cached ones should be
6277 // used.
6278 d.reset(new TestDelegate);
6279 {
6280 // Don't pass wrong credentials in the URL, they would override valid cached
6281 // ones.
[email protected]94e2bbe2012-06-22 15:26:136282 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:246283 r.Start();
6284 EXPECT_TRUE(r.is_pending());
6285
[email protected]255620da2013-08-19 13:14:296286 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246287
6288 int64 file_size = 0;
6289 file_util::GetFileSize(app_path, &file_size);
6290
6291 EXPECT_FALSE(r.is_pending());
6292 EXPECT_EQ(1, d->response_started_count());
6293 EXPECT_FALSE(d->received_data_before_response());
6294 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6295 }
6296}
[email protected]316c1e5e2012-09-12 15:17:446297#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:516298
6299} // namespace net