blob: 08aa1b15e277ef30bc889e182bdc1ea8e89d764f [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
[email protected]5f9581402013-10-30 13:08:32947TEST_F(URLRequestTest, FileDirOutputSanity) {
948 // Verify the general sanity of the the output of the file:
949 // directory lister by checking for the output of a known existing
950 // file.
951 const char sentinel_name[] = "filedir-sentinel";
952
953 base::FilePath path;
954 PathService::Get(base::DIR_SOURCE_ROOT, &path);
955 path = path.Append(FILE_PATH_LITERAL("net"));
956 path = path.Append(FILE_PATH_LITERAL("data"));
957 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
958
959 TestDelegate d;
960 URLRequest req(FilePathToFileURL(path), &d, &default_context_);
961 req.Start();
962 base::RunLoop().Run();
963
964 // Generate entry for the sentinel file.
965 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
966 base::PlatformFileInfo info;
967 EXPECT_TRUE(file_util::GetFileInfo(sentinel_path, &info));
968 EXPECT_GT(info.size, 0);
969 std::string sentinel_output = GetDirectoryListingEntry(
970 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
971 std::string(sentinel_name),
972 false /* is_dir */,
973 info.size,
974 info.last_modified);
975
976 ASSERT_LT(0, d.bytes_received());
977 ASSERT_FALSE(d.request_failed());
978 ASSERT_TRUE(req.status().is_success());
979 // Check for the entry generated for the "sentinel" file.
980 const std::string& data = d.data_received();
981 ASSERT_NE(data.find(sentinel_output), std::string::npos);
982}
983
[email protected]316c1e5e2012-09-12 15:17:44984TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
985 // There is an implicit redirect when loading a file path that matches a
986 // directory and does not end with a slash. Ensure that following such
987 // redirects does not crash. See http://crbug.com/18686.
988
[email protected]6cdfd7f2013-02-08 20:40:15989 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:44990 PathService::Get(base::DIR_SOURCE_ROOT, &path);
991 path = path.Append(FILE_PATH_LITERAL("net"));
992 path = path.Append(FILE_PATH_LITERAL("data"));
993 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
994
995 TestDelegate d;
996 URLRequest req(FilePathToFileURL(path), &d, &default_context_);
997 req.Start();
[email protected]255620da2013-08-19 13:14:29998 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:44999
1000 ASSERT_EQ(1, d.received_redirect_count());
1001 ASSERT_LT(0, d.bytes_received());
1002 ASSERT_FALSE(d.request_failed());
1003 ASSERT_TRUE(req.status().is_success());
1004}
1005
1006#if defined(OS_WIN)
1007// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1008TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1009 TestDelegate d;
1010 URLRequest req(GURL("file:///"), &d, &default_context_);
1011 req.Start();
[email protected]255620da2013-08-19 13:14:291012 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441013
1014 ASSERT_EQ(1, d.received_redirect_count());
1015 ASSERT_FALSE(req.status().is_success());
1016}
1017#endif
1018
1019// Custom URLRequestJobs for use with interceptor tests
1020class RestartTestJob : public URLRequestTestJob {
1021 public:
1022 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1023 : URLRequestTestJob(request, network_delegate, true) {}
1024 protected:
[email protected]46fadfd2013-02-06 09:40:161025 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441026 this->NotifyRestartRequired();
1027 }
1028 private:
[email protected]46fadfd2013-02-06 09:40:161029 virtual ~RestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441030};
1031
1032class CancelTestJob : public URLRequestTestJob {
1033 public:
1034 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1035 : URLRequestTestJob(request, network_delegate, true) {}
1036 protected:
[email protected]46fadfd2013-02-06 09:40:161037 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441038 request_->Cancel();
1039 }
1040 private:
[email protected]46fadfd2013-02-06 09:40:161041 virtual ~CancelTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441042};
1043
1044class CancelThenRestartTestJob : public URLRequestTestJob {
1045 public:
1046 explicit CancelThenRestartTestJob(URLRequest* request,
1047 NetworkDelegate* network_delegate)
1048 : URLRequestTestJob(request, network_delegate, true) {
1049 }
1050 protected:
[email protected]46fadfd2013-02-06 09:40:161051 virtual void StartAsync() OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441052 request_->Cancel();
1053 this->NotifyRestartRequired();
1054 }
1055 private:
[email protected]46fadfd2013-02-06 09:40:161056 virtual ~CancelThenRestartTestJob() {}
[email protected]316c1e5e2012-09-12 15:17:441057};
1058
1059// An Interceptor for use with interceptor tests
1060class TestInterceptor : URLRequest::Interceptor {
1061 public:
1062 TestInterceptor()
1063 : intercept_main_request_(false), restart_main_request_(false),
1064 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1065 simulate_main_network_error_(false),
1066 intercept_redirect_(false), cancel_redirect_request_(false),
1067 intercept_final_response_(false), cancel_final_request_(false),
1068 did_intercept_main_(false), did_restart_main_(false),
1069 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1070 did_simulate_error_main_(false),
1071 did_intercept_redirect_(false), did_cancel_redirect_(false),
1072 did_intercept_final_(false), did_cancel_final_(false) {
1073 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1074 }
1075
[email protected]46fadfd2013-02-06 09:40:161076 virtual ~TestInterceptor() {
[email protected]316c1e5e2012-09-12 15:17:441077 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1078 }
1079
[email protected]46fadfd2013-02-06 09:40:161080 virtual URLRequestJob* MaybeIntercept(
1081 URLRequest* request,
1082 NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441083 if (restart_main_request_) {
1084 restart_main_request_ = false;
1085 did_restart_main_ = true;
1086 return new RestartTestJob(request, network_delegate);
1087 }
1088 if (cancel_main_request_) {
1089 cancel_main_request_ = false;
1090 did_cancel_main_ = true;
1091 return new CancelTestJob(request, network_delegate);
1092 }
1093 if (cancel_then_restart_main_request_) {
1094 cancel_then_restart_main_request_ = false;
1095 did_cancel_then_restart_main_ = true;
1096 return new CancelThenRestartTestJob(request, network_delegate);
1097 }
1098 if (simulate_main_network_error_) {
1099 simulate_main_network_error_ = false;
1100 did_simulate_error_main_ = true;
1101 // will error since the requeted url is not one of its canned urls
1102 return new URLRequestTestJob(request, network_delegate, true);
1103 }
1104 if (!intercept_main_request_)
1105 return NULL;
1106 intercept_main_request_ = false;
1107 did_intercept_main_ = true;
[email protected]2bba3252013-04-08 19:50:591108 URLRequestTestJob* job = new URLRequestTestJob(request,
1109 network_delegate,
1110 main_headers_,
1111 main_data_,
1112 true);
1113 job->set_load_timing_info(main_request_load_timing_info_);
1114 return job;
[email protected]316c1e5e2012-09-12 15:17:441115 }
1116
1117 virtual URLRequestJob* MaybeInterceptRedirect(
1118 URLRequest* request,
1119 NetworkDelegate* network_delegate,
[email protected]46fadfd2013-02-06 09:40:161120 const GURL& location) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441121 if (cancel_redirect_request_) {
1122 cancel_redirect_request_ = false;
1123 did_cancel_redirect_ = true;
1124 return new CancelTestJob(request, network_delegate);
1125 }
1126 if (!intercept_redirect_)
1127 return NULL;
1128 intercept_redirect_ = false;
1129 did_intercept_redirect_ = true;
1130 return new URLRequestTestJob(request,
1131 network_delegate,
1132 redirect_headers_,
1133 redirect_data_,
1134 true);
1135 }
1136
1137 virtual URLRequestJob* MaybeInterceptResponse(
[email protected]46fadfd2013-02-06 09:40:161138 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:441139 if (cancel_final_request_) {
1140 cancel_final_request_ = false;
1141 did_cancel_final_ = true;
1142 return new CancelTestJob(request, network_delegate);
1143 }
1144 if (!intercept_final_response_)
1145 return NULL;
1146 intercept_final_response_ = false;
1147 did_intercept_final_ = true;
1148 return new URLRequestTestJob(request,
1149 network_delegate,
1150 final_headers_,
1151 final_data_,
1152 true);
1153 }
1154
[email protected]2bba3252013-04-08 19:50:591155 // Whether to intercept the main request, and if so the response to return and
1156 // the LoadTimingInfo to use.
[email protected]316c1e5e2012-09-12 15:17:441157 bool intercept_main_request_;
1158 std::string main_headers_;
1159 std::string main_data_;
[email protected]2bba3252013-04-08 19:50:591160 LoadTimingInfo main_request_load_timing_info_;
[email protected]316c1e5e2012-09-12 15:17:441161
1162 // Other actions we take at MaybeIntercept time
1163 bool restart_main_request_;
1164 bool cancel_main_request_;
1165 bool cancel_then_restart_main_request_;
1166 bool simulate_main_network_error_;
1167
1168 // Whether to intercept redirects, and if so the response to return.
1169 bool intercept_redirect_;
1170 std::string redirect_headers_;
1171 std::string redirect_data_;
1172
1173 // Other actions we can take at MaybeInterceptRedirect time
1174 bool cancel_redirect_request_;
1175
1176 // Whether to intercept final response, and if so the response to return.
1177 bool intercept_final_response_;
1178 std::string final_headers_;
1179 std::string final_data_;
1180
1181 // Other actions we can take at MaybeInterceptResponse time
1182 bool cancel_final_request_;
1183
1184 // If we did something or not
1185 bool did_intercept_main_;
1186 bool did_restart_main_;
1187 bool did_cancel_main_;
1188 bool did_cancel_then_restart_main_;
1189 bool did_simulate_error_main_;
1190 bool did_intercept_redirect_;
1191 bool did_cancel_redirect_;
1192 bool did_intercept_final_;
1193 bool did_cancel_final_;
1194
1195 // Static getters for canned response header and data strings
1196
1197 static std::string ok_data() {
1198 return URLRequestTestJob::test_data_1();
1199 }
1200
1201 static std::string ok_headers() {
1202 return URLRequestTestJob::test_headers();
1203 }
1204
1205 static std::string redirect_data() {
1206 return std::string();
1207 }
1208
1209 static std::string redirect_headers() {
1210 return URLRequestTestJob::test_redirect_headers();
1211 }
1212
1213 static std::string error_data() {
1214 return std::string("ohhh nooooo mr. bill!");
1215 }
1216
1217 static std::string error_headers() {
1218 return URLRequestTestJob::test_error_headers();
1219 }
1220};
1221
1222TEST_F(URLRequestTest, Intercept) {
1223 TestInterceptor interceptor;
1224
1225 // intercept the main request and respond with a simple response
1226 interceptor.intercept_main_request_ = true;
1227 interceptor.main_headers_ = TestInterceptor::ok_headers();
1228 interceptor.main_data_ = TestInterceptor::ok_data();
1229
1230 TestDelegate d;
1231 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1232 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1233 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1234 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1235 req.SetUserData(NULL, user_data0);
1236 req.SetUserData(&user_data1, user_data1);
1237 req.SetUserData(&user_data2, user_data2);
1238 req.set_method("GET");
1239 req.Start();
[email protected]255620da2013-08-19 13:14:291240 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441241
1242 // Make sure we can retrieve our specific user data
1243 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1244 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1245 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1246
1247 // Check the interceptor got called as expected
1248 EXPECT_TRUE(interceptor.did_intercept_main_);
1249
1250 // Check we got one good response
1251 EXPECT_TRUE(req.status().is_success());
1252 EXPECT_EQ(200, req.response_headers()->response_code());
1253 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1254 EXPECT_EQ(1, d.response_started_count());
1255 EXPECT_EQ(0, d.received_redirect_count());
1256}
1257
1258TEST_F(URLRequestTest, InterceptRedirect) {
1259 TestInterceptor interceptor;
1260
1261 // intercept the main request and respond with a redirect
1262 interceptor.intercept_main_request_ = true;
1263 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1264 interceptor.main_data_ = TestInterceptor::redirect_data();
1265
1266 // intercept that redirect and respond a final OK response
1267 interceptor.intercept_redirect_ = true;
1268 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1269 interceptor.redirect_data_ = TestInterceptor::ok_data();
1270
1271 TestDelegate d;
1272 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1273 req.set_method("GET");
1274 req.Start();
[email protected]255620da2013-08-19 13:14:291275 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441276
1277 // Check the interceptor got called as expected
1278 EXPECT_TRUE(interceptor.did_intercept_main_);
1279 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1280
1281 // Check we got one good response
1282 EXPECT_TRUE(req.status().is_success());
1283 if (req.status().is_success()) {
1284 EXPECT_EQ(200, req.response_headers()->response_code());
1285 }
1286 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1287 EXPECT_EQ(1, d.response_started_count());
1288 EXPECT_EQ(0, d.received_redirect_count());
1289}
1290
1291TEST_F(URLRequestTest, InterceptServerError) {
1292 TestInterceptor interceptor;
1293
1294 // intercept the main request to generate a server error response
1295 interceptor.intercept_main_request_ = true;
1296 interceptor.main_headers_ = TestInterceptor::error_headers();
1297 interceptor.main_data_ = TestInterceptor::error_data();
1298
1299 // intercept that error and respond with an OK response
1300 interceptor.intercept_final_response_ = true;
1301 interceptor.final_headers_ = TestInterceptor::ok_headers();
1302 interceptor.final_data_ = TestInterceptor::ok_data();
1303
1304 TestDelegate d;
1305 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1306 req.set_method("GET");
1307 req.Start();
[email protected]255620da2013-08-19 13:14:291308 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441309
1310 // Check the interceptor got called as expected
1311 EXPECT_TRUE(interceptor.did_intercept_main_);
1312 EXPECT_TRUE(interceptor.did_intercept_final_);
1313
1314 // Check we got one good response
1315 EXPECT_TRUE(req.status().is_success());
1316 EXPECT_EQ(200, req.response_headers()->response_code());
1317 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1318 EXPECT_EQ(1, d.response_started_count());
1319 EXPECT_EQ(0, d.received_redirect_count());
1320}
1321
1322TEST_F(URLRequestTest, InterceptNetworkError) {
1323 TestInterceptor interceptor;
1324
1325 // intercept the main request to simulate a network error
1326 interceptor.simulate_main_network_error_ = true;
1327
1328 // intercept that error and respond with an OK response
1329 interceptor.intercept_final_response_ = true;
1330 interceptor.final_headers_ = TestInterceptor::ok_headers();
1331 interceptor.final_data_ = TestInterceptor::ok_data();
1332
1333 TestDelegate d;
1334 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1335 req.set_method("GET");
1336 req.Start();
[email protected]255620da2013-08-19 13:14:291337 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441338
1339 // Check the interceptor got called as expected
1340 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1341 EXPECT_TRUE(interceptor.did_intercept_final_);
1342
1343 // Check we received one good response
1344 EXPECT_TRUE(req.status().is_success());
1345 EXPECT_EQ(200, req.response_headers()->response_code());
1346 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1347 EXPECT_EQ(1, d.response_started_count());
1348 EXPECT_EQ(0, d.received_redirect_count());
1349}
1350
1351TEST_F(URLRequestTest, InterceptRestartRequired) {
1352 TestInterceptor interceptor;
1353
1354 // restart the main request
1355 interceptor.restart_main_request_ = true;
1356
1357 // then intercept the new main request and respond with an OK response
1358 interceptor.intercept_main_request_ = true;
1359 interceptor.main_headers_ = TestInterceptor::ok_headers();
1360 interceptor.main_data_ = TestInterceptor::ok_data();
1361
1362 TestDelegate d;
1363 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1364 req.set_method("GET");
1365 req.Start();
[email protected]255620da2013-08-19 13:14:291366 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441367
1368 // Check the interceptor got called as expected
1369 EXPECT_TRUE(interceptor.did_restart_main_);
1370 EXPECT_TRUE(interceptor.did_intercept_main_);
1371
1372 // Check we received one good response
1373 EXPECT_TRUE(req.status().is_success());
1374 if (req.status().is_success()) {
1375 EXPECT_EQ(200, req.response_headers()->response_code());
1376 }
1377 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1378 EXPECT_EQ(1, d.response_started_count());
1379 EXPECT_EQ(0, d.received_redirect_count());
1380}
1381
1382TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1383 TestInterceptor interceptor;
1384
1385 // intercept the main request and cancel from within the restarted job
1386 interceptor.cancel_main_request_ = true;
1387
1388 // setup to intercept final response and override it with an OK response
1389 interceptor.intercept_final_response_ = true;
1390 interceptor.final_headers_ = TestInterceptor::ok_headers();
1391 interceptor.final_data_ = TestInterceptor::ok_data();
1392
1393 TestDelegate d;
1394 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1395 req.set_method("GET");
1396 req.Start();
[email protected]255620da2013-08-19 13:14:291397 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441398
1399 // Check the interceptor got called as expected
1400 EXPECT_TRUE(interceptor.did_cancel_main_);
1401 EXPECT_FALSE(interceptor.did_intercept_final_);
1402
1403 // Check we see a canceled request
1404 EXPECT_FALSE(req.status().is_success());
1405 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1406}
1407
1408TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1409 TestInterceptor interceptor;
1410
1411 // intercept the main request and respond with a redirect
1412 interceptor.intercept_main_request_ = true;
1413 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1414 interceptor.main_data_ = TestInterceptor::redirect_data();
1415
1416 // intercept the redirect and cancel from within that job
1417 interceptor.cancel_redirect_request_ = true;
1418
1419 // setup to intercept final response and override it with an OK response
1420 interceptor.intercept_final_response_ = true;
1421 interceptor.final_headers_ = TestInterceptor::ok_headers();
1422 interceptor.final_data_ = TestInterceptor::ok_data();
1423
1424 TestDelegate d;
1425 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1426 req.set_method("GET");
1427 req.Start();
[email protected]255620da2013-08-19 13:14:291428 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441429
1430 // Check the interceptor got called as expected
1431 EXPECT_TRUE(interceptor.did_intercept_main_);
1432 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1433 EXPECT_FALSE(interceptor.did_intercept_final_);
1434
1435 // Check we see a canceled request
1436 EXPECT_FALSE(req.status().is_success());
1437 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1438}
1439
1440TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1441 TestInterceptor interceptor;
1442
1443 // intercept the main request to simulate a network error
1444 interceptor.simulate_main_network_error_ = true;
1445
1446 // setup to intercept final response and cancel from within that job
1447 interceptor.cancel_final_request_ = true;
1448
1449 TestDelegate d;
1450 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1451 req.set_method("GET");
1452 req.Start();
[email protected]255620da2013-08-19 13:14:291453 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441454
1455 // Check the interceptor got called as expected
1456 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1457 EXPECT_TRUE(interceptor.did_cancel_final_);
1458
1459 // Check we see a canceled request
1460 EXPECT_FALSE(req.status().is_success());
1461 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1462}
1463
1464TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1465 TestInterceptor interceptor;
1466
1467 // intercept the main request and cancel then restart from within that job
1468 interceptor.cancel_then_restart_main_request_ = true;
1469
1470 // setup to intercept final response and override it with an OK response
1471 interceptor.intercept_final_response_ = true;
1472 interceptor.final_headers_ = TestInterceptor::ok_headers();
1473 interceptor.final_data_ = TestInterceptor::ok_data();
1474
1475 TestDelegate d;
1476 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1477 req.set_method("GET");
1478 req.Start();
[email protected]255620da2013-08-19 13:14:291479 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441480
1481 // Check the interceptor got called as expected
1482 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1483 EXPECT_FALSE(interceptor.did_intercept_final_);
1484
1485 // Check we see a canceled request
1486 EXPECT_FALSE(req.status().is_success());
1487 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1488}
1489
[email protected]2bba3252013-04-08 19:50:591490LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1491 URLRequestContext* context) {
1492 TestInterceptor interceptor;
1493 interceptor.intercept_main_request_ = true;
1494 interceptor.main_request_load_timing_info_ = job_load_timing;
1495 TestDelegate d;
1496 URLRequest req(GURL("http://test_intercept/foo"), &d, context);
1497 req.Start();
[email protected]255620da2013-08-19 13:14:291498 base::RunLoop().Run();
[email protected]2bba3252013-04-08 19:50:591499
1500 LoadTimingInfo resulting_load_timing;
1501 req.GetLoadTimingInfo(&resulting_load_timing);
1502
1503 // None of these should be modified by the URLRequest.
1504 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1505 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1506 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1507 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1508 EXPECT_EQ(job_load_timing.receive_headers_end,
1509 resulting_load_timing.receive_headers_end);
1510
1511 return resulting_load_timing;
1512}
1513
1514// "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1515// reused. |connect_time_flags| is used to indicate if there should be dns
1516// or SSL times, and |used_proxy| is used for proxy times.
1517LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1518 int connect_time_flags,
1519 bool used_proxy) {
1520 LoadTimingInfo load_timing;
1521 load_timing.socket_log_id = 1;
1522
1523 if (used_proxy) {
1524 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1525 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1526 }
1527
1528 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1529 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1530 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1531 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1532 }
1533 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1534 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1535 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1536 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1537 }
1538 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1539
1540 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1541 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1542 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1543 return load_timing;
1544}
1545
1546// Same as above, but in the case of a reused socket.
1547LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1548 bool used_proxy) {
1549 LoadTimingInfo load_timing;
1550 load_timing.socket_log_id = 1;
1551 load_timing.socket_reused = true;
1552
1553 if (used_proxy) {
1554 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1555 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1556 }
1557
1558 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1559 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1560 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1561 return load_timing;
1562}
1563
1564// Basic test that the intercept + load timing tests work.
1565TEST_F(URLRequestTest, InterceptLoadTiming) {
1566 base::TimeTicks now = base::TimeTicks::Now();
1567 LoadTimingInfo job_load_timing =
1568 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1569
1570 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1571 &default_context_);
1572
1573 // Nothing should have been changed by the URLRequest.
1574 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1575 load_timing_result.proxy_resolve_start);
1576 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1577 load_timing_result.proxy_resolve_end);
1578 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1579 load_timing_result.connect_timing.dns_start);
1580 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1581 load_timing_result.connect_timing.dns_end);
1582 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1583 load_timing_result.connect_timing.connect_start);
1584 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1585 load_timing_result.connect_timing.connect_end);
1586 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1587 load_timing_result.connect_timing.ssl_start);
1588 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1589 load_timing_result.connect_timing.ssl_end);
1590
1591 // Redundant sanity check.
1592 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1593}
1594
1595// Another basic test, with proxy and SSL times, but no DNS times.
1596TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1597 base::TimeTicks now = base::TimeTicks::Now();
1598 LoadTimingInfo job_load_timing =
1599 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1600
1601 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1602 &default_context_);
1603
1604 // Nothing should have been changed by the URLRequest.
1605 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1606 load_timing_result.proxy_resolve_start);
1607 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1608 load_timing_result.proxy_resolve_end);
1609 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1610 load_timing_result.connect_timing.dns_start);
1611 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1612 load_timing_result.connect_timing.dns_end);
1613 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1614 load_timing_result.connect_timing.connect_start);
1615 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1616 load_timing_result.connect_timing.connect_end);
1617 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1618 load_timing_result.connect_timing.ssl_start);
1619 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1620 load_timing_result.connect_timing.ssl_end);
1621
1622 // Redundant sanity check.
1623 TestLoadTimingNotReusedWithProxy(load_timing_result,
1624 CONNECT_TIMING_HAS_SSL_TIMES);
1625}
1626
1627// Make sure that URLRequest correctly adjusts proxy times when they're before
1628// |request_start|, due to already having a connected socket. This happens in
1629// the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1630// not considered reused in this test (May be a preconnect).
1631//
1632// To mix things up from the test above, assumes DNS times but no SSL times.
1633TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1634 base::TimeTicks now = base::TimeTicks::Now();
1635 LoadTimingInfo job_load_timing =
1636 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1637 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1638 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1639 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1640 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1641 job_load_timing.connect_timing.connect_start =
1642 now - base::TimeDelta::FromDays(2);
1643 job_load_timing.connect_timing.connect_end =
1644 now - base::TimeDelta::FromDays(1);
1645
1646 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1647 &default_context_);
1648
1649 // Proxy times, connect times, and DNS times should all be replaced with
1650 // request_start.
1651 EXPECT_EQ(load_timing_result.request_start,
1652 load_timing_result.proxy_resolve_start);
1653 EXPECT_EQ(load_timing_result.request_start,
1654 load_timing_result.proxy_resolve_end);
1655 EXPECT_EQ(load_timing_result.request_start,
1656 load_timing_result.connect_timing.dns_start);
1657 EXPECT_EQ(load_timing_result.request_start,
1658 load_timing_result.connect_timing.dns_end);
1659 EXPECT_EQ(load_timing_result.request_start,
1660 load_timing_result.connect_timing.connect_start);
1661 EXPECT_EQ(load_timing_result.request_start,
1662 load_timing_result.connect_timing.connect_end);
1663
1664 // Other times should have been left null.
1665 TestLoadTimingNotReusedWithProxy(load_timing_result,
1666 CONNECT_TIMING_HAS_DNS_TIMES);
1667}
1668
1669// Same as above, but in the reused case.
1670TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1671 base::TimeTicks now = base::TimeTicks::Now();
1672 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1673 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1674 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1675
1676 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1677 &default_context_);
1678
1679 // Proxy times and connect times should all be replaced with request_start.
1680 EXPECT_EQ(load_timing_result.request_start,
1681 load_timing_result.proxy_resolve_start);
1682 EXPECT_EQ(load_timing_result.request_start,
1683 load_timing_result.proxy_resolve_end);
1684
1685 // Other times should have been left null.
1686 TestLoadTimingReusedWithProxy(load_timing_result);
1687}
1688
1689// Make sure that URLRequest correctly adjusts connect times when they're before
1690// |request_start|, due to reusing a connected socket. The connected socket is
1691// not considered reused in this test (May be a preconnect).
1692//
1693// To mix things up, the request has SSL times, but no DNS times.
1694TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1695 base::TimeTicks now = base::TimeTicks::Now();
1696 LoadTimingInfo job_load_timing =
1697 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1698 job_load_timing.connect_timing.connect_start =
1699 now - base::TimeDelta::FromDays(1);
1700 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1701 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1702 job_load_timing.connect_timing.connect_end =
1703 now - base::TimeDelta::FromDays(4);
1704
1705 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1706 &default_context_);
1707
1708 // Connect times, and SSL times should be replaced with request_start.
1709 EXPECT_EQ(load_timing_result.request_start,
1710 load_timing_result.connect_timing.connect_start);
1711 EXPECT_EQ(load_timing_result.request_start,
1712 load_timing_result.connect_timing.ssl_start);
1713 EXPECT_EQ(load_timing_result.request_start,
1714 load_timing_result.connect_timing.ssl_end);
1715 EXPECT_EQ(load_timing_result.request_start,
1716 load_timing_result.connect_timing.connect_end);
1717
1718 // Other times should have been left null.
1719 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1720}
1721
1722// Make sure that URLRequest correctly adjusts connect times when they're before
1723// |request_start|, due to reusing a connected socket in the case that there
1724// are also proxy times. The connected socket is not considered reused in this
1725// test (May be a preconnect).
1726//
1727// In this test, there are no SSL or DNS times.
1728TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1729 base::TimeTicks now = base::TimeTicks::Now();
1730 LoadTimingInfo job_load_timing =
1731 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1732 job_load_timing.connect_timing.connect_start =
1733 now - base::TimeDelta::FromDays(1);
1734 job_load_timing.connect_timing.connect_end =
1735 now - base::TimeDelta::FromDays(2);
1736
1737 LoadTimingInfo load_timing_result = RunLoadTimingTest(job_load_timing,
1738 &default_context_);
1739
1740 // Connect times should be replaced with proxy_resolve_end.
1741 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1742 load_timing_result.connect_timing.connect_start);
1743 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1744 load_timing_result.connect_timing.connect_end);
1745
1746 // Other times should have been left null.
1747 TestLoadTimingNotReusedWithProxy(load_timing_result,
1748 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1749}
1750
[email protected]316c1e5e2012-09-12 15:17:441751// Check that two different URL requests have different identifiers.
1752TEST_F(URLRequestTest, Identifiers) {
1753 TestDelegate d;
1754 TestURLRequestContext context;
[email protected]cc05edc2013-03-08 18:04:411755 TestURLRequest req(GURL("http://example.com"), &d, &context, NULL);
1756 TestURLRequest other_req(GURL("http://example.com"), &d, &context, NULL);
[email protected]316c1e5e2012-09-12 15:17:441757
1758 ASSERT_NE(req.identifier(), other_req.identifier());
1759}
1760
1761// Check that a failure to connect to the proxy is reported to the network
1762// delegate.
1763TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1764 MockHostResolver host_resolver;
1765 host_resolver.rules()->AddSimulatedFailure("*");
1766
[email protected]ceefd7fd2012-11-29 00:36:241767 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:441768 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1769
1770 TestDelegate d;
1771 URLRequest req(GURL("http://example.com"), &d, &context);
1772 req.set_method("GET");
1773
1774 req.Start();
[email protected]255620da2013-08-19 13:14:291775 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441776
1777 // Check we see a failed request.
1778 EXPECT_FALSE(req.status().is_success());
1779 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1780 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1781
1782 EXPECT_EQ(1, network_delegate.error_count());
1783 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1784 EXPECT_EQ(1, network_delegate.completed_requests());
1785}
1786
1787// Make sure that net::NetworkDelegate::NotifyCompleted is called if
1788// content is empty.
1789TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1790 TestDelegate d;
1791 URLRequest req(GURL("data:,"), &d, &default_context_);
1792 req.Start();
[email protected]255620da2013-08-19 13:14:291793 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441794 EXPECT_EQ("", d.data_received());
1795 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1796}
1797
[email protected]5033ab82013-03-22 20:17:461798// Make sure that SetPriority actually sets the URLRequest's priority
1799// correctly, both before and after start.
1800TEST_F(URLRequestTest, SetPriorityBasic) {
1801 TestDelegate d;
1802 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1803 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1804
1805 req.SetPriority(LOW);
1806 EXPECT_EQ(LOW, req.priority());
1807
1808 req.Start();
1809 EXPECT_EQ(LOW, req.priority());
1810
1811 req.SetPriority(MEDIUM);
1812 EXPECT_EQ(MEDIUM, req.priority());
1813}
1814
1815// Make sure that URLRequest calls SetPriority on a job before calling
1816// Start on it.
1817TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1818 TestDelegate d;
1819 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1820 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1821
1822 scoped_refptr<URLRequestTestJob> job =
1823 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501824 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461825 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1826
1827 req.SetPriority(LOW);
1828
1829 req.Start();
1830 EXPECT_EQ(LOW, job->priority());
1831}
1832
1833// Make sure that URLRequest passes on its priority updates to its
1834// job.
1835TEST_F(URLRequestTest, SetJobPriority) {
1836 TestDelegate d;
1837 URLRequest req(GURL("http://test_intercept/foo"), &d, &default_context_);
1838
1839 scoped_refptr<URLRequestTestJob> job =
1840 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:501841 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:461842
1843 req.SetPriority(LOW);
1844 req.Start();
1845 EXPECT_EQ(LOW, job->priority());
1846
1847 req.SetPriority(MEDIUM);
1848 EXPECT_EQ(MEDIUM, req.priority());
1849 EXPECT_EQ(MEDIUM, job->priority());
1850}
1851
[email protected]ce7d0cbc2013-05-03 18:57:221852// TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
[email protected]316c1e5e2012-09-12 15:17:441853#if !defined(OS_IOS)
[email protected]ce7d0cbc2013-05-03 18:57:221854// A subclass of SpawnedTestServer that uses a statically-configured hostname.
1855// This is to work around mysterious failures in chrome_frame_net_tests. See:
[email protected]316c1e5e2012-09-12 15:17:441856// http://crbug.com/114369
[email protected]ce7d0cbc2013-05-03 18:57:221857class LocalHttpTestServer : public SpawnedTestServer {
[email protected]316c1e5e2012-09-12 15:17:441858 public:
[email protected]6cdfd7f2013-02-08 20:40:151859 explicit LocalHttpTestServer(const base::FilePath& document_root)
[email protected]ce7d0cbc2013-05-03 18:57:221860 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1861 ScopedCustomUrlRequestTestHttpHost::value(),
1862 document_root) {}
[email protected]316c1e5e2012-09-12 15:17:441863 LocalHttpTestServer()
[email protected]ce7d0cbc2013-05-03 18:57:221864 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1865 ScopedCustomUrlRequestTestHttpHost::value(),
1866 base::FilePath()) {}
[email protected]316c1e5e2012-09-12 15:17:441867};
1868
[email protected]f2f31b32013-01-16 23:24:091869TEST_F(URLRequestTest, DelayedCookieCallback) {
[email protected]316c1e5e2012-09-12 15:17:441870 LocalHttpTestServer test_server;
1871 ASSERT_TRUE(test_server.Start());
1872
1873 TestURLRequestContext context;
1874 scoped_refptr<DelayedCookieMonster> delayed_cm =
1875 new DelayedCookieMonster();
1876 scoped_refptr<CookieStore> cookie_store = delayed_cm;
[email protected]90499482013-06-01 00:39:501877 context.set_cookie_store(delayed_cm.get());
[email protected]316c1e5e2012-09-12 15:17:441878
1879 // Set up a cookie.
1880 {
1881 TestNetworkDelegate network_delegate;
1882 context.set_network_delegate(&network_delegate);
1883 TestDelegate d;
1884 URLRequest req(
1885 test_server.GetURL("set-cookie?CookieToNotSend=1"), &d, &context);
1886 req.Start();
[email protected]255620da2013-08-19 13:14:291887 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441888 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1889 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1890 EXPECT_EQ(1, network_delegate.set_cookie_count());
1891 }
1892
1893 // Verify that the cookie is set.
1894 {
1895 TestNetworkDelegate network_delegate;
1896 context.set_network_delegate(&network_delegate);
1897 TestDelegate d;
1898 URLRequest req(test_server.GetURL("echoheader?Cookie"), &d, &context);
1899 req.Start();
[email protected]255620da2013-08-19 13:14:291900 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441901
1902 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1903 != std::string::npos);
1904 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1905 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1906 }
1907}
1908
[email protected]f2f31b32013-01-16 23:24:091909TEST_F(URLRequestTest, DoNotSendCookies) {
[email protected]316c1e5e2012-09-12 15:17:441910 LocalHttpTestServer test_server;
1911 ASSERT_TRUE(test_server.Start());
1912
1913 // Set up a cookie.
1914 {
1915 TestNetworkDelegate network_delegate;
1916 default_context_.set_network_delegate(&network_delegate);
1917 TestDelegate d;
1918 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1919 &d,
1920 &default_context_);
1921 req.Start();
[email protected]255620da2013-08-19 13:14:291922 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441923 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1924 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1925 }
1926
1927 // Verify that the cookie is set.
1928 {
1929 TestNetworkDelegate network_delegate;
1930 default_context_.set_network_delegate(&network_delegate);
1931 TestDelegate d;
1932 URLRequest req(
1933 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1934 req.Start();
[email protected]255620da2013-08-19 13:14:291935 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441936
1937 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
1938 != std::string::npos);
1939 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1940 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1941 }
1942
1943 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
1944 {
1945 TestNetworkDelegate network_delegate;
1946 default_context_.set_network_delegate(&network_delegate);
1947 TestDelegate d;
1948 URLRequest req(
1949 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
1950 req.set_load_flags(LOAD_DO_NOT_SEND_COOKIES);
1951 req.Start();
[email protected]255620da2013-08-19 13:14:291952 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441953
1954 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
1955 == std::string::npos);
1956
1957 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
1958 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1959 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1960 }
1961}
1962
1963TEST_F(URLRequestTest, DoNotSaveCookies) {
1964 LocalHttpTestServer test_server;
1965 ASSERT_TRUE(test_server.Start());
1966
1967 // Set up a cookie.
1968 {
1969 TestNetworkDelegate network_delegate;
1970 default_context_.set_network_delegate(&network_delegate);
1971 TestDelegate d;
1972 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
1973 &d,
1974 &default_context_);
1975 req.Start();
[email protected]255620da2013-08-19 13:14:291976 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441977
1978 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1979 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
1980 EXPECT_EQ(1, network_delegate.set_cookie_count());
1981 }
1982
1983 // Try to set-up another cookie and update the previous cookie.
1984 {
1985 TestNetworkDelegate network_delegate;
1986 default_context_.set_network_delegate(&network_delegate);
1987 TestDelegate d;
1988 URLRequest req(
1989 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
1990 &d,
1991 &default_context_);
1992 req.set_load_flags(LOAD_DO_NOT_SAVE_COOKIES);
1993 req.Start();
1994
[email protected]255620da2013-08-19 13:14:291995 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:441996
1997 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
1998 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
1999 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2000 EXPECT_EQ(0, network_delegate.set_cookie_count());
2001 }
2002
2003 // Verify the cookies weren't saved or updated.
2004 {
2005 TestNetworkDelegate network_delegate;
2006 default_context_.set_network_delegate(&network_delegate);
2007 TestDelegate d;
2008 URLRequest req(
2009 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2010 req.Start();
[email protected]255620da2013-08-19 13:14:292011 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442012
2013 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2014 == std::string::npos);
2015 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2016 != std::string::npos);
2017
2018 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2019 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2020 EXPECT_EQ(0, network_delegate.set_cookie_count());
2021 }
2022}
2023
2024TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2025 LocalHttpTestServer test_server;
2026 ASSERT_TRUE(test_server.Start());
2027
2028 // Set up a cookie.
2029 {
2030 TestNetworkDelegate network_delegate;
2031 default_context_.set_network_delegate(&network_delegate);
2032 TestDelegate d;
2033 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2034 &d,
2035 &default_context_);
2036 req.Start();
[email protected]255620da2013-08-19 13:14:292037 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442038
2039 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2040 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2041 }
2042
2043 // Verify that the cookie is set.
2044 {
2045 TestNetworkDelegate network_delegate;
2046 default_context_.set_network_delegate(&network_delegate);
2047 TestDelegate d;
2048 URLRequest req(
2049 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2050 req.Start();
[email protected]255620da2013-08-19 13:14:292051 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442052
2053 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2054 != std::string::npos);
2055
2056 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2057 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2058 }
2059
2060 // Verify that the cookie isn't sent.
2061 {
2062 TestNetworkDelegate network_delegate;
2063 default_context_.set_network_delegate(&network_delegate);
2064 TestDelegate d;
2065 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2066 URLRequest req(
2067 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2068 req.Start();
[email protected]255620da2013-08-19 13:14:292069 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442070
2071 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2072 == std::string::npos);
2073
[email protected]22e045f2013-09-20 03:54:032074 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442075 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2076 }
2077}
2078
2079TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2080 LocalHttpTestServer test_server;
2081 ASSERT_TRUE(test_server.Start());
2082
2083 // Set up a cookie.
2084 {
2085 TestNetworkDelegate network_delegate;
2086 default_context_.set_network_delegate(&network_delegate);
2087 TestDelegate d;
2088 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2089 &d,
2090 &default_context_);
2091 req.Start();
[email protected]255620da2013-08-19 13:14:292092 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442093
2094 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2095 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2096 }
2097
2098 // Try to set-up another cookie and update the previous cookie.
2099 {
2100 TestNetworkDelegate network_delegate;
2101 default_context_.set_network_delegate(&network_delegate);
2102 TestDelegate d;
2103 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2104 URLRequest req(
2105 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2106 &d,
2107 &default_context_);
2108 req.Start();
2109
[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(2, network_delegate.blocked_set_cookie_count());
2114 }
2115
2116 // Verify the cookies weren't saved or updated.
2117 {
2118 TestNetworkDelegate network_delegate;
2119 default_context_.set_network_delegate(&network_delegate);
2120 TestDelegate d;
2121 URLRequest req(
2122 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2123 req.Start();
[email protected]255620da2013-08-19 13:14:292124 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442125
2126 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2127 == std::string::npos);
2128 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2129 != std::string::npos);
2130
2131 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2132 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2133 }
2134}
2135
2136TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2137 LocalHttpTestServer test_server;
2138 ASSERT_TRUE(test_server.Start());
2139
2140 // Set up an empty cookie.
2141 {
2142 TestNetworkDelegate network_delegate;
2143 default_context_.set_network_delegate(&network_delegate);
2144 TestDelegate d;
2145 URLRequest req(test_server.GetURL("set-cookie"), &d, &default_context_);
2146 req.Start();
[email protected]255620da2013-08-19 13:14:292147 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442148
2149 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2150 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2151 EXPECT_EQ(0, network_delegate.set_cookie_count());
2152 }
2153}
2154
2155TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2156 LocalHttpTestServer test_server;
2157 ASSERT_TRUE(test_server.Start());
2158
2159 // Set up a cookie.
2160 {
2161 TestNetworkDelegate network_delegate;
2162 default_context_.set_network_delegate(&network_delegate);
2163 TestDelegate d;
2164 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2165 &d,
2166 &default_context_);
2167 req.Start();
[email protected]255620da2013-08-19 13:14:292168 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442169
2170 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2171 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2172 }
2173
2174 // Verify that the cookie is set.
2175 {
2176 TestNetworkDelegate network_delegate;
2177 default_context_.set_network_delegate(&network_delegate);
2178 TestDelegate d;
2179 URLRequest req(
2180 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2181 req.Start();
[email protected]255620da2013-08-19 13:14:292182 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442183
2184 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2185 != std::string::npos);
2186
2187 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2188 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2189 }
2190
2191 // Verify that the cookie isn't sent.
2192 {
2193 TestNetworkDelegate network_delegate;
2194 default_context_.set_network_delegate(&network_delegate);
2195 TestDelegate d;
2196 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2197 URLRequest req(
2198 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2199 req.Start();
[email protected]255620da2013-08-19 13:14:292200 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442201
2202 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2203 == std::string::npos);
2204
[email protected]22e045f2013-09-20 03:54:032205 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
[email protected]316c1e5e2012-09-12 15:17:442206 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2207 }
2208}
2209
2210TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2211 LocalHttpTestServer test_server;
2212 ASSERT_TRUE(test_server.Start());
2213
2214 // Set up a cookie.
2215 {
2216 TestNetworkDelegate network_delegate;
2217 default_context_.set_network_delegate(&network_delegate);
2218 TestDelegate d;
2219 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2220 &d,
2221 &default_context_);
2222 req.Start();
[email protected]255620da2013-08-19 13:14:292223 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442224
2225 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2226 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2227 }
2228
2229 // Try to set-up another cookie and update the previous cookie.
2230 {
2231 TestNetworkDelegate network_delegate;
2232 default_context_.set_network_delegate(&network_delegate);
2233 TestDelegate d;
2234 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2235 URLRequest req(
2236 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2237 &d,
2238 &default_context_);
2239 req.Start();
2240
[email protected]255620da2013-08-19 13:14:292241 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442242
2243 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2244 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2245 }
2246
2247 // Verify the cookies weren't saved or updated.
2248 {
2249 TestNetworkDelegate network_delegate;
2250 default_context_.set_network_delegate(&network_delegate);
2251 TestDelegate d;
2252 URLRequest req(
2253 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2254 req.Start();
[email protected]255620da2013-08-19 13:14:292255 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442256
2257 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2258 == std::string::npos);
2259 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2260 != std::string::npos);
2261
2262 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2263 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2264 }
2265}
2266
[email protected]5095cd72012-11-01 10:29:162267// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2268// value for the |fixed_date| argument given to the constructor.
2269class FixedDateNetworkDelegate : public TestNetworkDelegate {
2270 public:
2271 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2272 : fixed_date_(fixed_date) {}
2273 virtual ~FixedDateNetworkDelegate() {}
2274
2275 // net::NetworkDelegate implementation
2276 virtual int OnHeadersReceived(
2277 net::URLRequest* request,
2278 const net::CompletionCallback& callback,
2279 const net::HttpResponseHeaders* original_response_headers,
2280 scoped_refptr<net::HttpResponseHeaders>* override_response_headers)
2281 OVERRIDE;
2282
2283 private:
2284 std::string fixed_date_;
2285
2286 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2287};
2288
2289int FixedDateNetworkDelegate::OnHeadersReceived(
2290 net::URLRequest* request,
2291 const net::CompletionCallback& callback,
2292 const net::HttpResponseHeaders* original_response_headers,
2293 scoped_refptr<net::HttpResponseHeaders>* override_response_headers) {
2294 net::HttpResponseHeaders* new_response_headers =
2295 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2296
2297 new_response_headers->RemoveHeader("Date");
2298 new_response_headers->AddHeader("Date: " + fixed_date_);
2299
2300 *override_response_headers = new_response_headers;
2301 return TestNetworkDelegate::OnHeadersReceived(request,
2302 callback,
2303 original_response_headers,
2304 override_response_headers);
2305}
2306
2307// Test that cookie expiration times are adjusted for server/client clock
2308// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2309// headers by defaulting to GMT. (crbug.com/135131)
2310TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2311 LocalHttpTestServer test_server;
2312 ASSERT_TRUE(test_server.Start());
2313
2314 // Set up an expired cookie.
2315 {
2316 TestNetworkDelegate network_delegate;
2317 default_context_.set_network_delegate(&network_delegate);
2318 TestDelegate d;
2319 URLRequest req(test_server.GetURL(
2320 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2321 &d,
2322 &default_context_);
2323 req.Start();
[email protected]255620da2013-08-19 13:14:292324 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162325 }
2326 // Verify that the cookie is not set.
2327 {
2328 TestNetworkDelegate network_delegate;
2329 default_context_.set_network_delegate(&network_delegate);
2330 TestDelegate d;
2331 URLRequest req(
2332 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2333 req.Start();
[email protected]255620da2013-08-19 13:14:292334 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162335
2336 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2337 }
2338 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2339 {
2340 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2341 default_context_.set_network_delegate(&network_delegate);
2342 TestDelegate d;
2343 URLRequest req(test_server.GetURL(
2344 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2345 &d,
2346 &default_context_);
2347 req.Start();
[email protected]255620da2013-08-19 13:14:292348 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162349 }
2350 // Verify that the cookie is set.
2351 {
2352 TestNetworkDelegate network_delegate;
2353 default_context_.set_network_delegate(&network_delegate);
2354 TestDelegate d;
2355 URLRequest req(
2356 test_server.GetURL("echoheader?Cookie"), &d, &default_context_);
2357 req.Start();
[email protected]255620da2013-08-19 13:14:292358 base::RunLoop().Run();
[email protected]5095cd72012-11-01 10:29:162359
2360 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2361 }
2362}
2363
2364
[email protected]316c1e5e2012-09-12 15:17:442365// Check that it is impossible to change the referrer in the extra headers of
2366// an URLRequest.
2367TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2368 LocalHttpTestServer test_server;
2369 ASSERT_TRUE(test_server.Start());
2370
2371 // If extra headers contain referer and the request contains a referer,
2372 // only the latter shall be respected.
2373 {
2374 TestDelegate d;
2375 URLRequest req(
2376 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:132377 req.SetReferrer("http://foo.com/");
[email protected]316c1e5e2012-09-12 15:17:442378
2379 HttpRequestHeaders headers;
2380 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2381 req.SetExtraRequestHeaders(headers);
2382
2383 req.Start();
[email protected]255620da2013-08-19 13:14:292384 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442385
2386 EXPECT_EQ("http://foo.com/", d.data_received());
2387 }
2388
2389 // If extra headers contain a referer but the request does not, no referer
2390 // shall be sent in the header.
2391 {
2392 TestDelegate d;
2393 URLRequest req(
2394 test_server.GetURL("echoheader?Referer"), &d, &default_context_);
2395
2396 HttpRequestHeaders headers;
2397 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2398 req.SetExtraRequestHeaders(headers);
2399 req.set_load_flags(LOAD_VALIDATE_CACHE);
2400
2401 req.Start();
[email protected]255620da2013-08-19 13:14:292402 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:442403
2404 EXPECT_EQ("None", d.data_received());
2405 }
2406}
2407
[email protected]b89290212009-08-14 22:37:352408class URLRequestTestHTTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:112409 public:
2410 URLRequestTestHTTP()
[email protected]6cdfd7f2013-02-08 20:40:152411 : test_server_(base::FilePath(FILE_PATH_LITERAL(
[email protected]95409e12010-08-17 20:07:112412 "net/data/url_request_unittest"))) {
2413 }
2414
[email protected]b89290212009-08-14 22:37:352415 protected:
[email protected]21184962011-10-26 00:50:302416 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2417 // |request_method| is the method to use for the initial request.
2418 // |redirect_method| is the method that is expected to be used for the second
2419 // request, after redirection.
2420 // If |include_data| is true, data is uploaded with the request. The
2421 // response body is expected to match it exactly, if and only if
2422 // |request_method| == |redirect_method|.
2423 void HTTPRedirectMethodTest(const GURL& redirect_url,
2424 const std::string& request_method,
2425 const std::string& redirect_method,
2426 bool include_data) {
2427 static const char kData[] = "hello world";
2428 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:132429 URLRequest req(redirect_url, &d, &default_context_);
[email protected]21184962011-10-26 00:50:302430 req.set_method(request_method);
2431 if (include_data) {
[email protected]f288ef02012-12-15 20:28:282432 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]21184962011-10-26 00:50:302433 HttpRequestHeaders headers;
2434 headers.SetHeader(HttpRequestHeaders::kContentLength,
2435 base::UintToString(arraysize(kData) - 1));
2436 req.SetExtraRequestHeaders(headers);
2437 }
2438 req.Start();
[email protected]255620da2013-08-19 13:14:292439 base::RunLoop().Run();
[email protected]21184962011-10-26 00:50:302440 EXPECT_EQ(redirect_method, req.method());
2441 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2442 EXPECT_EQ(OK, req.status().error());
2443 if (include_data) {
2444 if (request_method == redirect_method) {
2445 EXPECT_EQ(kData, d.data_received());
2446 } else {
2447 EXPECT_NE(kData, d.data_received());
2448 }
2449 }
2450 if (HasFailure())
2451 LOG(WARNING) << "Request method was: " << request_method;
2452 }
2453
[email protected]762d2db2010-01-11 19:03:012454 void HTTPUploadDataOperationTest(const std::string& method) {
[email protected]762d2db2010-01-11 19:03:012455 const int kMsgSize = 20000; // multiple of 10
2456 const int kIterations = 50;
[email protected]f43b89f32012-05-01 19:39:482457 char* uploadBytes = new char[kMsgSize+1];
2458 char* ptr = uploadBytes;
[email protected]762d2db2010-01-11 19:03:012459 char marker = 'a';
2460 for (int idx = 0; idx < kMsgSize/10; idx++) {
2461 memcpy(ptr, "----------", 10);
2462 ptr += 10;
2463 if (idx % 100 == 0) {
2464 ptr--;
2465 *ptr++ = marker;
2466 if (++marker > 'z')
2467 marker = 'a';
2468 }
2469 }
2470 uploadBytes[kMsgSize] = '\0';
2471
[email protected]762d2db2010-01-11 19:03:012472 for (int i = 0; i < kIterations; ++i) {
2473 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:132474 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
[email protected]762d2db2010-01-11 19:03:012475 r.set_method(method.c_str());
2476
[email protected]f288ef02012-12-15 20:28:282477 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
[email protected]762d2db2010-01-11 19:03:012478
2479 r.Start();
2480 EXPECT_TRUE(r.is_pending());
2481
[email protected]255620da2013-08-19 13:14:292482 base::RunLoop().Run();
[email protected]762d2db2010-01-11 19:03:012483
[email protected]329b68b2012-11-14 17:54:272484 ASSERT_EQ(1, d.response_started_count())
2485 << "request failed: " << r.status().status()
2486 << ", os error: " << r.status().error();
[email protected]762d2db2010-01-11 19:03:012487
2488 EXPECT_FALSE(d.received_data_before_response());
2489 EXPECT_EQ(uploadBytes, d.data_received());
[email protected]762d2db2010-01-11 19:03:012490 }
2491 delete[] uploadBytes;
2492 }
2493
[email protected]ef2bf422012-05-11 03:27:092494 void AddChunksToUpload(URLRequest* r) {
[email protected]0c9bf872011-03-04 17:53:222495 r->AppendChunkToUpload("a", 1, false);
2496 r->AppendChunkToUpload("bcd", 3, false);
2497 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2498 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2499 r->AppendChunkToUpload("0", 1, false);
2500 r->AppendChunkToUpload("2323", 4, true);
[email protected]699efe602011-01-25 07:17:112501 }
2502
[email protected]ef2bf422012-05-11 03:27:092503 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
[email protected]699efe602011-01-25 07:17:112504 // This should match the chunks sent by AddChunksToUpload().
[email protected]329b68b2012-11-14 17:54:272505 const std::string expected_data =
[email protected]699efe602011-01-25 07:17:112506 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2507
[email protected]329b68b2012-11-14 17:54:272508 ASSERT_EQ(1, d->response_started_count())
2509 << "request failed: " << r->status().status()
2510 << ", os error: " << r->status().error();
[email protected]699efe602011-01-25 07:17:112511
2512 EXPECT_FALSE(d->received_data_before_response());
2513
[email protected]329b68b2012-11-14 17:54:272514 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2515 EXPECT_EQ(expected_data, d->data_received());
[email protected]699efe602011-01-25 07:17:112516 }
2517
[email protected]ede03212012-09-07 12:52:262518 bool DoManyCookiesRequest(int num_cookies) {
[email protected]263163f2012-06-14 22:40:342519 TestDelegate d;
2520 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2521 base::IntToString(num_cookies)),
[email protected]94e2bbe2012-06-22 15:26:132522 &d,
2523 &default_context_);
[email protected]263163f2012-06-14 22:40:342524
2525 r.Start();
2526 EXPECT_TRUE(r.is_pending());
2527
[email protected]255620da2013-08-19 13:14:292528 base::RunLoop().Run();
[email protected]263163f2012-06-14 22:40:342529
2530 bool is_success = r.status().is_success();
2531
[email protected]ede03212012-09-07 12:52:262532 if (!is_success) {
[email protected]263163f2012-06-14 22:40:342533 // Requests handled by ChromeFrame send a less precise error message,
2534 // ERR_CONNECTION_ABORTED.
2535 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG ||
2536 r.status().error() == ERR_CONNECTION_ABORTED);
2537 // The test server appears to be unable to handle subsequent requests
2538 // after this error is triggered. Force it to restart.
2539 EXPECT_TRUE(test_server_.Stop());
2540 EXPECT_TRUE(test_server_.Start());
2541 }
2542
2543 return is_success;
2544 }
2545
[email protected]1700c6a2012-02-22 18:07:072546 LocalHttpTestServer test_server_;
[email protected]b89290212009-08-14 22:37:352547};
2548
[email protected]95409e12010-08-17 20:07:112549// In this unit test, we're using the HTTPTestServer as a proxy server and
2550// issuing a CONNECT request with the magic host name "www.redirect.com".
2551// The HTTPTestServer will return a 302 response, which we should not
2552// follow.
[email protected]f2f31b32013-01-16 23:24:092553TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
[email protected]95409e12010-08-17 20:07:112554 ASSERT_TRUE(test_server_.Start());
2555
[email protected]ceefd7fd2012-11-29 00:36:242556 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042557 TestURLRequestContextWithProxy context(
2558 test_server_.host_port_pair().ToString(),
2559 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502560
[email protected]d1ec59082009-02-11 02:48:152561 TestDelegate d;
2562 {
[email protected]94e2bbe2012-06-22 15:26:132563 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]d1ec59082009-02-11 02:48:152564 r.Start();
2565 EXPECT_TRUE(r.is_pending());
2566
[email protected]255620da2013-08-19 13:14:292567 base::RunLoop().Run();
[email protected]d1ec59082009-02-11 02:48:152568
[email protected]7461a402011-03-24 23:19:512569 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052570 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:082571 EXPECT_EQ(1, d.response_started_count());
[email protected]d1ec59082009-02-11 02:48:152572 // We should not have followed the redirect.
2573 EXPECT_EQ(0, d.received_redirect_count());
2574 }
2575}
2576
[email protected]8202d0c2011-02-23 08:31:142577// This is the same as the previous test, but checks that the network delegate
2578// registers the error.
[email protected]c044616e2013-02-20 02:01:262579TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
[email protected]8202d0c2011-02-23 08:31:142580 ASSERT_TRUE(test_server_.Start());
2581
[email protected]ceefd7fd2012-11-29 00:36:242582 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:042583 TestURLRequestContextWithProxy context(
2584 test_server_.host_port_pair().ToString(),
2585 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502586
[email protected]8202d0c2011-02-23 08:31:142587 TestDelegate d;
2588 {
[email protected]94e2bbe2012-06-22 15:26:132589 URLRequest r(GURL("https://www.redirect.com/"), &d, &context);
[email protected]8202d0c2011-02-23 08:31:142590 r.Start();
2591 EXPECT_TRUE(r.is_pending());
2592
[email protected]255620da2013-08-19 13:14:292593 base::RunLoop().Run();
[email protected]8202d0c2011-02-23 08:31:142594
[email protected]7461a402011-03-24 23:19:512595 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052596 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]8202d0c2011-02-23 08:31:142597 EXPECT_EQ(1, d.response_started_count());
2598 // We should not have followed the redirect.
2599 EXPECT_EQ(0, d.received_redirect_count());
2600
2601 EXPECT_EQ(1, network_delegate.error_count());
[email protected]d0cc35b2011-09-08 12:02:052602 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
[email protected]8202d0c2011-02-23 08:31:142603 }
2604}
2605
[email protected]dc5a5cf2012-09-26 02:49:302606// Tests that we can block and asynchronously return OK in various stages.
2607TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2608 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2609 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2610 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2611 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2612 };
2613 static const size_t blocking_stages_length = arraysize(blocking_stages);
2614
2615 ASSERT_TRUE(test_server_.Start());
2616
2617 TestDelegate d;
2618 BlockingNetworkDelegate network_delegate(
2619 BlockingNetworkDelegate::USER_CALLBACK);
2620 network_delegate.set_block_on(
2621 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2622 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2623 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2624
2625 TestURLRequestContext context(true);
2626 context.set_network_delegate(&network_delegate);
2627 context.Init();
2628
2629 {
2630 URLRequest r(test_server_.GetURL("empty.html"), &d, &context);
2631
2632 r.Start();
2633 for (size_t i = 0; i < blocking_stages_length; ++i) {
[email protected]255620da2013-08-19 13:14:292634 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302635 EXPECT_EQ(blocking_stages[i],
2636 network_delegate.stage_blocked_for_callback());
2637 network_delegate.DoCallback(OK);
2638 }
[email protected]255620da2013-08-19 13:14:292639 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:302640 EXPECT_EQ(200, r.GetResponseCode());
2641 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2642 EXPECT_EQ(1, network_delegate.created_requests());
2643 EXPECT_EQ(0, network_delegate.destroyed_requests());
2644 }
2645 EXPECT_EQ(1, network_delegate.destroyed_requests());
2646}
2647
[email protected]4c76d7c2011-04-15 19:14:122648// Tests that the network delegate can block and cancel a request.
2649TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2650 ASSERT_TRUE(test_server_.Start());
2651
2652 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302653 BlockingNetworkDelegate network_delegate(
2654 BlockingNetworkDelegate::AUTO_CALLBACK);
2655 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2656 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
[email protected]4c76d7c2011-04-15 19:14:122657
[email protected]d5a4dd62012-05-23 01:41:042658 TestURLRequestContextWithProxy context(
2659 test_server_.host_port_pair().ToString(),
2660 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502661
[email protected]4c76d7c2011-04-15 19:14:122662 {
[email protected]007b3f82013-04-09 08:46:452663 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122664
2665 r.Start();
[email protected]255620da2013-08-19 13:14:292666 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122667
2668 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052669 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122670 EXPECT_EQ(1, network_delegate.created_requests());
2671 EXPECT_EQ(0, network_delegate.destroyed_requests());
2672 }
2673 EXPECT_EQ(1, network_delegate.destroyed_requests());
2674}
2675
[email protected]b4438d32012-09-27 06:15:302676// Helper function for NetworkDelegateCancelRequestAsynchronously and
2677// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2678// delegate operating in |block_mode| and a request for |url|. It blocks the
2679// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2680void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2681 BlockingNetworkDelegate::Stage stage,
2682 const GURL& url) {
[email protected]3cd384c602011-08-31 16:12:362683 TestDelegate d;
[email protected]b4438d32012-09-27 06:15:302684 BlockingNetworkDelegate network_delegate(block_mode);
2685 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2686 network_delegate.set_block_on(stage);
[email protected]3cd384c602011-08-31 16:12:362687
[email protected]b4438d32012-09-27 06:15:302688 TestURLRequestContext context(true);
2689 context.set_network_delegate(&network_delegate);
2690 context.Init();
[email protected]3cd384c602011-08-31 16:12:362691
2692 {
[email protected]b4438d32012-09-27 06:15:302693 URLRequest r(url, &d, &context);
[email protected]3cd384c602011-08-31 16:12:362694
2695 r.Start();
[email protected]255620da2013-08-19 13:14:292696 base::RunLoop().Run();
[email protected]3cd384c602011-08-31 16:12:362697
2698 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]b4438d32012-09-27 06:15:302699 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
[email protected]3cd384c602011-08-31 16:12:362700 EXPECT_EQ(1, network_delegate.created_requests());
2701 EXPECT_EQ(0, network_delegate.destroyed_requests());
2702 }
2703 EXPECT_EQ(1, network_delegate.destroyed_requests());
2704}
2705
[email protected]b4438d32012-09-27 06:15:302706// The following 3 tests check that the network delegate can cancel a request
2707// synchronously in various stages of the request.
2708TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2709 ASSERT_TRUE(test_server_.Start());
2710 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2711 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452712 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302713}
2714
2715TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2716 ASSERT_TRUE(test_server_.Start());
2717 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2718 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452719 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302720}
2721
2722TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2723 ASSERT_TRUE(test_server_.Start());
2724 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2725 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452726 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302727}
2728
2729// The following 3 tests check that the network delegate can cancel a request
2730// asynchronously in various stages of the request.
2731TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2732 ASSERT_TRUE(test_server_.Start());
2733 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2734 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
[email protected]007b3f82013-04-09 08:46:452735 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302736}
2737
2738TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2739 ASSERT_TRUE(test_server_.Start());
2740 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2741 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
[email protected]007b3f82013-04-09 08:46:452742 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302743}
2744
2745TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2746 ASSERT_TRUE(test_server_.Start());
2747 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2748 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
[email protected]007b3f82013-04-09 08:46:452749 test_server_.GetURL(std::string()));
[email protected]b4438d32012-09-27 06:15:302750}
2751
[email protected]4c76d7c2011-04-15 19:14:122752// Tests that the network delegate can block and redirect a request to a new
2753// URL.
2754TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2755 ASSERT_TRUE(test_server_.Start());
2756
2757 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302758 BlockingNetworkDelegate network_delegate(
2759 BlockingNetworkDelegate::AUTO_CALLBACK);
2760 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]4c76d7c2011-04-15 19:14:122761 GURL redirect_url(test_server_.GetURL("simple.html"));
2762 network_delegate.set_redirect_url(redirect_url);
2763
[email protected]d5a4dd62012-05-23 01:41:042764 TestURLRequestContextWithProxy context(
2765 test_server_.host_port_pair().ToString(),
2766 &network_delegate);
[email protected]87a09a92011-07-14 15:50:502767
[email protected]4c76d7c2011-04-15 19:14:122768 {
[email protected]8f1ac082011-04-19 21:14:132769 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132770 URLRequest r(original_url, &d, &context);
[email protected]4c76d7c2011-04-15 19:14:122771
2772 r.Start();
[email protected]255620da2013-08-19 13:14:292773 base::RunLoop().Run();
[email protected]4c76d7c2011-04-15 19:14:122774
2775 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:052776 EXPECT_EQ(0, r.status().error());
[email protected]4c76d7c2011-04-15 19:14:122777 EXPECT_EQ(redirect_url, r.url());
[email protected]8f1ac082011-04-19 21:14:132778 EXPECT_EQ(original_url, r.original_url());
2779 EXPECT_EQ(2U, r.url_chain().size());
[email protected]4c76d7c2011-04-15 19:14:122780 EXPECT_EQ(1, network_delegate.created_requests());
2781 EXPECT_EQ(0, network_delegate.destroyed_requests());
2782 }
2783 EXPECT_EQ(1, network_delegate.destroyed_requests());
2784}
2785
[email protected]b813ed72012-04-05 08:21:362786// Tests that the network delegate can block and redirect a request to a new
2787// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2788TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2789 ASSERT_TRUE(test_server_.Start());
2790
2791 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302792 BlockingNetworkDelegate network_delegate(
2793 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]b813ed72012-04-05 08:21:362794 GURL redirect_url(test_server_.GetURL("simple.html"));
2795 network_delegate.set_redirect_url(redirect_url);
[email protected]b813ed72012-04-05 08:21:362796
[email protected]d5a4dd62012-05-23 01:41:042797 TestURLRequestContextWithProxy context(
2798 test_server_.host_port_pair().ToString(),
2799 &network_delegate);
[email protected]b813ed72012-04-05 08:21:362800
2801 {
2802 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132803 URLRequest r(original_url, &d, &context);
[email protected]b813ed72012-04-05 08:21:362804
2805 r.Start();
[email protected]255620da2013-08-19 13:14:292806 base::RunLoop().Run();
[email protected]b813ed72012-04-05 08:21:362807
2808 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2809 EXPECT_EQ(0, r.status().error());
2810 EXPECT_EQ(redirect_url, r.url());
2811 EXPECT_EQ(original_url, r.original_url());
2812 EXPECT_EQ(2U, r.url_chain().size());
2813 EXPECT_EQ(1, network_delegate.created_requests());
2814 EXPECT_EQ(0, network_delegate.destroyed_requests());
2815 }
2816 EXPECT_EQ(1, network_delegate.destroyed_requests());
2817}
2818
[email protected]3c5ca8c2011-09-29 01:14:512819// Tests that redirects caused by the network delegate preserve POST data.
2820TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2821 ASSERT_TRUE(test_server_.Start());
2822
2823 const char kData[] = "hello world";
2824
2825 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302826 BlockingNetworkDelegate network_delegate(
2827 BlockingNetworkDelegate::AUTO_CALLBACK);
2828 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]3c5ca8c2011-09-29 01:14:512829 GURL redirect_url(test_server_.GetURL("echo"));
2830 network_delegate.set_redirect_url(redirect_url);
2831
[email protected]ef2bf422012-05-11 03:27:092832 TestURLRequestContext context(true);
2833 context.set_network_delegate(&network_delegate);
2834 context.Init();
[email protected]3c5ca8c2011-09-29 01:14:512835
2836 {
2837 GURL original_url(test_server_.GetURL("empty.html"));
[email protected]94e2bbe2012-06-22 15:26:132838 URLRequest r(original_url, &d, &context);
[email protected]3c5ca8c2011-09-29 01:14:512839 r.set_method("POST");
[email protected]f288ef02012-12-15 20:28:282840 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]3c5ca8c2011-09-29 01:14:512841 HttpRequestHeaders headers;
2842 headers.SetHeader(HttpRequestHeaders::kContentLength,
2843 base::UintToString(arraysize(kData) - 1));
2844 r.SetExtraRequestHeaders(headers);
[email protected]3c5ca8c2011-09-29 01:14:512845 r.Start();
[email protected]255620da2013-08-19 13:14:292846 base::RunLoop().Run();
[email protected]3c5ca8c2011-09-29 01:14:512847
2848 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2849 EXPECT_EQ(0, r.status().error());
2850 EXPECT_EQ(redirect_url, r.url());
2851 EXPECT_EQ(original_url, r.original_url());
2852 EXPECT_EQ(2U, r.url_chain().size());
2853 EXPECT_EQ(1, network_delegate.created_requests());
2854 EXPECT_EQ(0, network_delegate.destroyed_requests());
2855 EXPECT_EQ("POST", r.method());
2856 EXPECT_EQ(kData, d.data_received());
2857 }
2858 EXPECT_EQ(1, network_delegate.destroyed_requests());
2859}
2860
[email protected]c2911d72011-10-03 22:16:362861// Tests that the network delegate can synchronously complete OnAuthRequired
2862// by taking no action. This indicates that the NetworkDelegate does not want to
2863// handle the challenge, and is passing the buck along to the
2864// URLRequest::Delegate.
2865TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
2866 ASSERT_TRUE(test_server_.Start());
2867
2868 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302869 BlockingNetworkDelegate network_delegate(
2870 BlockingNetworkDelegate::SYNCHRONOUS);
[email protected]c2911d72011-10-03 22:16:362871
[email protected]ef2bf422012-05-11 03:27:092872 TestURLRequestContext context(true);
2873 context.set_network_delegate(&network_delegate);
2874 context.Init();
[email protected]c2911d72011-10-03 22:16:362875
[email protected]f3cf9802011-10-28 18:44:582876 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362877
2878 {
2879 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132880 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362881 r.Start();
[email protected]79e1fd62013-06-20 06:50:042882
[email protected]255620da2013-08-19 13:14:292883 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:042884
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
2895TEST_F(URLRequestTestHTTP,
2896 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
2897 ASSERT_TRUE(test_server_.Start());
2898
2899 TestDelegate d;
2900 BlockingNetworkDelegate network_delegate(
2901 BlockingNetworkDelegate::SYNCHRONOUS);
2902
2903 TestURLRequestContext context(true);
2904 context.set_network_delegate(&network_delegate);
2905 context.Init();
2906
2907 d.set_credentials(AuthCredentials(kUser, kSecret));
2908
2909 {
2910 GURL url(test_server_.GetURL("auth-basic"));
2911 URLRequest r(url, &d, &context);
2912 r.Start();
2913
2914 {
2915 HttpRequestHeaders headers;
2916 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
2917 EXPECT_FALSE(headers.HasHeader("Authorization"));
2918 }
2919
[email protected]255620da2013-08-19 13:14:292920 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:362921
2922 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2923 EXPECT_EQ(0, r.status().error());
2924 EXPECT_EQ(200, r.GetResponseCode());
2925 EXPECT_TRUE(d.auth_required_called());
2926 EXPECT_EQ(1, network_delegate.created_requests());
2927 EXPECT_EQ(0, network_delegate.destroyed_requests());
2928 }
2929 EXPECT_EQ(1, network_delegate.destroyed_requests());
2930}
2931
2932// Tests that the network delegate can synchronously complete OnAuthRequired
[email protected]1e110eae2013-05-10 22:02:402933// by setting credentials.
[email protected]c2911d72011-10-03 22:16:362934TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
2935 ASSERT_TRUE(test_server_.Start());
2936
2937 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:302938 BlockingNetworkDelegate network_delegate(
2939 BlockingNetworkDelegate::SYNCHRONOUS);
2940 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:362941 network_delegate.set_auth_retval(
2942 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2943
[email protected]f3cf9802011-10-28 18:44:582944 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:362945
[email protected]ef2bf422012-05-11 03:27:092946 TestURLRequestContext context(true);
2947 context.set_network_delegate(&network_delegate);
2948 context.Init();
[email protected]c2911d72011-10-03 22:16:362949
2950 {
2951 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:132952 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:362953 r.Start();
[email protected]255620da2013-08-19 13:14:292954 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:362955
2956 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2957 EXPECT_EQ(0, r.status().error());
2958 EXPECT_EQ(200, r.GetResponseCode());
2959 EXPECT_FALSE(d.auth_required_called());
2960 EXPECT_EQ(1, network_delegate.created_requests());
2961 EXPECT_EQ(0, network_delegate.destroyed_requests());
2962 }
2963 EXPECT_EQ(1, network_delegate.destroyed_requests());
2964}
2965
[email protected]79e1fd62013-06-20 06:50:042966// Same as above, but also tests that GetFullRequestHeaders returns the proper
2967// headers (for the first or second request) when called at the proper times.
2968TEST_F(URLRequestTestHTTP,
2969 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
2970 ASSERT_TRUE(test_server_.Start());
2971
2972 TestDelegate d;
2973 BlockingNetworkDelegate network_delegate(
2974 BlockingNetworkDelegate::SYNCHRONOUS);
2975 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
2976 network_delegate.set_auth_retval(
2977 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
2978
2979 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
2980
2981 TestURLRequestContext context(true);
2982 context.set_network_delegate(&network_delegate);
2983 context.Init();
2984
2985 {
2986 GURL url(test_server_.GetURL("auth-basic"));
2987 URLRequest r(url, &d, &context);
2988 r.Start();
[email protected]255620da2013-08-19 13:14:292989 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:042990
2991 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2992 EXPECT_EQ(0, r.status().error());
2993 EXPECT_EQ(200, r.GetResponseCode());
2994 EXPECT_FALSE(d.auth_required_called());
2995 EXPECT_EQ(1, network_delegate.created_requests());
2996 EXPECT_EQ(0, network_delegate.destroyed_requests());
2997
2998 {
2999 HttpRequestHeaders headers;
3000 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3001 EXPECT_TRUE(headers.HasHeader("Authorization"));
3002 }
3003 }
3004 EXPECT_EQ(1, network_delegate.destroyed_requests());
3005}
3006
[email protected]c2911d72011-10-03 22:16:363007// Tests that the network delegate can synchronously complete OnAuthRequired
3008// by cancelling authentication.
3009TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3010 ASSERT_TRUE(test_server_.Start());
3011
3012 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303013 BlockingNetworkDelegate network_delegate(
3014 BlockingNetworkDelegate::SYNCHRONOUS);
3015 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363016 network_delegate.set_auth_retval(
3017 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3018
[email protected]ef2bf422012-05-11 03:27:093019 TestURLRequestContext context(true);
3020 context.set_network_delegate(&network_delegate);
3021 context.Init();
[email protected]c2911d72011-10-03 22:16:363022
3023 {
3024 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133025 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363026 r.Start();
[email protected]255620da2013-08-19 13:14:293027 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363028
3029 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3030 EXPECT_EQ(OK, r.status().error());
3031 EXPECT_EQ(401, r.GetResponseCode());
3032 EXPECT_FALSE(d.auth_required_called());
3033 EXPECT_EQ(1, network_delegate.created_requests());
3034 EXPECT_EQ(0, network_delegate.destroyed_requests());
3035 }
3036 EXPECT_EQ(1, network_delegate.destroyed_requests());
3037}
3038
3039// Tests that the network delegate can asynchronously complete OnAuthRequired
3040// by taking no action. This indicates that the NetworkDelegate does not want
3041// to handle the challenge, and is passing the buck along to the
3042// URLRequest::Delegate.
3043TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3044 ASSERT_TRUE(test_server_.Start());
3045
3046 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303047 BlockingNetworkDelegate network_delegate(
3048 BlockingNetworkDelegate::AUTO_CALLBACK);
3049 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363050
[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
[email protected]f3cf9802011-10-28 18:44:583055 d.set_credentials(AuthCredentials(kUser, kSecret));
[email protected]c2911d72011-10-03 22:16:363056
3057 {
3058 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133059 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363060 r.Start();
[email protected]255620da2013-08-19 13:14:293061 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363062
3063 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3064 EXPECT_EQ(0, r.status().error());
3065 EXPECT_EQ(200, r.GetResponseCode());
3066 EXPECT_TRUE(d.auth_required_called());
3067 EXPECT_EQ(1, network_delegate.created_requests());
3068 EXPECT_EQ(0, network_delegate.destroyed_requests());
3069 }
3070 EXPECT_EQ(1, network_delegate.destroyed_requests());
3071}
3072
3073// Tests that the network delegate can asynchronously complete OnAuthRequired
3074// by setting credentials.
3075TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3076 ASSERT_TRUE(test_server_.Start());
3077
3078 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303079 BlockingNetworkDelegate network_delegate(
3080 BlockingNetworkDelegate::AUTO_CALLBACK);
3081 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363082 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363083 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3084
[email protected]f3cf9802011-10-28 18:44:583085 AuthCredentials auth_credentials(kUser, kSecret);
[email protected]c2911d72011-10-03 22:16:363086 network_delegate.set_auth_credentials(auth_credentials);
3087
[email protected]ef2bf422012-05-11 03:27:093088 TestURLRequestContext context(true);
3089 context.set_network_delegate(&network_delegate);
3090 context.Init();
[email protected]c2911d72011-10-03 22:16:363091
3092 {
3093 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133094 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363095 r.Start();
[email protected]255620da2013-08-19 13:14:293096 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363097
3098 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3099 EXPECT_EQ(0, r.status().error());
3100
3101 EXPECT_EQ(200, r.GetResponseCode());
3102 EXPECT_FALSE(d.auth_required_called());
3103 EXPECT_EQ(1, network_delegate.created_requests());
3104 EXPECT_EQ(0, network_delegate.destroyed_requests());
3105 }
3106 EXPECT_EQ(1, network_delegate.destroyed_requests());
3107}
3108
3109// Tests that the network delegate can asynchronously complete OnAuthRequired
3110// by cancelling authentication.
3111TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3112 ASSERT_TRUE(test_server_.Start());
3113
3114 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303115 BlockingNetworkDelegate network_delegate(
3116 BlockingNetworkDelegate::AUTO_CALLBACK);
3117 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]c2911d72011-10-03 22:16:363118 network_delegate.set_auth_retval(
[email protected]c2911d72011-10-03 22:16:363119 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3120
[email protected]ef2bf422012-05-11 03:27:093121 TestURLRequestContext context(true);
3122 context.set_network_delegate(&network_delegate);
3123 context.Init();
[email protected]c2911d72011-10-03 22:16:363124
3125 {
3126 GURL url(test_server_.GetURL("auth-basic"));
[email protected]94e2bbe2012-06-22 15:26:133127 URLRequest r(url, &d, &context);
[email protected]c2911d72011-10-03 22:16:363128 r.Start();
[email protected]255620da2013-08-19 13:14:293129 base::RunLoop().Run();
[email protected]c2911d72011-10-03 22:16:363130
3131 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3132 EXPECT_EQ(OK, r.status().error());
3133 EXPECT_EQ(401, r.GetResponseCode());
3134 EXPECT_FALSE(d.auth_required_called());
3135 EXPECT_EQ(1, network_delegate.created_requests());
3136 EXPECT_EQ(0, network_delegate.destroyed_requests());
3137 }
3138 EXPECT_EQ(1, network_delegate.destroyed_requests());
3139}
3140
[email protected]9045b8822012-01-13 20:35:353141// Tests that we can handle when a network request was canceled while we were
3142// waiting for the network delegate.
3143// Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3144TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3145 ASSERT_TRUE(test_server_.Start());
3146
3147 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303148 BlockingNetworkDelegate network_delegate(
3149 BlockingNetworkDelegate::USER_CALLBACK);
3150 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
[email protected]9045b8822012-01-13 20:35:353151
[email protected]ef2bf422012-05-11 03:27:093152 TestURLRequestContext context(true);
3153 context.set_network_delegate(&network_delegate);
3154 context.Init();
[email protected]9045b8822012-01-13 20:35:353155
3156 {
[email protected]007b3f82013-04-09 08:46:453157 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353158
3159 r.Start();
[email protected]255620da2013-08-19 13:14:293160 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303161 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3162 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353163 EXPECT_EQ(0, network_delegate.completed_requests());
3164 // Cancel before callback.
3165 r.Cancel();
3166 // Ensure that network delegate is notified.
3167 EXPECT_EQ(1, network_delegate.completed_requests());
3168 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3169 EXPECT_EQ(ERR_ABORTED, r.status().error());
3170 EXPECT_EQ(1, network_delegate.created_requests());
3171 EXPECT_EQ(0, network_delegate.destroyed_requests());
3172 }
3173 EXPECT_EQ(1, network_delegate.destroyed_requests());
3174}
3175
3176// Tests that we can handle when a network request was canceled while we were
3177// waiting for the network delegate.
3178// Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3179TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3180 ASSERT_TRUE(test_server_.Start());
3181
3182 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303183 BlockingNetworkDelegate network_delegate(
3184 BlockingNetworkDelegate::USER_CALLBACK);
3185 network_delegate.set_block_on(
3186 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
[email protected]9045b8822012-01-13 20:35:353187
[email protected]ef2bf422012-05-11 03:27:093188 TestURLRequestContext context(true);
3189 context.set_network_delegate(&network_delegate);
3190 context.Init();
[email protected]9045b8822012-01-13 20:35:353191
3192 {
[email protected]007b3f82013-04-09 08:46:453193 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353194
3195 r.Start();
[email protected]255620da2013-08-19 13:14:293196 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303197 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3198 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353199 EXPECT_EQ(0, network_delegate.completed_requests());
3200 // Cancel before callback.
3201 r.Cancel();
3202 // Ensure that network delegate is notified.
3203 EXPECT_EQ(1, network_delegate.completed_requests());
3204 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3205 EXPECT_EQ(ERR_ABORTED, r.status().error());
3206 EXPECT_EQ(1, network_delegate.created_requests());
3207 EXPECT_EQ(0, network_delegate.destroyed_requests());
3208 }
3209 EXPECT_EQ(1, network_delegate.destroyed_requests());
3210}
3211
3212// Tests that we can handle when a network request was canceled while we were
3213// waiting for the network delegate.
3214// Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3215TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3216 ASSERT_TRUE(test_server_.Start());
3217
3218 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303219 BlockingNetworkDelegate network_delegate(
3220 BlockingNetworkDelegate::USER_CALLBACK);
3221 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
[email protected]9045b8822012-01-13 20:35:353222
[email protected]ef2bf422012-05-11 03:27:093223 TestURLRequestContext context(true);
3224 context.set_network_delegate(&network_delegate);
3225 context.Init();
[email protected]9045b8822012-01-13 20:35:353226
3227 {
[email protected]007b3f82013-04-09 08:46:453228 URLRequest r(test_server_.GetURL(std::string()), &d, &context);
[email protected]9045b8822012-01-13 20:35:353229
3230 r.Start();
[email protected]255620da2013-08-19 13:14:293231 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303232 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3233 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353234 EXPECT_EQ(0, network_delegate.completed_requests());
3235 // Cancel before callback.
3236 r.Cancel();
3237 // Ensure that network delegate is notified.
3238 EXPECT_EQ(1, network_delegate.completed_requests());
3239 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3240 EXPECT_EQ(ERR_ABORTED, r.status().error());
3241 EXPECT_EQ(1, network_delegate.created_requests());
3242 EXPECT_EQ(0, network_delegate.destroyed_requests());
3243 }
3244 EXPECT_EQ(1, network_delegate.destroyed_requests());
3245}
3246
3247// Tests that we can handle when a network request was canceled while we were
3248// waiting for the network delegate.
3249// Part 4: Request is cancelled while waiting for OnAuthRequired callback.
[email protected]bfe8b302013-02-15 12:16:023250TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
[email protected]9045b8822012-01-13 20:35:353251 ASSERT_TRUE(test_server_.Start());
3252
3253 TestDelegate d;
[email protected]dc5a5cf2012-09-26 02:49:303254 BlockingNetworkDelegate network_delegate(
3255 BlockingNetworkDelegate::USER_CALLBACK);
3256 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
[email protected]9045b8822012-01-13 20:35:353257
[email protected]ef2bf422012-05-11 03:27:093258 TestURLRequestContext context(true);
3259 context.set_network_delegate(&network_delegate);
3260 context.Init();
[email protected]9045b8822012-01-13 20:35:353261
3262 {
[email protected]94e2bbe2012-06-22 15:26:133263 URLRequest r(test_server_.GetURL("auth-basic"), &d, &context);
[email protected]9045b8822012-01-13 20:35:353264
3265 r.Start();
[email protected]255620da2013-08-19 13:14:293266 base::RunLoop().Run();
[email protected]dc5a5cf2012-09-26 02:49:303267 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3268 network_delegate.stage_blocked_for_callback());
[email protected]9045b8822012-01-13 20:35:353269 EXPECT_EQ(0, network_delegate.completed_requests());
3270 // Cancel before callback.
3271 r.Cancel();
3272 // Ensure that network delegate is notified.
3273 EXPECT_EQ(1, network_delegate.completed_requests());
3274 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3275 EXPECT_EQ(ERR_ABORTED, r.status().error());
3276 EXPECT_EQ(1, network_delegate.created_requests());
3277 EXPECT_EQ(0, network_delegate.destroyed_requests());
3278 }
3279 EXPECT_EQ(1, network_delegate.destroyed_requests());
3280}
3281
[email protected]95409e12010-08-17 20:07:113282// In this unit test, we're using the HTTPTestServer as a proxy server and
3283// issuing a CONNECT request with the magic host name "www.server-auth.com".
3284// The HTTPTestServer will return a 401 response, which we should balk at.
[email protected]b89290212009-08-14 22:37:353285TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
[email protected]95409e12010-08-17 20:07:113286 ASSERT_TRUE(test_server_.Start());
3287
[email protected]ceefd7fd2012-11-29 00:36:243288 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]d5a4dd62012-05-23 01:41:043289 TestURLRequestContextWithProxy context(
3290 test_server_.host_port_pair().ToString(),
3291 &network_delegate);
[email protected]87a09a92011-07-14 15:50:503292
[email protected]dc651782009-02-14 01:45:083293 TestDelegate d;
3294 {
[email protected]94e2bbe2012-06-22 15:26:133295 URLRequest r(GURL("https://www.server-auth.com/"), &d, &context);
[email protected]dc651782009-02-14 01:45:083296
3297 r.Start();
3298 EXPECT_TRUE(r.is_pending());
3299
[email protected]255620da2013-08-19 13:14:293300 base::RunLoop().Run();
[email protected]dc651782009-02-14 01:45:083301
[email protected]7461a402011-03-24 23:19:513302 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]d0cc35b2011-09-08 12:02:053303 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
[email protected]dc651782009-02-14 01:45:083304 }
3305}
3306
[email protected]b89290212009-08-14 22:37:353307TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
[email protected]95409e12010-08-17 20:07:113308 ASSERT_TRUE(test_server_.Start());
3309
initial.commit586acc5fe2008-07-26 22:42:523310 TestDelegate d;
3311 {
[email protected]007b3f82013-04-09 08:46:453312 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523313
3314 r.Start();
3315 EXPECT_TRUE(r.is_pending());
3316
[email protected]255620da2013-08-19 13:14:293317 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523318
3319 EXPECT_EQ(1, d.response_started_count());
3320 EXPECT_FALSE(d.received_data_before_response());
3321 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193322 EXPECT_EQ(test_server_.host_port_pair().host(),
3323 r.GetSocketAddress().host());
3324 EXPECT_EQ(test_server_.host_port_pair().port(),
3325 r.GetSocketAddress().port());
[email protected]c31a54592009-09-04 02:36:163326
[email protected]9e743cd2010-03-16 07:03:533327 // TODO(eroman): Add back the NetLog tests...
initial.commit586acc5fe2008-07-26 22:42:523328 }
initial.commit586acc5fe2008-07-26 22:42:523329}
3330
[email protected]263163f2012-06-14 22:40:343331// This test has the server send a large number of cookies to the client.
3332// To ensure that no number of cookies causes a crash, a galloping binary
3333// search is used to estimate that maximum number of cookies that are accepted
3334// by the browser. Beyond the maximum number, the request will fail with
3335// ERR_RESPONSE_HEADERS_TOO_BIG.
[email protected]69dd6fe2013-02-23 23:15:303336#if defined(OS_WIN)
3337// http://crbug.com/177916
3338#define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3339#else
3340#define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3341#endif // defined(OS_WIN)
3342TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
[email protected]263163f2012-06-14 22:40:343343 ASSERT_TRUE(test_server_.Start());
3344
3345 int lower_bound = 0;
3346 int upper_bound = 1;
3347
3348 // Double the number of cookies until the response header limits are
3349 // exceeded.
3350 while (DoManyCookiesRequest(upper_bound)) {
3351 lower_bound = upper_bound;
3352 upper_bound *= 2;
3353 ASSERT_LT(upper_bound, 1000000);
3354 }
3355
3356 int tolerance = upper_bound * 0.005;
3357 if (tolerance < 2)
3358 tolerance = 2;
3359
3360 // Perform a binary search to find the highest possible number of cookies,
3361 // within the desired tolerance.
3362 while (upper_bound - lower_bound >= tolerance) {
3363 int num_cookies = (lower_bound + upper_bound) / 2;
3364
3365 if (DoManyCookiesRequest(num_cookies))
3366 lower_bound = num_cookies;
3367 else
3368 upper_bound = num_cookies;
3369 }
3370 // Success: the test did not crash.
3371}
3372
[email protected]b89290212009-08-14 22:37:353373TEST_F(URLRequestTestHTTP, GetTest) {
[email protected]95409e12010-08-17 20:07:113374 ASSERT_TRUE(test_server_.Start());
3375
initial.commit586acc5fe2008-07-26 22:42:523376 TestDelegate d;
3377 {
[email protected]1e110eae2013-05-10 22:02:403378 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
initial.commit586acc5fe2008-07-26 22:42:523379
3380 r.Start();
3381 EXPECT_TRUE(r.is_pending());
3382
[email protected]255620da2013-08-19 13:14:293383 base::RunLoop().Run();
initial.commit586acc5fe2008-07-26 22:42:523384
3385 EXPECT_EQ(1, d.response_started_count());
3386 EXPECT_FALSE(d.received_data_before_response());
3387 EXPECT_NE(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:193388 EXPECT_EQ(test_server_.host_port_pair().host(),
3389 r.GetSocketAddress().host());
3390 EXPECT_EQ(test_server_.host_port_pair().port(),
3391 r.GetSocketAddress().port());
initial.commit586acc5fe2008-07-26 22:42:523392 }
[email protected]5d7b373e2009-09-02 07:19:033393}
3394
[email protected]79e1fd62013-06-20 06:50:043395TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3396 ASSERT_TRUE(test_server_.Start());
3397
3398 TestDelegate d;
3399 {
3400 GURL test_url(test_server_.GetURL(std::string()));
3401 URLRequest r(test_url, &d, &default_context_);
3402
3403 HttpRequestHeaders headers;
3404 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3405
3406 r.Start();
3407 EXPECT_TRUE(r.is_pending());
3408
[email protected]255620da2013-08-19 13:14:293409 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:043410
3411 EXPECT_EQ(1, d.response_started_count());
3412 EXPECT_FALSE(d.received_data_before_response());
3413 EXPECT_NE(0, d.bytes_received());
3414 EXPECT_EQ(test_server_.host_port_pair().host(),
3415 r.GetSocketAddress().host());
3416 EXPECT_EQ(test_server_.host_port_pair().port(),
3417 r.GetSocketAddress().port());
3418
3419 EXPECT_TRUE(d.have_full_request_headers());
3420 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3421 }
3422}
3423
[email protected]58e32bb2013-01-21 18:23:253424TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3425 ASSERT_TRUE(test_server_.Start());
3426
3427 TestDelegate d;
3428 {
[email protected]007b3f82013-04-09 08:46:453429 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]58e32bb2013-01-21 18:23:253430
3431 r.Start();
3432 EXPECT_TRUE(r.is_pending());
3433
[email protected]255620da2013-08-19 13:14:293434 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253435
3436 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173437 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253438 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3439
3440 EXPECT_EQ(1, d.response_started_count());
3441 EXPECT_FALSE(d.received_data_before_response());
3442 EXPECT_NE(0, d.bytes_received());
3443 EXPECT_EQ(test_server_.host_port_pair().host(),
3444 r.GetSocketAddress().host());
3445 EXPECT_EQ(test_server_.host_port_pair().port(),
3446 r.GetSocketAddress().port());
3447 }
3448}
3449
[email protected]aad63572011-05-24 20:14:393450TEST_F(URLRequestTestHTTP, GetZippedTest) {
3451 ASSERT_TRUE(test_server_.Start());
3452
3453 // Parameter that specifies the Content-Length field in the response:
3454 // C - Compressed length.
3455 // U - Uncompressed length.
3456 // L - Large length (larger than both C & U).
3457 // M - Medium length (between C & U).
3458 // S - Small length (smaller than both C & U).
3459 const char test_parameters[] = "CULMS";
3460 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3461 // C & U should be OK.
[email protected]f0e2bf42011-07-22 21:21:443462 // L & M are larger than the data sent, and show an error.
[email protected]aad63572011-05-24 20:14:393463 // S has too little data, but we seem to accept it.
3464 const bool test_expect_success[num_tests] =
[email protected]f001bd6a2011-12-08 04:31:373465 { true, true, false, false, true };
[email protected]aad63572011-05-24 20:14:393466
3467 for (int i = 0; i < num_tests ; i++) {
3468 TestDelegate d;
3469 {
3470 std::string test_file =
3471 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3472 test_parameters[i]);
[email protected]aad63572011-05-24 20:14:393473
[email protected]ceefd7fd2012-11-29 00:36:243474 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:093475 TestURLRequestContext context(true);
3476 context.set_network_delegate(&network_delegate);
3477 context.Init();
[email protected]87a09a92011-07-14 15:50:503478
[email protected]94e2bbe2012-06-22 15:26:133479 URLRequest r(test_server_.GetURL(test_file), &d, &context);
[email protected]aad63572011-05-24 20:14:393480 r.Start();
3481 EXPECT_TRUE(r.is_pending());
3482
[email protected]255620da2013-08-19 13:14:293483 base::RunLoop().Run();
[email protected]aad63572011-05-24 20:14:393484
3485 EXPECT_EQ(1, d.response_started_count());
3486 EXPECT_FALSE(d.received_data_before_response());
3487 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3488 << " status = " << r.status().status()
[email protected]d0cc35b2011-09-08 12:02:053489 << " error = " << r.status().error();
[email protected]aad63572011-05-24 20:14:393490 if (test_expect_success[i]) {
3491 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3492 << " Parameter = \"" << test_file << "\"";
3493 } else {
3494 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
[email protected]5543cbb2012-04-20 16:35:233495 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
[email protected]aad63572011-05-24 20:14:393496 << " Parameter = \"" << test_file << "\"";
3497 }
3498 }
3499 }
3500}
3501
[email protected]c044616e2013-02-20 02:01:263502TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
[email protected]95409e12010-08-17 20:07:113503 ASSERT_TRUE(test_server_.Start());
3504
[email protected]ce7d0cbc2013-05-03 18:57:223505 SpawnedTestServer https_test_server(
3506 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:153507 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:113508 ASSERT_TRUE(https_test_server.Start());
[email protected]7844480a2009-12-16 21:18:583509
3510 // An https server is sent a request with an https referer,
3511 // and responds with a redirect to an http url. The http
3512 // server should not be sent the referer.
[email protected]007b3f82013-04-09 08:46:453513 GURL http_destination = test_server_.GetURL(std::string());
[email protected]7844480a2009-12-16 21:18:583514 TestDelegate d;
[email protected]ef2bf422012-05-11 03:27:093515 URLRequest req(https_test_server.GetURL(
[email protected]94e2bbe2012-06-22 15:26:133516 "server-redirect?" + http_destination.spec()), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:133517 req.SetReferrer("https://www.referrer.com/");
[email protected]7844480a2009-12-16 21:18:583518 req.Start();
[email protected]255620da2013-08-19 13:14:293519 base::RunLoop().Run();
[email protected]7844480a2009-12-16 21:18:583520
3521 EXPECT_EQ(1, d.response_started_count());
3522 EXPECT_EQ(1, d.received_redirect_count());
3523 EXPECT_EQ(http_destination, req.url());
3524 EXPECT_EQ(std::string(), req.referrer());
3525}
3526
[email protected]58e32bb2013-01-21 18:23:253527TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3528 ASSERT_TRUE(test_server_.Start());
3529
[email protected]007b3f82013-04-09 08:46:453530 GURL destination_url = test_server_.GetURL(std::string());
3531 GURL original_url =
3532 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]58e32bb2013-01-21 18:23:253533 TestDelegate d;
3534 URLRequest req(original_url, &d, &default_context_);
3535 req.Start();
[email protected]255620da2013-08-19 13:14:293536 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:253537
3538 EXPECT_EQ(1, d.response_started_count());
3539 EXPECT_EQ(1, d.received_redirect_count());
3540 EXPECT_EQ(destination_url, req.url());
3541 EXPECT_EQ(original_url, req.original_url());
3542 ASSERT_EQ(2U, req.url_chain().size());
3543 EXPECT_EQ(original_url, req.url_chain()[0]);
3544 EXPECT_EQ(destination_url, req.url_chain()[1]);
3545
3546 LoadTimingInfo load_timing_info_before_redirect;
3547 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3548 &load_timing_info_before_redirect));
3549 TestLoadTimingNotReused(load_timing_info_before_redirect,
3550 CONNECT_TIMING_HAS_DNS_TIMES);
3551
3552 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:173553 req.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:253554 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3555
3556 // Check that a new socket was used on redirect, since the server does not
3557 // supposed keep-alive sockets, and that the times before the redirect are
3558 // before the ones recorded for the second request.
3559 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3560 load_timing_info.socket_log_id);
3561 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3562 load_timing_info.connect_timing.connect_start);
3563}
3564
[email protected]8f1ac082011-04-19 21:14:133565TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3566 ASSERT_TRUE(test_server_.Start());
3567
[email protected]007b3f82013-04-09 08:46:453568 GURL destination_url = test_server_.GetURL(std::string());
3569 GURL middle_redirect_url =
3570 test_server_.GetURL("server-redirect?" + destination_url.spec());
[email protected]8f1ac082011-04-19 21:14:133571 GURL original_url = test_server_.GetURL(
3572 "server-redirect?" + middle_redirect_url.spec());
3573 TestDelegate d;
[email protected]94e2bbe2012-06-22 15:26:133574 URLRequest req(original_url, &d, &default_context_);
[email protected]8f1ac082011-04-19 21:14:133575 req.Start();
[email protected]255620da2013-08-19 13:14:293576 base::RunLoop().Run();
[email protected]8f1ac082011-04-19 21:14:133577
3578 EXPECT_EQ(1, d.response_started_count());
3579 EXPECT_EQ(2, d.received_redirect_count());
3580 EXPECT_EQ(destination_url, req.url());
3581 EXPECT_EQ(original_url, req.original_url());
3582 ASSERT_EQ(3U, req.url_chain().size());
3583 EXPECT_EQ(original_url, req.url_chain()[0]);
3584 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3585 EXPECT_EQ(destination_url, req.url_chain()[2]);
3586}
3587
[email protected]abe1c4a2013-10-25 19:28:513588// First and second pieces of information logged by delegates to URLRequests.
3589const char kFirstDelegateInfo[] = "Wonderful delegate";
3590const char kSecondDelegateInfo[] = "Exciting delegate";
3591
3592// Logs delegate information to a URLRequest. The first string is logged
3593// synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3594// logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3595// another asynchronous call is used to clear the delegate information
3596// before calling a callback. The object then deletes itself.
3597class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3598 public:
3599 typedef base::Callback<void()> Callback;
3600
3601 // Each time delegate information is added to the URLRequest, the resulting
3602 // load state is checked. The expected load state after each request is
3603 // passed in as an argument.
3604 static void Run(URLRequest* url_request,
3605 LoadState expected_first_load_state,
3606 LoadState expected_second_load_state,
3607 LoadState expected_third_load_state,
3608 const Callback& callback) {
3609 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3610 url_request,
3611 expected_first_load_state,
3612 expected_second_load_state,
3613 expected_third_load_state,
3614 callback);
3615 logger->Start();
3616 }
3617
3618 // Checks that the log entries, starting with log_position, contain the
3619 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3620 // recorded. Returns the index of entry after the expected number of
3621 // events this logged, or entries.size() if there aren't enough entries.
3622 static size_t CheckDelegateInfo(
3623 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3624 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3625 if (log_position + 3 >= entries.size()) {
3626 ADD_FAILURE() << "Not enough log entries";
3627 return entries.size();
3628 }
3629 std::string delegate_info;
3630 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3631 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3632 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3633 &delegate_info));
3634 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3635
3636 ++log_position;
3637 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3638 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3639
3640 ++log_position;
3641 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3642 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3643 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3644 &delegate_info));
3645 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3646
3647 ++log_position;
3648 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3649 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3650
3651 return log_position + 1;
3652 }
3653
3654 private:
3655 friend class base::RefCounted<AsyncDelegateLogger>;
3656
3657 AsyncDelegateLogger(URLRequest* url_request,
3658 LoadState expected_first_load_state,
3659 LoadState expected_second_load_state,
3660 LoadState expected_third_load_state,
3661 const Callback& callback)
3662 : url_request_(url_request),
3663 expected_first_load_state_(expected_first_load_state),
3664 expected_second_load_state_(expected_second_load_state),
3665 expected_third_load_state_(expected_third_load_state),
3666 callback_(callback) {
3667 }
3668
3669 ~AsyncDelegateLogger() {}
3670
3671 void Start() {
3672 url_request_->SetDelegateInfo(kFirstDelegateInfo,
3673 URLRequest::DELEGATE_INFO_DEBUG_ONLY);
3674 LoadStateWithParam load_state = url_request_->GetLoadState();
3675 EXPECT_EQ(expected_first_load_state_, load_state.state);
3676 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3677 base::MessageLoop::current()->PostTask(
3678 FROM_HERE,
3679 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3680 }
3681
3682 void LogSecondDelegate() {
3683 url_request_->SetDelegateInfo(kSecondDelegateInfo,
3684 URLRequest::DELEGATE_INFO_DISPLAY_TO_USER);
3685 LoadStateWithParam load_state = url_request_->GetLoadState();
3686 EXPECT_EQ(expected_second_load_state_, load_state.state);
3687 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3688 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3689 } else {
3690 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3691 }
3692 base::MessageLoop::current()->PostTask(
3693 FROM_HERE,
3694 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3695 }
3696
3697 void LogComplete() {
3698 url_request_->SetDelegateInfo(
3699 NULL, URLRequest::DELEGATE_INFO_DISPLAY_TO_USER);
3700 LoadStateWithParam load_state = url_request_->GetLoadState();
3701 EXPECT_EQ(expected_third_load_state_, load_state.state);
3702 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3703 EXPECT_EQ(string16(), load_state.param);
3704 callback_.Run();
3705 }
3706
3707 URLRequest* url_request_;
3708 const int expected_first_load_state_;
3709 const int expected_second_load_state_;
3710 const int expected_third_load_state_;
3711 const Callback callback_;
3712
3713 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3714};
3715
3716// NetworkDelegate that logs delegate information before a request is started,
3717// before headers are sent, when headers are read, and when auth information
3718// is requested. Uses AsyncDelegateLogger.
3719class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3720 public:
3721 AsyncLoggingNetworkDelegate() {}
3722 virtual ~AsyncLoggingNetworkDelegate() {}
3723
3724 // NetworkDelegate implementation.
3725 virtual int OnBeforeURLRequest(URLRequest* request,
3726 const CompletionCallback& callback,
3727 GURL* new_url) OVERRIDE {
3728 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3729 return RunCallbackAsynchronously(request, callback);
3730 }
3731
3732 virtual int OnBeforeSendHeaders(URLRequest* request,
3733 const CompletionCallback& callback,
3734 HttpRequestHeaders* headers) OVERRIDE {
3735 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3736 return RunCallbackAsynchronously(request, callback);
3737 }
3738
3739 virtual int OnHeadersReceived(
3740 URLRequest* request,
3741 const CompletionCallback& callback,
3742 const HttpResponseHeaders* original_response_headers,
3743 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE {
3744 TestNetworkDelegate::OnHeadersReceived(request, callback,
3745 original_response_headers,
3746 override_response_headers);
3747 return RunCallbackAsynchronously(request, callback);
3748 }
3749
3750 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3751 URLRequest* request,
3752 const AuthChallengeInfo& auth_info,
3753 const AuthCallback& callback,
3754 AuthCredentials* credentials) OVERRIDE {
3755 AsyncDelegateLogger::Run(
3756 request,
3757 LOAD_STATE_WAITING_FOR_DELEGATE,
3758 LOAD_STATE_WAITING_FOR_DELEGATE,
3759 LOAD_STATE_WAITING_FOR_DELEGATE,
3760 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3761 callback, credentials));
3762 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3763 }
3764
3765 private:
3766 static int RunCallbackAsynchronously(
3767 URLRequest* request,
3768 const CompletionCallback& callback) {
3769 AsyncDelegateLogger::Run(
3770 request,
3771 LOAD_STATE_WAITING_FOR_DELEGATE,
3772 LOAD_STATE_WAITING_FOR_DELEGATE,
3773 LOAD_STATE_WAITING_FOR_DELEGATE,
3774 base::Bind(callback, OK));
3775 return ERR_IO_PENDING;
3776 }
3777
3778 static void SetAuthAndResume(const AuthCallback& callback,
3779 AuthCredentials* credentials) {
3780 *credentials = AuthCredentials(kUser, kSecret);
3781 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3782 }
3783
3784 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
3785};
3786
3787// URLRequest::Delegate that logs delegate information when the headers
3788// are received, when each read completes, and during redirects. Uses
3789// AsyncDelegateLogger. Can optionally cancel a request in any phase.
3790//
3791// Inherits from TestDelegate to reuse the TestDelegate code to handle
3792// advancing to the next step in most cases, as well as cancellation.
3793class AsyncLoggingUrlRequestDelegate : public TestDelegate {
3794 public:
3795 enum CancelStage {
3796 NO_CANCEL = 0,
3797 CANCEL_ON_RECEIVED_REDIRECT,
3798 CANCEL_ON_RESPONSE_STARTED,
3799 CANCEL_ON_READ_COMPLETED
3800 };
3801
3802 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
3803 : cancel_stage_(cancel_stage) {
3804 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
3805 set_cancel_in_received_redirect(true);
3806 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
3807 set_cancel_in_response_started(true);
3808 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
3809 set_cancel_in_received_data(true);
3810 }
3811 virtual ~AsyncLoggingUrlRequestDelegate() {}
3812
3813 // URLRequest::Delegate implementation:
3814 void virtual OnReceivedRedirect(URLRequest* request,
3815 const GURL& new_url,
3816 bool* defer_redirect) OVERRIDE {
3817 *defer_redirect = true;
3818 AsyncDelegateLogger::Run(
3819 request,
3820 LOAD_STATE_WAITING_FOR_DELEGATE,
3821 LOAD_STATE_WAITING_FOR_DELEGATE,
3822 LOAD_STATE_WAITING_FOR_DELEGATE,
3823 base::Bind(
3824 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
3825 base::Unretained(this), request, new_url));
3826 }
3827
3828 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
3829 AsyncDelegateLogger::Run(
3830 request,
3831 LOAD_STATE_WAITING_FOR_DELEGATE,
3832 LOAD_STATE_WAITING_FOR_DELEGATE,
3833 LOAD_STATE_WAITING_FOR_DELEGATE,
3834 base::Bind(
3835 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
3836 base::Unretained(this), request));
3837 }
3838
3839 virtual void OnReadCompleted(URLRequest* request,
3840 int bytes_read) OVERRIDE {
3841 AsyncDelegateLogger::Run(
3842 request,
3843 LOAD_STATE_IDLE,
3844 LOAD_STATE_IDLE,
3845 LOAD_STATE_IDLE,
3846 base::Bind(
3847 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
3848 base::Unretained(this), request, bytes_read));
3849 }
3850
3851 private:
3852 void OnReceivedRedirectLoggingComplete(URLRequest* request,
3853 const GURL& new_url) {
3854 bool defer_redirect = false;
3855 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
3856 // FollowDeferredRedirect should not be called after cancellation.
3857 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
3858 return;
3859 if (!defer_redirect)
3860 request->FollowDeferredRedirect();
3861 }
3862
3863 void OnResponseStartedLoggingComplete(URLRequest* request) {
3864 // The parent class continues the request.
3865 TestDelegate::OnResponseStarted(request);
3866 }
3867
3868 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
3869 // The parent class continues the request.
3870 TestDelegate::OnReadCompleted(request, bytes_read);
3871 }
3872
3873 const CancelStage cancel_stage_;
3874
3875 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
3876};
3877
3878// Tests handling of delegate info before a request starts.
3879TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
3880 ASSERT_TRUE(test_server_.Start());
3881
3882 TestDelegate request_delegate;
3883 TestURLRequestContext context(true);
3884 context.set_network_delegate(NULL);
3885 context.set_net_log(&net_log_);
3886 context.Init();
3887
3888 {
3889 URLRequest r(test_server_.GetURL("empty.html"),
3890 &request_delegate, &context);
3891 LoadStateWithParam load_state = r.GetLoadState();
3892 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
3893 EXPECT_EQ(string16(), load_state.param);
3894
3895 AsyncDelegateLogger::Run(
3896 &r,
3897 LOAD_STATE_WAITING_FOR_DELEGATE,
3898 LOAD_STATE_WAITING_FOR_DELEGATE,
3899 LOAD_STATE_IDLE,
3900 base::Bind(&URLRequest::Start, base::Unretained(&r)));
3901
3902 base::RunLoop().Run();
3903
3904 EXPECT_EQ(200, r.GetResponseCode());
3905 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3906 }
3907
3908 CapturingNetLog::CapturedEntryList entries;
3909 net_log_.GetEntries(&entries);
3910 size_t log_position = ExpectLogContainsSomewhereAfter(
3911 entries,
3912 0,
3913 NetLog::TYPE_DELEGATE_INFO,
3914 NetLog::PHASE_BEGIN);
3915
3916 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
3917
3918 // Nothing else should add any delegate info to the request.
3919 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3920 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
3921}
3922
3923// Tests handling of delegate info from a network delegate.
3924TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
3925 ASSERT_TRUE(test_server_.Start());
3926
3927 TestDelegate request_delegate;
3928 AsyncLoggingNetworkDelegate network_delegate;
3929 TestURLRequestContext context(true);
3930 context.set_network_delegate(&network_delegate);
3931 context.set_net_log(&net_log_);
3932 context.Init();
3933
3934 {
3935 URLRequest r(test_server_.GetURL("simple.html"),
3936 &request_delegate, &context);
3937 LoadStateWithParam load_state = r.GetLoadState();
3938 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
3939 EXPECT_EQ(string16(), load_state.param);
3940
3941 r.Start();
3942 base::RunLoop().Run();
3943
3944 EXPECT_EQ(200, r.GetResponseCode());
3945 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3946 EXPECT_EQ(1, network_delegate.created_requests());
3947 EXPECT_EQ(0, network_delegate.destroyed_requests());
3948 }
3949 EXPECT_EQ(1, network_delegate.destroyed_requests());
3950
3951 size_t log_position = 0;
3952 CapturingNetLog::CapturedEntryList entries;
3953 net_log_.GetEntries(&entries);
3954 for (size_t i = 0; i < 3; ++i) {
3955 log_position = ExpectLogContainsSomewhereAfter(
3956 entries,
3957 log_position + 1,
3958 NetLog::TYPE_URL_REQUEST_DELEGATE,
3959 NetLog::PHASE_BEGIN);
3960
3961 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
3962 log_position + 1);
3963
3964 ASSERT_LT(log_position, entries.size());
3965 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
3966 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3967 }
3968
3969 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
3970 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
3971}
3972
3973// Tests handling of delegate info from a network delegate in the case of an
3974// HTTP redirect.
3975TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
3976 ASSERT_TRUE(test_server_.Start());
3977
3978 TestDelegate request_delegate;
3979 AsyncLoggingNetworkDelegate network_delegate;
3980 TestURLRequestContext context(true);
3981 context.set_network_delegate(&network_delegate);
3982 context.set_net_log(&net_log_);
3983 context.Init();
3984
3985 {
3986 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
3987 &request_delegate, &context);
3988 LoadStateWithParam load_state = r.GetLoadState();
3989 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
3990 EXPECT_EQ(string16(), load_state.param);
3991
3992 r.Start();
3993 base::RunLoop().Run();
3994
3995 EXPECT_EQ(200, r.GetResponseCode());
3996 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3997 EXPECT_EQ(2, network_delegate.created_requests());
3998 EXPECT_EQ(0, network_delegate.destroyed_requests());
3999 }
4000 EXPECT_EQ(1, network_delegate.destroyed_requests());
4001
4002 size_t log_position = 0;
4003 CapturingNetLog::CapturedEntryList entries;
4004 net_log_.GetEntries(&entries);
4005 // The NetworkDelegate logged information in OnBeforeURLRequest,
4006 // OnBeforeSendHeaders, and OnHeadersReceived.
4007 for (size_t i = 0; i < 3; ++i) {
4008 log_position = ExpectLogContainsSomewhereAfter(
4009 entries,
4010 log_position + 1,
4011 NetLog::TYPE_URL_REQUEST_DELEGATE,
4012 NetLog::PHASE_BEGIN);
4013
4014 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4015 log_position + 1);
4016
4017 ASSERT_LT(log_position, entries.size());
4018 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4019 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4020 }
4021
4022 // The URLRequest::Delegate then gets informed about the redirect.
4023 log_position = ExpectLogContainsSomewhereAfter(
4024 entries,
4025 log_position + 1,
4026 NetLog::TYPE_URL_REQUEST_DELEGATE,
4027 NetLog::PHASE_BEGIN);
4028
4029 // The NetworkDelegate logged information in the same three events as before.
4030 for (size_t i = 0; i < 3; ++i) {
4031 log_position = ExpectLogContainsSomewhereAfter(
4032 entries,
4033 log_position + 1,
4034 NetLog::TYPE_URL_REQUEST_DELEGATE,
4035 NetLog::PHASE_BEGIN);
4036
4037 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4038 log_position + 1);
4039
4040 ASSERT_LT(log_position, entries.size());
4041 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4042 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4043 }
4044
4045 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4046 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4047}
4048
4049// Tests handling of delegate info from a network delegate in the case of HTTP
4050// AUTH.
4051TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4052 ASSERT_TRUE(test_server_.Start());
4053
4054 TestDelegate request_delegate;
4055 AsyncLoggingNetworkDelegate network_delegate;
4056 TestURLRequestContext context(true);
4057 context.set_network_delegate(&network_delegate);
4058 context.set_net_log(&net_log_);
4059 context.Init();
4060
4061 {
4062 URLRequest r(test_server_.GetURL("auth-basic"),
4063 &request_delegate, &context);
4064 LoadStateWithParam load_state = r.GetLoadState();
4065 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4066 EXPECT_EQ(string16(), load_state.param);
4067
4068 r.Start();
4069 base::RunLoop().Run();
4070
4071 EXPECT_EQ(200, r.GetResponseCode());
4072 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4073 EXPECT_EQ(1, network_delegate.created_requests());
4074 EXPECT_EQ(0, network_delegate.destroyed_requests());
4075 }
4076 EXPECT_EQ(1, network_delegate.destroyed_requests());
4077
4078 size_t log_position = 0;
4079 CapturingNetLog::CapturedEntryList entries;
4080 net_log_.GetEntries(&entries);
4081 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4082 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4083 // OnBeforeURLRequest and OnBeforeSendHeaders.
4084 for (size_t i = 0; i < 6; ++i) {
4085 log_position = ExpectLogContainsSomewhereAfter(
4086 entries,
4087 log_position + 1,
4088 NetLog::TYPE_URL_REQUEST_DELEGATE,
4089 NetLog::PHASE_BEGIN);
4090
4091 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4092 log_position + 1);
4093
4094 ASSERT_LT(log_position, entries.size());
4095 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4096 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4097 }
4098
4099 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4100 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4101}
4102
4103// Tests handling of delegate info from a URLRequest::Delegate.
4104TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4105 ASSERT_TRUE(test_server_.Start());
4106
4107 AsyncLoggingUrlRequestDelegate request_delegate(
4108 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4109 TestURLRequestContext context(true);
4110 context.set_network_delegate(NULL);
4111 context.set_net_log(&net_log_);
4112 context.Init();
4113
4114 {
4115 // A chunked response with delays between chunks is used to make sure that
4116 // attempts by the URLRequest delegate to log information while reading the
4117 // body are ignored. Since they are ignored, this test is robust against
4118 // the possability of multiple reads being combined in the unlikely event
4119 // that it occurs.
4120 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
4121 &request_delegate, &context);
4122 LoadStateWithParam load_state = r.GetLoadState();
4123 r.Start();
4124 base::RunLoop().Run();
4125
4126 EXPECT_EQ(200, r.GetResponseCode());
4127 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4128 }
4129
4130 CapturingNetLog::CapturedEntryList entries;
4131 net_log_.GetEntries(&entries);
4132
4133 // The delegate info should only have been logged on header complete. Other
4134 // times it should silently be ignored.
4135
4136 size_t log_position = ExpectLogContainsSomewhereAfter(
4137 entries,
4138 0,
4139 NetLog::TYPE_URL_REQUEST_DELEGATE,
4140 NetLog::PHASE_BEGIN);
4141
4142 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4143 log_position + 1);
4144
4145 ASSERT_LT(log_position, entries.size());
4146 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4147 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4148
4149 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4150 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4151 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4152 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4153}
4154
4155// Tests handling of delegate info from a URLRequest::Delegate in the case of
4156// an HTTP redirect.
4157TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4158 ASSERT_TRUE(test_server_.Start());
4159
4160 AsyncLoggingUrlRequestDelegate request_delegate(
4161 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4162 TestURLRequestContext context(true);
4163 context.set_network_delegate(NULL);
4164 context.set_net_log(&net_log_);
4165 context.Init();
4166
4167 {
4168 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4169 &request_delegate, &context);
4170 LoadStateWithParam load_state = r.GetLoadState();
4171 r.Start();
4172 base::RunLoop().Run();
4173
4174 EXPECT_EQ(200, r.GetResponseCode());
4175 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4176 }
4177
4178 CapturingNetLog::CapturedEntryList entries;
4179 net_log_.GetEntries(&entries);
4180
4181 // Delegate info should only have been logged in OnReceivedRedirect and
4182 // OnResponseStarted.
4183 size_t log_position = 0;
4184 for (int i = 0; i < 2; ++i) {
4185 log_position = ExpectLogContainsSomewhereAfter(
4186 entries,
4187 log_position,
4188 NetLog::TYPE_URL_REQUEST_DELEGATE,
4189 NetLog::PHASE_BEGIN);
4190
4191 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4192 log_position + 1);
4193
4194 ASSERT_LT(log_position, entries.size());
4195 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4196 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4197 }
4198
4199 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4200 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4201 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4202 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4203}
4204
4205// Tests handling of delegate info from a URLRequest::Delegate in the case of
4206// an HTTP redirect, with cancellation at various points.
4207TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4208 ASSERT_TRUE(test_server_.Start());
4209
4210 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4211 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4212 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4213 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4214 };
4215
4216 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4217 ++test_case) {
4218 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4219 TestURLRequestContext context(true);
4220 CapturingNetLog net_log;
4221 context.set_network_delegate(NULL);
4222 context.set_net_log(&net_log);
4223 context.Init();
4224
4225 {
4226 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4227 &request_delegate, &context);
4228 LoadStateWithParam load_state = r.GetLoadState();
4229 r.Start();
4230 base::RunLoop().Run();
4231 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4232 }
4233
4234 CapturingNetLog::CapturedEntryList entries;
4235 net_log.GetEntries(&entries);
4236
4237 // Delegate info is always logged in both OnReceivedRedirect and
4238 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4239 // OnResponseStarted delegate call is after cancellation, but logging is
4240 // still currently supported in that call.
4241 size_t log_position = 0;
4242 for (int i = 0; i < 2; ++i) {
4243 log_position = ExpectLogContainsSomewhereAfter(
4244 entries,
4245 log_position,
4246 NetLog::TYPE_URL_REQUEST_DELEGATE,
4247 NetLog::PHASE_BEGIN);
4248
4249 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4250 log_position + 1);
4251
4252 ASSERT_LT(log_position, entries.size());
4253 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4254 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4255 }
4256
4257 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4258 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4259 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4260 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4261 }
4262}
4263
[email protected]847c0fa92012-11-06 16:37:424264namespace {
4265
4266const char kExtraHeader[] = "Allow-Snafu";
4267const char kExtraValue[] = "fubar";
4268
4269class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164270 virtual void OnReceivedRedirect(net::URLRequest* request,
4271 const GURL& new_url,
4272 bool* defer_redirect) OVERRIDE {
[email protected]847c0fa92012-11-06 16:37:424273 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4274 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4275 }
4276};
4277
4278} // namespace
4279
4280TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4281 ASSERT_TRUE(test_server_.Start());
4282
4283 GURL destination_url = test_server_.GetURL(
4284 "echoheader?" + std::string(kExtraHeader));
4285 GURL original_url = test_server_.GetURL(
4286 "server-redirect?" + destination_url.spec());
4287 RedirectWithAdditionalHeadersDelegate d;
4288 URLRequest req(original_url, &d, &default_context_);
4289 req.Start();
[email protected]255620da2013-08-19 13:14:294290 base::RunLoop().Run();
[email protected]847c0fa92012-11-06 16:37:424291
4292 std::string value;
4293 const HttpRequestHeaders& headers = req.extra_request_headers();
4294 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4295 EXPECT_EQ(kExtraValue, value);
4296 EXPECT_FALSE(req.is_pending());
4297 EXPECT_FALSE(req.is_redirecting());
4298 EXPECT_EQ(kExtraValue, d.data_received());
4299}
4300
[email protected]251a1b92012-11-13 11:01:094301namespace {
4302
4303const char kExtraHeaderToRemove[] = "To-Be-Removed";
4304
4305class RedirectWithHeaderRemovalDelegate : public TestDelegate {
[email protected]46fadfd2013-02-06 09:40:164306 virtual void OnReceivedRedirect(net::URLRequest* request,
[email protected]251a1b92012-11-13 11:01:094307 const GURL& new_url,
[email protected]46fadfd2013-02-06 09:40:164308 bool* defer_redirect) OVERRIDE {
[email protected]251a1b92012-11-13 11:01:094309 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4310 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4311 }
4312};
4313
4314} // namespace
4315
4316TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4317 ASSERT_TRUE(test_server_.Start());
4318
4319 GURL destination_url = test_server_.GetURL(
4320 "echoheader?" + std::string(kExtraHeaderToRemove));
4321 GURL original_url = test_server_.GetURL(
4322 "server-redirect?" + destination_url.spec());
4323 RedirectWithHeaderRemovalDelegate d;
4324 URLRequest req(original_url, &d, &default_context_);
4325 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4326 req.Start();
[email protected]255620da2013-08-19 13:14:294327 base::RunLoop().Run();
[email protected]251a1b92012-11-13 11:01:094328
4329 std::string value;
4330 const HttpRequestHeaders& headers = req.extra_request_headers();
4331 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4332 EXPECT_FALSE(req.is_pending());
4333 EXPECT_FALSE(req.is_redirecting());
4334 EXPECT_EQ("None", d.data_received());
4335}
4336
[email protected]316c1e5e2012-09-12 15:17:444337TEST_F(URLRequestTestHTTP, CancelTest) {
4338 TestDelegate d;
4339 {
4340 URLRequest r(GURL("http://www.google.com/"), &d, &default_context_);
4341
4342 r.Start();
4343 EXPECT_TRUE(r.is_pending());
4344
4345 r.Cancel();
4346
[email protected]255620da2013-08-19 13:14:294347 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444348
4349 // We expect to receive OnResponseStarted even though the request has been
4350 // cancelled.
4351 EXPECT_EQ(1, d.response_started_count());
4352 EXPECT_EQ(0, d.bytes_received());
4353 EXPECT_FALSE(d.received_data_before_response());
4354 }
4355}
4356
4357TEST_F(URLRequestTestHTTP, CancelTest2) {
4358 ASSERT_TRUE(test_server_.Start());
4359
4360 TestDelegate d;
4361 {
[email protected]007b3f82013-04-09 08:46:454362 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444363
4364 d.set_cancel_in_response_started(true);
4365
4366 r.Start();
4367 EXPECT_TRUE(r.is_pending());
4368
[email protected]255620da2013-08-19 13:14:294369 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444370
4371 EXPECT_EQ(1, d.response_started_count());
4372 EXPECT_EQ(0, d.bytes_received());
4373 EXPECT_FALSE(d.received_data_before_response());
4374 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4375 }
4376}
4377
4378TEST_F(URLRequestTestHTTP, CancelTest3) {
4379 ASSERT_TRUE(test_server_.Start());
4380
4381 TestDelegate d;
4382 {
[email protected]007b3f82013-04-09 08:46:454383 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444384
4385 d.set_cancel_in_received_data(true);
4386
4387 r.Start();
4388 EXPECT_TRUE(r.is_pending());
4389
[email protected]255620da2013-08-19 13:14:294390 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444391
4392 EXPECT_EQ(1, d.response_started_count());
4393 // There is no guarantee about how much data was received
4394 // before the cancel was issued. It could have been 0 bytes,
4395 // or it could have been all the bytes.
4396 // EXPECT_EQ(0, d.bytes_received());
4397 EXPECT_FALSE(d.received_data_before_response());
4398 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4399 }
4400}
4401
4402TEST_F(URLRequestTestHTTP, CancelTest4) {
4403 ASSERT_TRUE(test_server_.Start());
4404
4405 TestDelegate d;
4406 {
[email protected]007b3f82013-04-09 08:46:454407 URLRequest r(test_server_.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:444408
4409 r.Start();
4410 EXPECT_TRUE(r.is_pending());
4411
4412 // The request will be implicitly canceled when it is destroyed. The
4413 // test delegate must not post a quit message when this happens because
4414 // this test doesn't actually have a message loop. The quit message would
4415 // get put on this thread's message queue and the next test would exit
4416 // early, causing problems.
4417 d.set_quit_on_complete(false);
4418 }
4419 // expect things to just cleanup properly.
4420
4421 // we won't actually get a received reponse here because we've never run the
4422 // message loop
4423 EXPECT_FALSE(d.received_data_before_response());
4424 EXPECT_EQ(0, d.bytes_received());
4425}
4426
4427TEST_F(URLRequestTestHTTP, CancelTest5) {
4428 ASSERT_TRUE(test_server_.Start());
4429
4430 // populate cache
4431 {
4432 TestDelegate d;
4433 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
4434 r.Start();
[email protected]255620da2013-08-19 13:14:294435 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444436 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4437 }
4438
4439 // cancel read from cache (see bug 990242)
4440 {
4441 TestDelegate d;
4442 URLRequest r(test_server_.GetURL("cachetime"), &d, &default_context_);
4443 r.Start();
4444 r.Cancel();
[email protected]255620da2013-08-19 13:14:294445 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444446
4447 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4448 EXPECT_EQ(1, d.response_started_count());
4449 EXPECT_EQ(0, d.bytes_received());
4450 EXPECT_FALSE(d.received_data_before_response());
4451 }
4452}
4453
4454TEST_F(URLRequestTestHTTP, PostTest) {
4455 ASSERT_TRUE(test_server_.Start());
4456 HTTPUploadDataOperationTest("POST");
4457}
4458
4459TEST_F(URLRequestTestHTTP, PutTest) {
4460 ASSERT_TRUE(test_server_.Start());
4461 HTTPUploadDataOperationTest("PUT");
4462}
4463
4464TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4465 ASSERT_TRUE(test_server_.Start());
4466
4467 TestDelegate d;
4468 {
4469 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
4470 r.set_method("POST");
4471
4472 r.Start();
4473 EXPECT_TRUE(r.is_pending());
4474
[email protected]255620da2013-08-19 13:14:294475 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444476
[email protected]329b68b2012-11-14 17:54:274477 ASSERT_EQ(1, d.response_started_count())
4478 << "request failed: " << r.status().status()
4479 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444480
4481 EXPECT_FALSE(d.received_data_before_response());
4482 EXPECT_TRUE(d.data_received().empty());
4483 }
4484}
4485
4486TEST_F(URLRequestTestHTTP, PostFileTest) {
4487 ASSERT_TRUE(test_server_.Start());
4488
4489 TestDelegate d;
4490 {
4491 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
4492 r.set_method("POST");
4493
[email protected]6cdfd7f2013-02-08 20:40:154494 base::FilePath dir;
[email protected]316c1e5e2012-09-12 15:17:444495 PathService::Get(base::DIR_EXE, &dir);
4496 file_util::SetCurrentDirectory(dir);
4497
[email protected]f288ef02012-12-15 20:28:284498 ScopedVector<UploadElementReader> element_readers;
[email protected]316c1e5e2012-09-12 15:17:444499
[email protected]6cdfd7f2013-02-08 20:40:154500 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444501 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4502 path = path.Append(FILE_PATH_LITERAL("net"));
4503 path = path.Append(FILE_PATH_LITERAL("data"));
4504 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4505 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
[email protected]cadac622013-06-11 16:46:364506 element_readers.push_back(
4507 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4508 path,
4509 0,
4510 kuint64max,
4511 base::Time()));
[email protected]316c1e5e2012-09-12 15:17:444512
4513 // This file should just be ignored in the upload stream.
[email protected]f288ef02012-12-15 20:28:284514 element_readers.push_back(new UploadFileElementReader(
[email protected]cadac622013-06-11 16:46:364515 base::MessageLoopProxy::current().get(),
[email protected]6cdfd7f2013-02-08 20:40:154516 base::FilePath(FILE_PATH_LITERAL(
[email protected]316c1e5e2012-09-12 15:17:444517 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
[email protected]cadac622013-06-11 16:46:364518 0,
4519 kuint64max,
4520 base::Time()));
[email protected]96c77a72013-09-24 09:49:204521 r.set_upload(make_scoped_ptr(
4522 new UploadDataStream(element_readers.Pass(), 0)));
[email protected]316c1e5e2012-09-12 15:17:444523
4524 r.Start();
4525 EXPECT_TRUE(r.is_pending());
4526
[email protected]255620da2013-08-19 13:14:294527 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444528
[email protected]329b68b2012-11-14 17:54:274529 int64 size = 0;
4530 ASSERT_EQ(true, file_util::GetFileSize(path, &size));
[email protected]4356f0f2013-04-07 00:58:174531 scoped_ptr<char[]> buf(new char[size]);
[email protected]316c1e5e2012-09-12 15:17:444532
[email protected]329b68b2012-11-14 17:54:274533 ASSERT_EQ(size, file_util::ReadFile(path, buf.get(), size));
[email protected]316c1e5e2012-09-12 15:17:444534
[email protected]329b68b2012-11-14 17:54:274535 ASSERT_EQ(1, d.response_started_count())
4536 << "request failed: " << r.status().status()
4537 << ", error: " << r.status().error();
[email protected]316c1e5e2012-09-12 15:17:444538
4539 EXPECT_FALSE(d.received_data_before_response());
4540
[email protected]329b68b2012-11-14 17:54:274541 EXPECT_EQ(size, d.bytes_received());
4542 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
[email protected]316c1e5e2012-09-12 15:17:444543 }
4544}
4545
4546TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4547 ASSERT_TRUE(test_server_.Start());
4548
4549 TestDelegate d;
4550 {
4551 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
4552 r.EnableChunkedUpload();
4553 r.set_method("POST");
4554 AddChunksToUpload(&r);
4555 r.Start();
4556 EXPECT_TRUE(r.is_pending());
4557
[email protected]255620da2013-08-19 13:14:294558 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444559
4560 VerifyReceivedDataMatchesChunks(&r, &d);
4561 }
4562}
4563
[email protected]329b68b2012-11-14 17:54:274564TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4565 ASSERT_TRUE(test_server_.Start());
4566
4567 TestDelegate d;
4568 {
4569 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
4570 r.EnableChunkedUpload();
4571 r.set_method("POST");
4572 r.Start();
4573 EXPECT_TRUE(r.is_pending());
4574 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294575 base::RunLoop().Run();
[email protected]329b68b2012-11-14 17:54:274576
4577 VerifyReceivedDataMatchesChunks(&r, &d);
4578 }
4579}
4580
[email protected]316c1e5e2012-09-12 15:17:444581TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4582 ASSERT_TRUE(test_server_.Start());
4583
4584 TestDelegate d;
4585 {
4586 URLRequest r(test_server_.GetURL("echo"), &d, &default_context_);
4587 r.EnableChunkedUpload();
4588 r.set_method("POST");
4589 r.Start();
4590 EXPECT_TRUE(r.is_pending());
4591
[email protected]255620da2013-08-19 13:14:294592 base::RunLoop().RunUntilIdle();
[email protected]316c1e5e2012-09-12 15:17:444593 AddChunksToUpload(&r);
[email protected]255620da2013-08-19 13:14:294594 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444595
4596 VerifyReceivedDataMatchesChunks(&r, &d);
4597 }
4598}
4599
4600TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4601 ASSERT_TRUE(test_server_.Start());
4602
4603 TestDelegate d;
4604 URLRequest req(
4605 test_server_.GetURL("files/with-headers.html"), &d, &default_context_);
4606 req.Start();
[email protected]255620da2013-08-19 13:14:294607 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444608
4609 const HttpResponseHeaders* headers = req.response_headers();
4610
4611 // Simple sanity check that response_info() accesses the same data.
4612 EXPECT_EQ(headers, req.response_info().headers.get());
4613
4614 std::string header;
4615 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4616 EXPECT_EQ("private", header);
4617
4618 header.clear();
4619 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4620 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4621
4622 // The response has two "X-Multiple-Entries" headers.
4623 // This verfies our output has them concatenated together.
4624 header.clear();
4625 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4626 EXPECT_EQ("a, b", header);
4627}
4628
[email protected]242d8562012-10-30 21:20:464629TEST_F(URLRequestTestHTTP, ProcessSTS) {
[email protected]ce7d0cbc2013-05-03 18:57:224630 SpawnedTestServer::SSLOptions ssl_options;
4631 SpawnedTestServer https_test_server(
4632 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464633 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154634 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464635 ASSERT_TRUE(https_test_server.Start());
4636
4637 TestDelegate d;
4638 URLRequest request(
4639 https_test_server.GetURL("files/hsts-headers.html"),
4640 &d,
4641 &default_context_);
4642 request.Start();
[email protected]255620da2013-08-19 13:14:294643 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464644
4645 TransportSecurityState* security_state =
4646 default_context_.transport_security_state();
4647 bool sni_available = true;
4648 TransportSecurityState::DomainState domain_state;
4649 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034650 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:464651 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4652 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:054653 EXPECT_TRUE(domain_state.sts_include_subdomains);
[email protected]22e045f2013-09-20 03:54:034654 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]37fd55fb2013-06-29 13:13:274655#if defined(OS_ANDROID)
4656 // Android's CertVerifyProc does not (yet) handle pins.
4657#else
4658 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4659#endif
4660}
4661
4662// Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4663// reject HPKP headers, and a test setting only HPKP headers will fail (no
4664// DomainState present because header rejected).
4665#if defined(OS_ANDROID)
4666#define MAYBE_ProcessPKP DISABLED_ProcessPKP
4667#else
4668#define MAYBE_ProcessPKP ProcessPKP
4669#endif
4670
4671// Tests that enabling HPKP on a domain does not affect the HSTS
4672// validity/expiration.
4673TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
4674 SpawnedTestServer::SSLOptions ssl_options;
4675 SpawnedTestServer https_test_server(
4676 SpawnedTestServer::TYPE_HTTPS,
4677 ssl_options,
4678 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4679 ASSERT_TRUE(https_test_server.Start());
4680
4681 TestDelegate d;
4682 URLRequest request(
4683 https_test_server.GetURL("files/hpkp-headers.html"),
4684 &d,
4685 &default_context_);
4686 request.Start();
[email protected]255620da2013-08-19 13:14:294687 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:274688
4689 TransportSecurityState* security_state =
4690 default_context_.transport_security_state();
4691 bool sni_available = true;
4692 TransportSecurityState::DomainState domain_state;
4693 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034694 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:274695 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
4696 domain_state.upgrade_mode);
4697 EXPECT_FALSE(domain_state.sts_include_subdomains);
4698 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4699 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4700 EXPECT_NE(domain_state.upgrade_expiry,
4701 domain_state.dynamic_spki_hashes_expiry);
[email protected]242d8562012-10-30 21:20:464702}
4703
4704TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
[email protected]ce7d0cbc2013-05-03 18:57:224705 SpawnedTestServer::SSLOptions ssl_options;
4706 SpawnedTestServer https_test_server(
4707 SpawnedTestServer::TYPE_HTTPS,
[email protected]242d8562012-10-30 21:20:464708 ssl_options,
[email protected]6cdfd7f2013-02-08 20:40:154709 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
[email protected]242d8562012-10-30 21:20:464710 ASSERT_TRUE(https_test_server.Start());
4711
4712 TestDelegate d;
4713 URLRequest request(
4714 https_test_server.GetURL("files/hsts-multiple-headers.html"),
4715 &d,
4716 &default_context_);
4717 request.Start();
[email protected]255620da2013-08-19 13:14:294718 base::RunLoop().Run();
[email protected]242d8562012-10-30 21:20:464719
4720 // We should have set parameters from the first header, not the second.
4721 TransportSecurityState* security_state =
4722 default_context_.transport_security_state();
4723 bool sni_available = true;
4724 TransportSecurityState::DomainState domain_state;
4725 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034726 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]242d8562012-10-30 21:20:464727 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4728 domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:054729 EXPECT_FALSE(domain_state.sts_include_subdomains);
4730 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]242d8562012-10-30 21:20:464731}
4732
[email protected]9f972ec2013-04-10 20:24:364733TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
[email protected]ce7d0cbc2013-05-03 18:57:224734 SpawnedTestServer::SSLOptions ssl_options;
4735 SpawnedTestServer https_test_server(
4736 SpawnedTestServer::TYPE_HTTPS,
[email protected]9f972ec2013-04-10 20:24:364737 ssl_options,
4738 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4739 ASSERT_TRUE(https_test_server.Start());
4740
4741 TestDelegate d;
4742 URLRequest request(
4743 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
4744 &d,
4745 &default_context_);
4746 request.Start();
[email protected]255620da2013-08-19 13:14:294747 base::RunLoop().Run();
[email protected]9f972ec2013-04-10 20:24:364748
4749 // We should have set parameters from the first header, not the second.
4750 TransportSecurityState* security_state =
4751 default_context_.transport_security_state();
4752 bool sni_available = true;
4753 TransportSecurityState::DomainState domain_state;
4754 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034755 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]9f972ec2013-04-10 20:24:364756 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4757 domain_state.upgrade_mode);
4758#if defined(OS_ANDROID)
4759 // Android's CertVerifyProc does not (yet) handle pins.
4760#else
4761 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4762#endif
4763 EXPECT_NE(domain_state.upgrade_expiry,
4764 domain_state.dynamic_spki_hashes_expiry);
4765
[email protected]a165f092013-06-12 16:10:054766 // Even though there is an HSTS header asserting includeSubdomains, it is
4767 // the *second* such header, and we MUST process only the first.
4768 EXPECT_FALSE(domain_state.sts_include_subdomains);
4769 // includeSubdomains does not occur in the test HPKP header.
4770 EXPECT_FALSE(domain_state.pkp_include_subdomains);
[email protected]9f972ec2013-04-10 20:24:364771}
4772
[email protected]37fd55fb2013-06-29 13:13:274773// Tests that when multiple HPKP headers are present, asserting different
4774// policies, that only the first such policy is processed.
4775TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
4776 SpawnedTestServer::SSLOptions ssl_options;
4777 SpawnedTestServer https_test_server(
4778 SpawnedTestServer::TYPE_HTTPS,
4779 ssl_options,
4780 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4781 ASSERT_TRUE(https_test_server.Start());
4782
4783 TestDelegate d;
4784 URLRequest request(
4785 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
4786 &d,
4787 &default_context_);
4788 request.Start();
[email protected]255620da2013-08-19 13:14:294789 base::RunLoop().Run();
[email protected]37fd55fb2013-06-29 13:13:274790
4791 TransportSecurityState* security_state =
4792 default_context_.transport_security_state();
4793 bool sni_available = true;
4794 TransportSecurityState::DomainState domain_state;
4795 EXPECT_TRUE(security_state->GetDomainState(
[email protected]22e045f2013-09-20 03:54:034796 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
[email protected]37fd55fb2013-06-29 13:13:274797 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4798 domain_state.upgrade_mode);
4799#if defined(OS_ANDROID)
4800 // Android's CertVerifyProc does not (yet) handle pins.
4801#else
4802 EXPECT_TRUE(domain_state.HasPublicKeyPins());
4803#endif
4804 EXPECT_NE(domain_state.upgrade_expiry,
4805 domain_state.dynamic_spki_hashes_expiry);
4806
4807 EXPECT_TRUE(domain_state.sts_include_subdomains);
4808 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4809}
4810
[email protected]316c1e5e2012-09-12 15:17:444811TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
4812 ASSERT_TRUE(test_server_.Start());
4813
4814 TestDelegate d;
4815 URLRequest req(test_server_.GetURL(
4816 "files/content-type-normalization.html"), &d, &default_context_);
4817 req.Start();
[email protected]255620da2013-08-19 13:14:294818 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444819
4820 std::string mime_type;
4821 req.GetMimeType(&mime_type);
4822 EXPECT_EQ("text/html", mime_type);
4823
4824 std::string charset;
4825 req.GetCharset(&charset);
4826 EXPECT_EQ("utf-8", charset);
4827 req.Cancel();
4828}
4829
[email protected]e0f35c92013-05-08 16:04:344830TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) {
4831 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
4832 GURL file_url("file:///foo.txt");
4833 GURL data_url("data:,foo");
[email protected]255620da2013-08-19 13:14:294834 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
[email protected]e0f35c92013-05-08 16:04:344835 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
4836 DataProtocolHandler data_protocol_handler;
[email protected]588614c22013-08-16 00:09:024837 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:344838
4839 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
4840 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
[email protected]588614c22013-08-16 00:09:024841 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
[email protected]e0f35c92013-05-08 16:04:344842}
4843
[email protected]588614c22013-08-16 00:09:024844TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
[email protected]316c1e5e2012-09-12 15:17:444845 ASSERT_TRUE(test_server_.Start());
4846
4847 TestDelegate d;
4848 URLRequest req(test_server_.GetURL(
4849 "files/redirect-to-file.html"), &d, &default_context_);
4850 req.Start();
[email protected]255620da2013-08-19 13:14:294851 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444852
4853 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4854 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
4855}
4856
[email protected]588614c22013-08-16 00:09:024857TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
4858 ASSERT_TRUE(test_server_.Start());
4859
4860 TestDelegate d;
4861 URLRequest req(test_server_.GetURL(
4862 "files/redirect-to-data.html"), &d, &default_context_);
4863 req.Start();
4864 base::MessageLoop::current()->Run();
4865
4866 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4867 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
4868}
4869
[email protected]316c1e5e2012-09-12 15:17:444870TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
4871 ASSERT_TRUE(test_server_.Start());
4872
4873 TestDelegate d;
4874 URLRequest req(test_server_.GetURL(
4875 "files/redirect-to-invalid-url.html"), &d, &default_context_);
4876 req.Start();
[email protected]255620da2013-08-19 13:14:294877 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444878
4879 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
4880 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
4881}
4882
4883TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
4884 ASSERT_TRUE(test_server_.Start());
4885
4886 TestDelegate d;
4887 URLRequest req(
4888 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
[email protected]99ecf6e2013-04-10 22:46:134889 req.SetReferrer("http://user:[email protected]/");
[email protected]316c1e5e2012-09-12 15:17:444890 req.Start();
[email protected]255620da2013-08-19 13:14:294891 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444892
4893 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
4894}
4895
[email protected]99ecf6e2013-04-10 22:46:134896TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
4897 ASSERT_TRUE(test_server_.Start());
4898
4899 TestDelegate d;
4900 URLRequest req(
4901 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
4902 req.SetReferrer("http://foo.com/test#fragment");
4903 req.Start();
[email protected]255620da2013-08-19 13:14:294904 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:134905
4906 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
4907}
4908
4909TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
4910 ASSERT_TRUE(test_server_.Start());
4911
4912 TestDelegate d;
4913 URLRequest req(
4914 test_server_.GetURL("echoheader?Referer"), &d, &default_context_);
4915 req.SetReferrer("http://foo.com/test#fragment");
4916 req.SetReferrer("");
4917 req.Start();
[email protected]255620da2013-08-19 13:14:294918 base::RunLoop().Run();
[email protected]99ecf6e2013-04-10 22:46:134919
4920 EXPECT_EQ(std::string("None"), d.data_received());
4921}
4922
[email protected]316c1e5e2012-09-12 15:17:444923TEST_F(URLRequestTestHTTP, CancelRedirect) {
4924 ASSERT_TRUE(test_server_.Start());
4925
4926 TestDelegate d;
4927 {
4928 d.set_cancel_in_received_redirect(true);
4929 URLRequest req(
4930 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
4931 req.Start();
[email protected]255620da2013-08-19 13:14:294932 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444933
4934 EXPECT_EQ(1, d.response_started_count());
4935 EXPECT_EQ(0, d.bytes_received());
4936 EXPECT_FALSE(d.received_data_before_response());
4937 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
4938 }
4939}
4940
4941TEST_F(URLRequestTestHTTP, DeferredRedirect) {
4942 ASSERT_TRUE(test_server_.Start());
4943
4944 TestDelegate d;
4945 {
4946 d.set_quit_on_redirect(true);
[email protected]79e1fd62013-06-20 06:50:044947 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
4948 URLRequest req(test_url, &d, &default_context_);
4949
[email protected]316c1e5e2012-09-12 15:17:444950 req.Start();
[email protected]255620da2013-08-19 13:14:294951 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444952
4953 EXPECT_EQ(1, d.received_redirect_count());
4954
4955 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:294956 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:444957
4958 EXPECT_EQ(1, d.response_started_count());
4959 EXPECT_FALSE(d.received_data_before_response());
4960 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
4961
[email protected]6cdfd7f2013-02-08 20:40:154962 base::FilePath path;
[email protected]316c1e5e2012-09-12 15:17:444963 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4964 path = path.Append(FILE_PATH_LITERAL("net"));
4965 path = path.Append(FILE_PATH_LITERAL("data"));
4966 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4967 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4968
4969 std::string contents;
[email protected]82f84b92013-08-30 18:23:504970 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]316c1e5e2012-09-12 15:17:444971 EXPECT_EQ(contents, d.data_received());
4972 }
4973}
4974
[email protected]79e1fd62013-06-20 06:50:044975TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
4976 ASSERT_TRUE(test_server_.Start());
4977
4978 TestDelegate d;
4979 {
4980 d.set_quit_on_redirect(true);
4981 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
4982 URLRequest req(test_url, &d, &default_context_);
4983
4984 EXPECT_FALSE(d.have_full_request_headers());
4985
4986 req.Start();
[email protected]255620da2013-08-19 13:14:294987 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044988
4989 EXPECT_EQ(1, d.received_redirect_count());
4990 EXPECT_TRUE(d.have_full_request_headers());
4991 CheckFullRequestHeaders(d.full_request_headers(), test_url);
4992 d.ClearFullRequestHeaders();
4993
4994 req.FollowDeferredRedirect();
[email protected]255620da2013-08-19 13:14:294995 base::RunLoop().Run();
[email protected]79e1fd62013-06-20 06:50:044996
4997 GURL target_url(test_server_.GetURL("files/with-headers.html"));
4998 EXPECT_EQ(1, d.response_started_count());
4999 EXPECT_TRUE(d.have_full_request_headers());
5000 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5001 EXPECT_FALSE(d.received_data_before_response());
5002 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5003
5004 base::FilePath path;
5005 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5006 path = path.Append(FILE_PATH_LITERAL("net"));
5007 path = path.Append(FILE_PATH_LITERAL("data"));
5008 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5009 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5010
5011 std::string contents;
[email protected]82f84b92013-08-30 18:23:505012 EXPECT_TRUE(base::ReadFileToString(path, &contents));
[email protected]79e1fd62013-06-20 06:50:045013 EXPECT_EQ(contents, d.data_received());
5014 }
5015}
5016
[email protected]316c1e5e2012-09-12 15:17:445017TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5018 ASSERT_TRUE(test_server_.Start());
5019
5020 TestDelegate d;
5021 {
5022 d.set_quit_on_redirect(true);
5023 URLRequest req(
5024 test_server_.GetURL("files/redirect-test.html"), &d, &default_context_);
5025 req.Start();
[email protected]255620da2013-08-19 13:14:295026 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445027
5028 EXPECT_EQ(1, d.received_redirect_count());
5029
5030 req.Cancel();
[email protected]255620da2013-08-19 13:14:295031 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445032
5033 EXPECT_EQ(1, d.response_started_count());
5034 EXPECT_EQ(0, d.bytes_received());
5035 EXPECT_FALSE(d.received_data_before_response());
5036 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5037 }
5038}
5039
5040TEST_F(URLRequestTestHTTP, VaryHeader) {
5041 ASSERT_TRUE(test_server_.Start());
5042
[email protected]3b23a222013-05-15 21:33:255043 // Populate the cache.
[email protected]316c1e5e2012-09-12 15:17:445044 {
5045 TestDelegate d;
5046 URLRequest req(
5047 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
5048 HttpRequestHeaders headers;
5049 headers.SetHeader("foo", "1");
5050 req.SetExtraRequestHeaders(headers);
5051 req.Start();
[email protected]255620da2013-08-19 13:14:295052 base::RunLoop().Run();
[email protected]3b23a222013-05-15 21:33:255053
5054 LoadTimingInfo load_timing_info;
5055 req.GetLoadTimingInfo(&load_timing_info);
5056 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445057 }
5058
[email protected]3b23a222013-05-15 21:33:255059 // Expect a cache hit.
[email protected]316c1e5e2012-09-12 15:17:445060 {
5061 TestDelegate d;
5062 URLRequest req(
5063 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
5064 HttpRequestHeaders headers;
5065 headers.SetHeader("foo", "1");
5066 req.SetExtraRequestHeaders(headers);
5067 req.Start();
[email protected]255620da2013-08-19 13:14:295068 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445069
5070 EXPECT_TRUE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255071
5072 LoadTimingInfo load_timing_info;
5073 req.GetLoadTimingInfo(&load_timing_info);
5074 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]316c1e5e2012-09-12 15:17:445075 }
5076
[email protected]3b23a222013-05-15 21:33:255077 // Expect a cache miss.
[email protected]316c1e5e2012-09-12 15:17:445078 {
5079 TestDelegate d;
5080 URLRequest req(
5081 test_server_.GetURL("echoheadercache?foo"), &d, &default_context_);
5082 HttpRequestHeaders headers;
5083 headers.SetHeader("foo", "2");
5084 req.SetExtraRequestHeaders(headers);
5085 req.Start();
[email protected]255620da2013-08-19 13:14:295086 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445087
5088 EXPECT_FALSE(req.was_cached());
[email protected]3b23a222013-05-15 21:33:255089
5090 LoadTimingInfo load_timing_info;
5091 req.GetLoadTimingInfo(&load_timing_info);
5092 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]316c1e5e2012-09-12 15:17:445093 }
5094}
5095
5096TEST_F(URLRequestTestHTTP, BasicAuth) {
5097 ASSERT_TRUE(test_server_.Start());
5098
5099 // populate the cache
5100 {
5101 TestDelegate d;
5102 d.set_credentials(AuthCredentials(kUser, kSecret));
5103
5104 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
5105 r.Start();
5106
[email protected]255620da2013-08-19 13:14:295107 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445108
5109 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5110 }
5111
5112 // repeat request with end-to-end validation. since auth-basic results in a
5113 // cachable page, we expect this test to result in a 304. in which case, the
5114 // response should be fetched from the cache.
5115 {
5116 TestDelegate d;
5117 d.set_credentials(AuthCredentials(kUser, kSecret));
5118
5119 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
5120 r.set_load_flags(LOAD_VALIDATE_CACHE);
5121 r.Start();
5122
[email protected]255620da2013-08-19 13:14:295123 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445124
5125 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5126
5127 // Should be the same cached document.
5128 EXPECT_TRUE(r.was_cached());
5129 }
5130}
5131
5132// Check that Set-Cookie headers in 401 responses are respected.
5133// http://crbug.com/6450
5134TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5135 ASSERT_TRUE(test_server_.Start());
5136
5137 GURL url_requiring_auth =
5138 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5139
5140 // Request a page that will give a 401 containing a Set-Cookie header.
5141 // Verify that when the transaction is restarted, it includes the new cookie.
5142 {
[email protected]ceefd7fd2012-11-29 00:36:245143 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445144 TestURLRequestContext context(true);
5145 context.set_network_delegate(&network_delegate);
5146 context.Init();
5147
5148 TestDelegate d;
5149 d.set_credentials(AuthCredentials(kUser, kSecret));
5150
5151 URLRequest r(url_requiring_auth, &d, &context);
5152 r.Start();
5153
[email protected]255620da2013-08-19 13:14:295154 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445155
5156 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5157
5158 // Make sure we sent the cookie in the restarted transaction.
5159 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5160 != std::string::npos);
5161 }
5162
5163 // Same test as above, except this time the restart is initiated earlier
5164 // (without user intervention since identity is embedded in the URL).
5165 {
[email protected]ceefd7fd2012-11-29 00:36:245166 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445167 TestURLRequestContext context(true);
5168 context.set_network_delegate(&network_delegate);
5169 context.Init();
5170
5171 TestDelegate d;
5172
5173 GURL::Replacements replacements;
5174 std::string username("user2");
5175 std::string password("secret");
5176 replacements.SetUsernameStr(username);
5177 replacements.SetPasswordStr(password);
5178 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5179
5180 URLRequest r(url_with_identity, &d, &context);
5181 r.Start();
5182
[email protected]255620da2013-08-19 13:14:295183 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445184
5185 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5186
5187 // Make sure we sent the cookie in the restarted transaction.
5188 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5189 != std::string::npos);
5190 }
5191}
5192
[email protected]58e32bb2013-01-21 18:23:255193// Tests that load timing works as expected with auth and the cache.
5194TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5195 ASSERT_TRUE(test_server_.Start());
5196
5197 // populate the cache
5198 {
5199 TestDelegate d;
5200 d.set_credentials(AuthCredentials(kUser, kSecret));
5201
5202 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
5203 r.Start();
5204
[email protected]255620da2013-08-19 13:14:295205 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255206
5207 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5208
5209 LoadTimingInfo load_timing_info_before_auth;
5210 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5211 &load_timing_info_before_auth));
5212 TestLoadTimingNotReused(load_timing_info_before_auth,
5213 CONNECT_TIMING_HAS_DNS_TIMES);
5214
5215 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175216 r.GetLoadTimingInfo(&load_timing_info);
[email protected]58e32bb2013-01-21 18:23:255217 // The test server does not support keep alive sockets, so the second
5218 // request with auth should use a new socket.
5219 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5220 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5221 load_timing_info.socket_log_id);
5222 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5223 load_timing_info.connect_timing.connect_start);
5224 }
5225
[email protected]3b23a222013-05-15 21:33:255226 // Repeat request with end-to-end validation. Since auth-basic results in a
5227 // cachable page, we expect this test to result in a 304. In which case, the
[email protected]58e32bb2013-01-21 18:23:255228 // response should be fetched from the cache.
5229 {
5230 TestDelegate d;
5231 d.set_credentials(AuthCredentials(kUser, kSecret));
5232
5233 URLRequest r(test_server_.GetURL("auth-basic"), &d, &default_context_);
5234 r.set_load_flags(LOAD_VALIDATE_CACHE);
5235 r.Start();
5236
[email protected]255620da2013-08-19 13:14:295237 base::RunLoop().Run();
[email protected]58e32bb2013-01-21 18:23:255238
5239 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5240
5241 // Should be the same cached document.
5242 EXPECT_TRUE(r.was_cached());
5243
[email protected]3b23a222013-05-15 21:33:255244 // Since there was a request that went over the wire, the load timing
5245 // information should include connection times.
[email protected]58e32bb2013-01-21 18:23:255246 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:175247 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:255248 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
[email protected]58e32bb2013-01-21 18:23:255249 }
5250}
5251
[email protected]316c1e5e2012-09-12 15:17:445252// In this test, we do a POST which the server will 302 redirect.
5253// The subsequent transaction should use GET, and should not send the
5254// Content-Type header.
5255// http://code.google.com/p/chromium/issues/detail?id=843
5256TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5257 ASSERT_TRUE(test_server_.Start());
5258
5259 const char kData[] = "hello world";
5260
5261 TestDelegate d;
5262 URLRequest req(
5263 test_server_.GetURL("files/redirect-to-echoall"), &d, &default_context_);
5264 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285265 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445266
5267 // Set headers (some of which are specific to the POST).
5268 HttpRequestHeaders headers;
5269 headers.AddHeadersFromString(
5270 "Content-Type: multipart/form-data; "
5271 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5272 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5273 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5274 "Accept-Language: en-US,en\r\n"
5275 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5276 "Content-Length: 11\r\n"
5277 "Origin: http://localhost:1337/");
5278 req.SetExtraRequestHeaders(headers);
5279 req.Start();
[email protected]255620da2013-08-19 13:14:295280 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445281
5282 std::string mime_type;
5283 req.GetMimeType(&mime_type);
5284 EXPECT_EQ("text/html", mime_type);
5285
5286 const std::string& data = d.data_received();
5287
5288 // Check that the post-specific headers were stripped:
5289 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5290 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5291 EXPECT_FALSE(ContainsString(data, "Origin:"));
5292
5293 // These extra request headers should not have been stripped.
5294 EXPECT_TRUE(ContainsString(data, "Accept:"));
5295 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5296 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5297}
5298
5299// The following tests check that we handle mutating the request method for
5300// HTTP redirects as expected.
5301// See http://crbug.com/56373 and http://crbug.com/102130.
5302
5303TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5304 ASSERT_TRUE(test_server_.Start());
5305
5306 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5307
5308 HTTPRedirectMethodTest(url, "POST", "GET", true);
5309 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5310 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5311}
5312
5313TEST_F(URLRequestTestHTTP, Redirect302Tests) {
5314 ASSERT_TRUE(test_server_.Start());
5315
5316 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
5317
5318 HTTPRedirectMethodTest(url, "POST", "GET", true);
5319 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5320 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5321}
5322
5323TEST_F(URLRequestTestHTTP, Redirect303Tests) {
5324 ASSERT_TRUE(test_server_.Start());
5325
5326 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
5327
5328 HTTPRedirectMethodTest(url, "POST", "GET", true);
5329 HTTPRedirectMethodTest(url, "PUT", "GET", true);
5330 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5331}
5332
5333TEST_F(URLRequestTestHTTP, Redirect307Tests) {
5334 ASSERT_TRUE(test_server_.Start());
5335
5336 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
5337
5338 HTTPRedirectMethodTest(url, "POST", "POST", true);
5339 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5340 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5341}
5342
5343TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
5344 ASSERT_TRUE(test_server_.Start());
5345
5346 const char kData[] = "hello world";
5347
5348 TestDelegate d;
5349 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
5350 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285351 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445352 HttpRequestHeaders headers;
5353 headers.SetHeader(HttpRequestHeaders::kContentLength,
5354 base::UintToString(arraysize(kData) - 1));
5355 req.SetExtraRequestHeaders(headers);
5356
5357 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:415358 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]8ccc69f2012-11-28 19:52:145359 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]316c1e5e2012-09-12 15:17:445360 AddTestInterceptor()->set_main_intercept_job(job);
5361
5362 req.Start();
[email protected]255620da2013-08-19 13:14:295363 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445364 EXPECT_EQ("GET", req.method());
5365}
5366
5367TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
5368 ASSERT_TRUE(test_server_.Start());
5369
5370 const char kData[] = "hello world";
5371
5372 TestDelegate d;
5373 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
5374 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285375 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]316c1e5e2012-09-12 15:17:445376 HttpRequestHeaders headers;
5377 headers.SetHeader(HttpRequestHeaders::kContentLength,
5378 base::UintToString(arraysize(kData) - 1));
5379 req.SetExtraRequestHeaders(headers);
5380
5381 URLRequestRedirectJob* job = new URLRequestRedirectJob(
[email protected]cc05edc2013-03-08 18:04:415382 &req, &default_network_delegate_, test_server_.GetURL("echo"),
[email protected]316c1e5e2012-09-12 15:17:445383 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT);
5384 AddTestInterceptor()->set_main_intercept_job(job);
5385
5386 req.Start();
[email protected]255620da2013-08-19 13:14:295387 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445388 EXPECT_EQ("POST", req.method());
5389 EXPECT_EQ(kData, d.data_received());
5390}
5391
5392// Check that default A-L header is sent.
5393TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
5394 ASSERT_TRUE(test_server_.Start());
5395
[email protected]84f05432013-03-15 01:00:125396 StaticHttpUserAgentSettings settings("en", EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:245397 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:445398 TestURLRequestContext context(true);
5399 context.set_network_delegate(&network_delegate);
[email protected]ee4c30d2012-11-07 15:08:435400 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:445401 context.Init();
5402
5403 TestDelegate d;
5404 URLRequest req(
5405 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
5406 req.Start();
[email protected]255620da2013-08-19 13:14:295407 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445408 EXPECT_EQ("en", d.data_received());
5409}
5410
5411// Check that an empty A-L header is not sent. http://crbug.com/77365.
5412TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
5413 ASSERT_TRUE(test_server_.Start());
5414
[email protected]84f05432013-03-15 01:00:125415 StaticHttpUserAgentSettings settings(EmptyString(), EmptyString());
[email protected]ceefd7fd2012-11-29 00:36:245416 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]316c1e5e2012-09-12 15:17:445417 TestURLRequestContext context(true);
5418 context.set_network_delegate(&network_delegate);
5419 context.Init();
5420 // We override the language after initialization because empty entries
5421 // get overridden by Init().
[email protected]ee4c30d2012-11-07 15:08:435422 context.set_http_user_agent_settings(&settings);
[email protected]316c1e5e2012-09-12 15:17:445423
5424 TestDelegate d;
5425 URLRequest req(
5426 test_server_.GetURL("echoheader?Accept-Language"), &d, &context);
5427 req.Start();
[email protected]255620da2013-08-19 13:14:295428 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445429 EXPECT_EQ("None", d.data_received());
5430}
5431
5432// Check that if request overrides the A-L header, the default is not appended.
5433// See http://crbug.com/20894
5434TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
5435 ASSERT_TRUE(test_server_.Start());
5436
5437 TestDelegate d;
5438 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
5439 &d,
5440 &default_context_);
5441 HttpRequestHeaders headers;
5442 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
5443 req.SetExtraRequestHeaders(headers);
5444 req.Start();
[email protected]255620da2013-08-19 13:14:295445 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445446 EXPECT_EQ(std::string("ru"), d.data_received());
5447}
5448
5449// Check that default A-E header is sent.
5450TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
5451 ASSERT_TRUE(test_server_.Start());
5452
5453 TestDelegate d;
5454 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
5455 &d,
5456 &default_context_);
5457 HttpRequestHeaders headers;
5458 req.SetExtraRequestHeaders(headers);
5459 req.Start();
[email protected]255620da2013-08-19 13:14:295460 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445461 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
5462}
5463
5464// Check that if request overrides the A-E header, the default is not appended.
5465// See http://crbug.com/47381
5466TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
5467 ASSERT_TRUE(test_server_.Start());
5468
5469 TestDelegate d;
5470 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
5471 &d,
5472 &default_context_);
5473 HttpRequestHeaders headers;
5474 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
5475 req.SetExtraRequestHeaders(headers);
5476 req.Start();
[email protected]255620da2013-08-19 13:14:295477 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445478 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
5479 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
5480}
5481
[email protected]84f05432013-03-15 01:00:125482// Check that setting the A-C header sends the proper header.
5483TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
[email protected]316c1e5e2012-09-12 15:17:445484 ASSERT_TRUE(test_server_.Start());
5485
5486 TestDelegate d;
5487 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
5488 &d,
5489 &default_context_);
5490 HttpRequestHeaders headers;
5491 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
5492 req.SetExtraRequestHeaders(headers);
5493 req.Start();
[email protected]255620da2013-08-19 13:14:295494 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445495 EXPECT_EQ(std::string("koi-8r"), d.data_received());
5496}
5497
5498// Check that default User-Agent header is sent.
5499TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
5500 ASSERT_TRUE(test_server_.Start());
5501
5502 TestDelegate d;
5503 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
5504 &d,
5505 &default_context_);
5506 req.Start();
[email protected]255620da2013-08-19 13:14:295507 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445508 EXPECT_EQ(req.context()->GetUserAgent(req.url()), d.data_received());
5509}
5510
5511// Check that if request overrides the User-Agent header,
5512// the default is not appended.
5513TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
5514 ASSERT_TRUE(test_server_.Start());
5515
5516 TestDelegate d;
5517 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
5518 &d,
5519 &default_context_);
5520 HttpRequestHeaders headers;
5521 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
5522 req.SetExtraRequestHeaders(headers);
5523 req.Start();
[email protected]255620da2013-08-19 13:14:295524 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445525 // If the net tests are being run with ChromeFrame then we need to allow for
5526 // the 'chromeframe' suffix which is added to the user agent before the
5527 // closing parentheses.
5528 EXPECT_TRUE(StartsWithASCII(d.data_received(), "Lynx (textmode", true));
5529}
5530
[email protected]ee4c30d2012-11-07 15:08:435531// Check that a NULL HttpUserAgentSettings causes the corresponding empty
5532// User-Agent header to be sent but does not send the Accept-Language and
5533// Accept-Charset headers.
5534TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
5535 ASSERT_TRUE(test_server_.Start());
5536
[email protected]ceefd7fd2012-11-29 00:36:245537 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
[email protected]ee4c30d2012-11-07 15:08:435538 TestURLRequestContext context(true);
5539 context.set_network_delegate(&network_delegate);
5540 context.Init();
5541 // We override the HttpUserAgentSettings after initialization because empty
5542 // entries get overridden by Init().
5543 context.set_http_user_agent_settings(NULL);
5544
5545 struct {
5546 const char* request;
5547 const char* expected_response;
5548 } tests[] = { { "echoheader?Accept-Language", "None" },
5549 { "echoheader?Accept-Charset", "None" },
5550 { "echoheader?User-Agent", "" } };
5551
5552 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
5553 TestDelegate d;
5554 URLRequest req(test_server_.GetURL(tests[i].request), &d, &context);
5555 req.Start();
[email protected]255620da2013-08-19 13:14:295556 base::RunLoop().Run();
[email protected]ee4c30d2012-11-07 15:08:435557 EXPECT_EQ(tests[i].expected_response, d.data_received())
5558 << " Request = \"" << tests[i].request << "\"";
5559 }
5560}
5561
[email protected]5033ab82013-03-22 20:17:465562// Make sure that URLRequest passes on its priority updates to
5563// newly-created jobs after the first one.
5564TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
5565 ASSERT_TRUE(test_server_.Start());
5566
5567 TestDelegate d;
5568 URLRequest req(test_server_.GetURL("empty.html"), &d, &default_context_);
5569 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
5570
5571 scoped_refptr<URLRequestRedirectJob> redirect_job =
5572 new URLRequestRedirectJob(
5573 &req, &default_network_delegate_, test_server_.GetURL("echo"),
5574 URLRequestRedirectJob::REDIRECT_302_FOUND);
[email protected]90499482013-06-01 00:39:505575 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
[email protected]5033ab82013-03-22 20:17:465576
5577 req.SetPriority(LOW);
5578 req.Start();
5579 EXPECT_TRUE(req.is_pending());
5580
5581 scoped_refptr<URLRequestTestJob> job =
5582 new URLRequestTestJob(&req, &default_network_delegate_);
[email protected]90499482013-06-01 00:39:505583 AddTestInterceptor()->set_main_intercept_job(job.get());
[email protected]5033ab82013-03-22 20:17:465584
5585 // Should trigger |job| to be started.
[email protected]255620da2013-08-19 13:14:295586 base::RunLoop().Run();
[email protected]5033ab82013-03-22 20:17:465587 EXPECT_EQ(LOW, job->priority());
5588}
5589
[email protected]73e0bba2009-02-19 22:57:095590class HTTPSRequestTest : public testing::Test {
[email protected]87a09a92011-07-14 15:50:505591 public:
[email protected]ef2bf422012-05-11 03:27:095592 HTTPSRequestTest() : default_context_(true) {
5593 default_context_.set_network_delegate(&default_network_delegate_);
5594 default_context_.Init();
[email protected]87a09a92011-07-14 15:50:505595 }
5596 virtual ~HTTPSRequestTest() {}
5597
5598 protected:
[email protected]ceefd7fd2012-11-29 00:36:245599 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
[email protected]ef2bf422012-05-11 03:27:095600 TestURLRequestContext default_context_;
[email protected]ea224582008-12-07 20:25:465601};
5602
[email protected]c044616e2013-02-20 02:01:265603TEST_F(HTTPSRequestTest, HTTPSGetTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225604 SpawnedTestServer test_server(
5605 SpawnedTestServer::TYPE_HTTPS,
5606 SpawnedTestServer::kLocalhost,
5607 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115608 ASSERT_TRUE(test_server.Start());
[email protected]ea224582008-12-07 20:25:465609
[email protected]ea224582008-12-07 20:25:465610 TestDelegate d;
5611 {
[email protected]007b3f82013-04-09 08:46:455612 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]ea224582008-12-07 20:25:465613 r.Start();
5614 EXPECT_TRUE(r.is_pending());
5615
[email protected]255620da2013-08-19 13:14:295616 base::RunLoop().Run();
[email protected]ea224582008-12-07 20:25:465617
5618 EXPECT_EQ(1, d.response_started_count());
5619 EXPECT_FALSE(d.received_data_before_response());
5620 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175621 CheckSSLInfo(r.ssl_info());
[email protected]6d81b482011-02-22 19:47:195622 EXPECT_EQ(test_server.host_port_pair().host(),
5623 r.GetSocketAddress().host());
5624 EXPECT_EQ(test_server.host_port_pair().port(),
5625 r.GetSocketAddress().port());
[email protected]ea224582008-12-07 20:25:465626 }
[email protected]ea224582008-12-07 20:25:465627}
5628
[email protected]5774ada2010-07-15 06:30:545629TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225630 SpawnedTestServer::SSLOptions ssl_options(
5631 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5632 SpawnedTestServer test_server(
5633 SpawnedTestServer::TYPE_HTTPS,
5634 ssl_options,
5635 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115636 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:335637
5638 bool err_allowed = true;
5639 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
5640 TestDelegate d;
5641 {
5642 d.set_allow_certificate_errors(err_allowed);
[email protected]007b3f82013-04-09 08:46:455643 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:335644
5645 r.Start();
5646 EXPECT_TRUE(r.is_pending());
5647
[email protected]255620da2013-08-19 13:14:295648 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:335649
5650 EXPECT_EQ(1, d.response_started_count());
5651 EXPECT_FALSE(d.received_data_before_response());
5652 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:175653 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:335654 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175655 CheckSSLInfo(r.ssl_info());
5656 } else {
[email protected]bacff652009-03-31 17:50:335657 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175658 }
[email protected]bacff652009-03-31 17:50:335659 }
5660 }
5661}
5662
[email protected]5774ada2010-07-15 06:30:545663TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225664 SpawnedTestServer::SSLOptions ssl_options(
5665 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
5666 SpawnedTestServer test_server(
5667 SpawnedTestServer::TYPE_HTTPS,
5668 ssl_options,
5669 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]95409e12010-08-17 20:07:115670 ASSERT_TRUE(test_server.Start());
[email protected]bacff652009-03-31 17:50:335671
5672 // Iterate from false to true, just so that we do the opposite of the
5673 // previous test in order to increase test coverage.
5674 bool err_allowed = false;
5675 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
5676 TestDelegate d;
5677 {
5678 d.set_allow_certificate_errors(err_allowed);
[email protected]007b3f82013-04-09 08:46:455679 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]bacff652009-03-31 17:50:335680
5681 r.Start();
5682 EXPECT_TRUE(r.is_pending());
5683
[email protected]255620da2013-08-19 13:14:295684 base::RunLoop().Run();
[email protected]bacff652009-03-31 17:50:335685
5686 EXPECT_EQ(1, d.response_started_count());
5687 EXPECT_FALSE(d.received_data_before_response());
5688 EXPECT_TRUE(d.have_certificate_errors());
[email protected]96adadb2010-08-28 01:16:175689 if (err_allowed) {
[email protected]bacff652009-03-31 17:50:335690 EXPECT_NE(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175691 CheckSSLInfo(r.ssl_info());
5692 } else {
[email protected]bacff652009-03-31 17:50:335693 EXPECT_EQ(0, d.bytes_received());
[email protected]96adadb2010-08-28 01:16:175694 }
[email protected]bacff652009-03-31 17:50:335695 }
5696 }
5697}
[email protected]73e0bba2009-02-19 22:57:095698
[email protected]316c1e5e2012-09-12 15:17:445699// Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
5700// than necessary.
5701TEST_F(HTTPSRequestTest, TLSv1Fallback) {
5702 uint16 default_version_max = SSLConfigService::default_version_max();
5703 // The OpenSSL library in use may not support TLS 1.1.
5704#if !defined(USE_OPENSSL)
5705 EXPECT_GT(default_version_max, SSL_PROTOCOL_VERSION_TLS1);
5706#endif
5707 if (default_version_max <= SSL_PROTOCOL_VERSION_TLS1)
5708 return;
5709
[email protected]ce7d0cbc2013-05-03 18:57:225710 SpawnedTestServer::SSLOptions ssl_options(
5711 SpawnedTestServer::SSLOptions::CERT_OK);
[email protected]316c1e5e2012-09-12 15:17:445712 ssl_options.tls_intolerant =
[email protected]ce7d0cbc2013-05-03 18:57:225713 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
5714 SpawnedTestServer test_server(
5715 SpawnedTestServer::TYPE_HTTPS,
5716 ssl_options,
5717 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445718 ASSERT_TRUE(test_server.Start());
5719
5720 TestDelegate d;
5721 TestURLRequestContext context(true);
5722 context.Init();
5723 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:455724 URLRequest r(test_server.GetURL(std::string()), &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445725 r.Start();
5726
[email protected]255620da2013-08-19 13:14:295727 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445728
5729 EXPECT_EQ(1, d.response_started_count());
5730 EXPECT_NE(0, d.bytes_received());
5731 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
5732 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
5733 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
5734}
5735
5736// This tests that a load of www.google.com with a certificate error sets
5737// the |certificate_errors_are_fatal| flag correctly. This flag will cause
5738// the interstitial to be fatal.
5739TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225740 SpawnedTestServer::SSLOptions ssl_options(
5741 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5742 SpawnedTestServer test_server(
5743 SpawnedTestServer::TYPE_HTTPS,
5744 ssl_options,
5745 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445746 ASSERT_TRUE(test_server.Start());
5747
5748 // We require that the URL be www.google.com in order to pick up the
5749 // preloaded HSTS entries in the TransportSecurityState. This means that we
5750 // have to use a MockHostResolver in order to direct www.google.com to the
[email protected]ceefd7fd2012-11-29 00:36:245751 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:445752
5753 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:245754 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445755 TestURLRequestContext context(true);
5756 context.set_network_delegate(&network_delegate);
5757 context.set_host_resolver(&host_resolver);
5758 TransportSecurityState transport_security_state;
5759 context.set_transport_security_state(&transport_security_state);
5760 context.Init();
5761
5762 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:045763 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
5764 test_server.host_port_pair().port())),
[email protected]316c1e5e2012-09-12 15:17:445765 &d,
5766 &context);
5767
5768 r.Start();
5769 EXPECT_TRUE(r.is_pending());
5770
[email protected]255620da2013-08-19 13:14:295771 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445772
5773 EXPECT_EQ(1, d.response_started_count());
5774 EXPECT_FALSE(d.received_data_before_response());
5775 EXPECT_TRUE(d.have_certificate_errors());
5776 EXPECT_TRUE(d.certificate_errors_are_fatal());
5777}
5778
5779// This tests that cached HTTPS page loads do not cause any updates to the
5780// TransportSecurityState.
5781TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
5782 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
5783 // matter. It just has to be any error.
[email protected]ce7d0cbc2013-05-03 18:57:225784 SpawnedTestServer::SSLOptions ssl_options(
5785 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
5786 SpawnedTestServer test_server(
5787 SpawnedTestServer::TYPE_HTTPS,
5788 ssl_options,
5789 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445790 ASSERT_TRUE(test_server.Start());
5791
5792 // We require that the URL be www.google.com in order to pick up the
5793 // preloaded and dynamic HSTS and public key pin entries in the
5794 // TransportSecurityState. This means that we have to use a
5795 // MockHostResolver in order to direct www.google.com to the testserver.
[email protected]ceefd7fd2012-11-29 00:36:245796 // By default, MockHostResolver maps all hosts to 127.0.0.1.
[email protected]316c1e5e2012-09-12 15:17:445797
5798 MockHostResolver host_resolver;
[email protected]ceefd7fd2012-11-29 00:36:245799 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
[email protected]316c1e5e2012-09-12 15:17:445800 TestURLRequestContext context(true);
5801 context.set_network_delegate(&network_delegate);
5802 context.set_host_resolver(&host_resolver);
5803 TransportSecurityState transport_security_state;
5804 TransportSecurityState::DomainState domain_state;
[email protected]22e045f2013-09-20 03:54:035805 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
5806 &domain_state));
[email protected]316c1e5e2012-09-12 15:17:445807 context.set_transport_security_state(&transport_security_state);
5808 context.Init();
5809
5810 TestDelegate d;
[email protected]7d3cbc92013-03-18 22:33:045811 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
5812 test_server.host_port_pair().port())),
[email protected]316c1e5e2012-09-12 15:17:445813 &d,
5814 &context);
5815
5816 r.Start();
5817 EXPECT_TRUE(r.is_pending());
5818
[email protected]255620da2013-08-19 13:14:295819 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445820
5821 EXPECT_EQ(1, d.response_started_count());
5822 EXPECT_FALSE(d.received_data_before_response());
5823 EXPECT_TRUE(d.have_certificate_errors());
5824 EXPECT_TRUE(d.certificate_errors_are_fatal());
5825
5826 // Get a fresh copy of the state, and check that it hasn't been updated.
5827 TransportSecurityState::DomainState new_domain_state;
[email protected]22e045f2013-09-20 03:54:035828 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
5829 &new_domain_state));
[email protected]316c1e5e2012-09-12 15:17:445830 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
[email protected]a165f092013-06-12 16:10:055831 EXPECT_EQ(new_domain_state.sts_include_subdomains,
5832 domain_state.sts_include_subdomains);
5833 EXPECT_EQ(new_domain_state.pkp_include_subdomains,
5834 domain_state.pkp_include_subdomains);
[email protected]316c1e5e2012-09-12 15:17:445835 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
5836 domain_state.static_spki_hashes));
5837 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
5838 domain_state.dynamic_spki_hashes));
5839 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
5840 domain_state.bad_static_spki_hashes));
5841}
5842
[email protected]8ccc69f2012-11-28 19:52:145843// Make sure HSTS preserves a POST request's method and body.
5844TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
5845 static const char kData[] = "hello world";
5846
[email protected]ce7d0cbc2013-05-03 18:57:225847 SpawnedTestServer::SSLOptions ssl_options(
5848 SpawnedTestServer::SSLOptions::CERT_OK);
5849 SpawnedTestServer test_server(
5850 SpawnedTestServer::TYPE_HTTPS,
5851 ssl_options,
5852 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]8ccc69f2012-11-28 19:52:145853 ASSERT_TRUE(test_server.Start());
5854
5855
5856 // Per spec, TransportSecurityState expects a domain name, rather than an IP
5857 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
[email protected]ce7d0cbc2013-05-03 18:57:225858 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
5859 // to 127.0.0.1.
[email protected]8ccc69f2012-11-28 19:52:145860 MockHostResolver host_resolver;
[email protected]8ccc69f2012-11-28 19:52:145861
5862 // Force https for www.somewhere.com.
5863 TransportSecurityState transport_security_state;
[email protected]474f079e2013-03-02 19:11:205864 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
5865 bool include_subdomains = false;
5866 transport_security_state.AddHSTS("www.somewhere.com", expiry,
5867 include_subdomains);
[email protected]8ccc69f2012-11-28 19:52:145868
5869 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5870
5871 TestURLRequestContext context(true);
5872 context.set_host_resolver(&host_resolver);
5873 context.set_transport_security_state(&transport_security_state);
5874 context.set_network_delegate(&network_delegate);
5875 context.Init();
5876
5877 TestDelegate d;
5878 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
5879 // cause a certificate error. Ignore the error.
5880 d.set_allow_certificate_errors(true);
5881
[email protected]7d3cbc92013-03-18 22:33:045882 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
5883 test_server.host_port_pair().port())),
[email protected]8ccc69f2012-11-28 19:52:145884 &d,
5885 &context);
5886 req.set_method("POST");
[email protected]f288ef02012-12-15 20:28:285887 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
[email protected]8ccc69f2012-11-28 19:52:145888
5889 req.Start();
[email protected]255620da2013-08-19 13:14:295890 base::RunLoop().Run();
[email protected]8ccc69f2012-11-28 19:52:145891
5892 EXPECT_EQ("https", req.url().scheme());
5893 EXPECT_EQ("POST", req.method());
5894 EXPECT_EQ(kData, d.data_received());
[email protected]07d9bfd2013-06-27 14:16:405895
5896 LoadTimingInfo load_timing_info;
5897 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
5898 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
5899 TestLoadTimingCacheHitNoNetwork(load_timing_info);
[email protected]8ccc69f2012-11-28 19:52:145900}
5901
[email protected]316c1e5e2012-09-12 15:17:445902TEST_F(HTTPSRequestTest, SSLv3Fallback) {
[email protected]ce7d0cbc2013-05-03 18:57:225903 SpawnedTestServer::SSLOptions ssl_options(
5904 SpawnedTestServer::SSLOptions::CERT_OK);
5905 ssl_options.tls_intolerant =
5906 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
5907 SpawnedTestServer test_server(
5908 SpawnedTestServer::TYPE_HTTPS,
5909 ssl_options,
5910 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445911 ASSERT_TRUE(test_server.Start());
5912
5913 TestDelegate d;
5914 TestURLRequestContext context(true);
5915 context.Init();
5916 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:455917 URLRequest r(test_server.GetURL(std::string()), &d, &context);
[email protected]316c1e5e2012-09-12 15:17:445918 r.Start();
5919
[email protected]255620da2013-08-19 13:14:295920 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445921
5922 EXPECT_EQ(1, d.response_started_count());
5923 EXPECT_NE(0, d.bytes_received());
5924 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
5925 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
5926 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
5927}
5928
5929namespace {
5930
5931class SSLClientAuthTestDelegate : public TestDelegate {
5932 public:
5933 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
5934 }
5935 virtual void OnCertificateRequested(
5936 URLRequest* request,
[email protected]46fadfd2013-02-06 09:40:165937 SSLCertRequestInfo* cert_request_info) OVERRIDE {
[email protected]316c1e5e2012-09-12 15:17:445938 on_certificate_requested_count_++;
[email protected]2da659e2013-05-23 20:51:345939 base::MessageLoop::current()->Quit();
[email protected]316c1e5e2012-09-12 15:17:445940 }
5941 int on_certificate_requested_count() {
5942 return on_certificate_requested_count_;
5943 }
5944 private:
5945 int on_certificate_requested_count_;
5946};
5947
5948} // namespace
5949
5950// TODO(davidben): Test the rest of the code. Specifically,
5951// - Filtering which certificates to select.
5952// - Sending a certificate back.
5953// - Getting a certificate request in an SSL renegotiation sending the
5954// HTTP request.
5955TEST_F(HTTPSRequestTest, ClientAuthTest) {
[email protected]ce7d0cbc2013-05-03 18:57:225956 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:445957 ssl_options.request_client_certificate = true;
[email protected]ce7d0cbc2013-05-03 18:57:225958 SpawnedTestServer test_server(
5959 SpawnedTestServer::TYPE_HTTPS,
5960 ssl_options,
5961 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445962 ASSERT_TRUE(test_server.Start());
5963
5964 SSLClientAuthTestDelegate d;
5965 {
[email protected]007b3f82013-04-09 08:46:455966 URLRequest r(test_server.GetURL(std::string()), &d, &default_context_);
[email protected]316c1e5e2012-09-12 15:17:445967
5968 r.Start();
5969 EXPECT_TRUE(r.is_pending());
5970
[email protected]255620da2013-08-19 13:14:295971 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445972
5973 EXPECT_EQ(1, d.on_certificate_requested_count());
5974 EXPECT_FALSE(d.received_data_before_response());
5975 EXPECT_EQ(0, d.bytes_received());
5976
5977 // Send no certificate.
5978 // TODO(davidben): Get temporary client cert import (with keys) working on
5979 // all platforms so we can test sending a cert as well.
5980 r.ContinueWithCertificate(NULL);
5981
[email protected]255620da2013-08-19 13:14:295982 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:445983
5984 EXPECT_EQ(1, d.response_started_count());
5985 EXPECT_FALSE(d.received_data_before_response());
5986 EXPECT_NE(0, d.bytes_received());
5987 }
5988}
5989
5990TEST_F(HTTPSRequestTest, ResumeTest) {
5991 // Test that we attempt a session resume when making two connections to the
5992 // same host.
[email protected]ce7d0cbc2013-05-03 18:57:225993 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:445994 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:225995 SpawnedTestServer test_server(
5996 SpawnedTestServer::TYPE_HTTPS,
5997 ssl_options,
5998 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:445999 ASSERT_TRUE(test_server.Start());
6000
6001 SSLClientSocket::ClearSessionCache();
6002
6003 {
6004 TestDelegate d;
6005 URLRequest r(
6006 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
6007
6008 r.Start();
6009 EXPECT_TRUE(r.is_pending());
6010
[email protected]255620da2013-08-19 13:14:296011 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446012
6013 EXPECT_EQ(1, d.response_started_count());
6014 }
6015
6016 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6017 CloseAllConnections();
6018
6019 {
6020 TestDelegate d;
6021 URLRequest r(
6022 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
6023
6024 r.Start();
6025 EXPECT_TRUE(r.is_pending());
6026
[email protected]255620da2013-08-19 13:14:296027 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446028
6029 // The response will look like;
6030 // insert abc
6031 // lookup abc
6032 // insert xyz
6033 //
6034 // With a newline at the end which makes the split think that there are
6035 // four lines.
6036
6037 EXPECT_EQ(1, d.response_started_count());
6038 std::vector<std::string> lines;
6039 base::SplitString(d.data_received(), '\n', &lines);
6040 ASSERT_EQ(4u, lines.size()) << d.data_received();
6041
6042 std::string session_id;
6043
6044 for (size_t i = 0; i < 2; i++) {
6045 std::vector<std::string> parts;
6046 base::SplitString(lines[i], '\t', &parts);
6047 ASSERT_EQ(2u, parts.size());
6048 if (i == 0) {
6049 EXPECT_EQ("insert", parts[0]);
6050 session_id = parts[1];
6051 } else {
6052 EXPECT_EQ("lookup", parts[0]);
6053 EXPECT_EQ(session_id, parts[1]);
6054 }
6055 }
6056 }
6057}
6058
6059TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6060 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6061 // differs.
[email protected]ce7d0cbc2013-05-03 18:57:226062 SpawnedTestServer::SSLOptions ssl_options;
[email protected]316c1e5e2012-09-12 15:17:446063 ssl_options.record_resume = true;
[email protected]ce7d0cbc2013-05-03 18:57:226064 SpawnedTestServer test_server(
6065 SpawnedTestServer::TYPE_HTTPS,
6066 ssl_options,
6067 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]316c1e5e2012-09-12 15:17:446068 ASSERT_TRUE(test_server.Start());
6069
6070 SSLClientSocket::ClearSessionCache();
6071
6072 {
6073 TestDelegate d;
6074 URLRequest r(
6075 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
6076
6077 r.Start();
6078 EXPECT_TRUE(r.is_pending());
6079
[email protected]255620da2013-08-19 13:14:296080 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446081
6082 EXPECT_EQ(1, d.response_started_count());
6083 }
6084
6085 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6086 HttpNetworkSession::Params params;
6087 params.host_resolver = default_context_.host_resolver();
6088 params.cert_verifier = default_context_.cert_verifier();
[email protected]b1c988b2013-06-13 06:48:116089 params.transport_security_state = default_context_.transport_security_state();
[email protected]316c1e5e2012-09-12 15:17:446090 params.proxy_service = default_context_.proxy_service();
6091 params.ssl_config_service = default_context_.ssl_config_service();
6092 params.http_auth_handler_factory =
6093 default_context_.http_auth_handler_factory();
[email protected]cc05edc2013-03-08 18:04:416094 params.network_delegate = &default_network_delegate_;
[email protected]316c1e5e2012-09-12 15:17:446095 params.http_server_properties = default_context_.http_server_properties();
6096 params.ssl_session_cache_shard = "alternate";
6097
6098 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6099 new net::HttpNetworkSession(params),
6100 net::HttpCache::DefaultBackend::InMemory(0)));
6101
6102 default_context_.set_http_transaction_factory(cache.get());
6103
6104 {
6105 TestDelegate d;
6106 URLRequest r(
6107 test_server.GetURL("ssl-session-cache"), &d, &default_context_);
6108
6109 r.Start();
6110 EXPECT_TRUE(r.is_pending());
6111
[email protected]255620da2013-08-19 13:14:296112 base::RunLoop().Run();
[email protected]316c1e5e2012-09-12 15:17:446113
6114 // The response will look like;
6115 // insert abc
6116 // insert xyz
6117 //
6118 // With a newline at the end which makes the split think that there are
6119 // three lines.
6120
6121 EXPECT_EQ(1, d.response_started_count());
6122 std::vector<std::string> lines;
6123 base::SplitString(d.data_received(), '\n', &lines);
6124 ASSERT_EQ(3u, lines.size());
6125
6126 std::string session_id;
6127 for (size_t i = 0; i < 2; i++) {
6128 std::vector<std::string> parts;
6129 base::SplitString(lines[i], '\t', &parts);
6130 ASSERT_EQ(2u, parts.size());
6131 EXPECT_EQ("insert", parts[0]);
6132 if (i == 0) {
6133 session_id = parts[1];
6134 } else {
6135 EXPECT_NE(session_id, parts[1]);
6136 }
6137 }
6138 }
6139}
6140
[email protected]a13234c2012-03-20 21:45:026141class TestSSLConfigService : public SSLConfigService {
[email protected]dffe8242012-03-20 15:14:276142 public:
[email protected]3a86a712013-07-30 07:16:206143 TestSSLConfigService(bool ev_enabled,
6144 bool online_rev_checking,
6145 bool rev_checking_required_local_anchors)
[email protected]a13234c2012-03-20 21:45:026146 : ev_enabled_(ev_enabled),
[email protected]3a86a712013-07-30 07:16:206147 online_rev_checking_(online_rev_checking),
6148 rev_checking_required_local_anchors_(
6149 rev_checking_required_local_anchors) {}
[email protected]a13234c2012-03-20 21:45:026150
[email protected]a9813302012-04-28 09:29:286151 // SSLConfigService:
6152 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
[email protected]dffe8242012-03-20 15:14:276153 *config = SSLConfig();
[email protected]a13234c2012-03-20 21:45:026154 config->rev_checking_enabled = online_rev_checking_;
6155 config->verify_ev_cert = ev_enabled_;
[email protected]3a86a712013-07-30 07:16:206156 config->rev_checking_required_local_anchors =
6157 rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:276158 }
[email protected]a13234c2012-03-20 21:45:026159
[email protected]a9813302012-04-28 09:29:286160 protected:
6161 virtual ~TestSSLConfigService() {}
6162
[email protected]a13234c2012-03-20 21:45:026163 private:
6164 const bool ev_enabled_;
6165 const bool online_rev_checking_;
[email protected]3a86a712013-07-30 07:16:206166 const bool rev_checking_required_local_anchors_;
[email protected]dffe8242012-03-20 15:14:276167};
6168
6169// This the fingerprint of the "Testing CA" certificate used by the testserver.
6170// See net/data/ssl/certificates/ocsp-test-root.pem.
[email protected]ede03212012-09-07 12:52:266171static const SHA1HashValue kOCSPTestCertFingerprint =
[email protected]dffe8242012-03-20 15:14:276172 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
6173 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
6174
[email protected]51523f52013-07-31 21:57:286175// This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
6176// testserver.
6177static const SHA256HashValue kOCSPTestCertSPKI = { {
6178 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
6179 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
6180 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
6181 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
6182} };
6183
[email protected]dffe8242012-03-20 15:14:276184// This is the policy OID contained in the certificates that testserver
6185// generates.
6186static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
6187
6188class HTTPSOCSPTest : public HTTPSRequestTest {
6189 public:
6190 HTTPSOCSPTest()
[email protected]ef2bf422012-05-11 03:27:096191 : context_(true),
[email protected]b6f2de32012-08-17 04:35:086192 ev_test_policy_(
6193 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
6194 kOCSPTestCertFingerprint,
6195 kOCSPTestCertPolicy)) {
[email protected]a13234c2012-03-20 21:45:026196 }
6197
6198 virtual void SetUp() OVERRIDE {
[email protected]ef2bf422012-05-11 03:27:096199 SetupContext(&context_);
6200 context_.Init();
[email protected]dffe8242012-03-20 15:14:276201
6202 scoped_refptr<net::X509Certificate> root_cert =
[email protected]3a86a712013-07-30 07:16:206203 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
[email protected]dffe8242012-03-20 15:14:276204 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
[email protected]90499482013-06-01 00:39:506205 test_root_.reset(new ScopedTestRoot(root_cert.get()));
[email protected]dffe8242012-03-20 15:14:276206
[email protected]a592c0432012-12-01 18:10:296207#if defined(USE_NSS) || defined(OS_IOS)
[email protected]ef2bf422012-05-11 03:27:096208 SetURLRequestContextForNSSHttpIO(&context_);
[email protected]dffe8242012-03-20 15:14:276209 EnsureNSSHttpIOInit();
6210#endif
6211 }
6212
[email protected]ce7d0cbc2013-05-03 18:57:226213 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
[email protected]dffe8242012-03-20 15:14:276214 CertStatus* out_cert_status) {
[email protected]924e9f92012-12-16 22:00:536215 // We always overwrite out_cert_status.
6216 *out_cert_status = 0;
[email protected]ce7d0cbc2013-05-03 18:57:226217 SpawnedTestServer test_server(
6218 SpawnedTestServer::TYPE_HTTPS,
6219 ssl_options,
6220 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
[email protected]dffe8242012-03-20 15:14:276221 ASSERT_TRUE(test_server.Start());
6222
6223 TestDelegate d;
6224 d.set_allow_certificate_errors(true);
[email protected]007b3f82013-04-09 08:46:456225 URLRequest r(test_server.GetURL(std::string()), &d, &context_);
[email protected]dffe8242012-03-20 15:14:276226 r.Start();
6227
[email protected]255620da2013-08-19 13:14:296228 base::RunLoop().Run();
[email protected]dffe8242012-03-20 15:14:276229
6230 EXPECT_EQ(1, d.response_started_count());
6231 *out_cert_status = r.ssl_info().cert_status;
6232 }
6233
[email protected]46fadfd2013-02-06 09:40:166234 virtual ~HTTPSOCSPTest() {
[email protected]a592c0432012-12-01 18:10:296235#if defined(USE_NSS) || defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:276236 ShutdownNSSHttpIO();
6237#endif
6238 }
6239
[email protected]a13234c2012-03-20 21:45:026240 protected:
6241 // SetupContext configures the URLRequestContext that will be used for making
6242 // connetions to testserver. This can be overridden in test subclasses for
6243 // different behaviour.
6244 virtual void SetupContext(URLRequestContext* context) {
6245 context->set_ssl_config_service(
6246 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206247 true /* online revocation checking */,
6248 false /* require rev. checking for local
6249 anchors */));
[email protected]a13234c2012-03-20 21:45:026250 }
6251
[email protected]dffe8242012-03-20 15:14:276252 scoped_ptr<ScopedTestRoot> test_root_;
[email protected]ef2bf422012-05-11 03:27:096253 TestURLRequestContext context_;
[email protected]b6f2de32012-08-17 04:35:086254 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
[email protected]dffe8242012-03-20 15:14:276255};
6256
[email protected]a13234c2012-03-20 21:45:026257static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
[email protected]05454a432012-03-20 20:04:016258#if defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:026259 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
6260 // have that ability on other platforms.
6261 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
6262#else
6263 return 0;
6264#endif
6265}
6266
[email protected]3a86a712013-07-30 07:16:206267// SystemSupportsHardFailRevocationChecking returns true iff the current
6268// operating system supports revocation checking and can distinguish between
6269// situations where a given certificate lacks any revocation information (eg:
6270// no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
6271// revocation information cannot be obtained (eg: the CRL was unreachable).
6272// If it does not, then tests which rely on 'hard fail' behaviour should be
6273// skipped.
6274static bool SystemSupportsHardFailRevocationChecking() {
6275#if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
6276 return true;
6277#else
6278 return false;
6279#endif
6280}
6281
[email protected]a13234c2012-03-20 21:45:026282// SystemUsesChromiumEVMetadata returns true iff the current operating system
6283// uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
6284// several tests are effected because our testing EV certificate won't be
6285// recognised as EV.
6286static bool SystemUsesChromiumEVMetadata() {
[email protected]5c504192012-03-27 19:00:576287#if defined(USE_OPENSSL)
6288 // http://crbug.com/117478 - OpenSSL does not support EV validation.
6289 return false;
[email protected]a592c0432012-12-01 18:10:296290#elif defined(OS_MACOSX) && !defined(OS_IOS)
[email protected]a13234c2012-03-20 21:45:026291 // On OS X, we use the system to tell us whether a certificate is EV or not
6292 // and the system won't recognise our testing root.
[email protected]05454a432012-03-20 20:04:016293 return false;
6294#else
6295 return true;
6296#endif
6297}
6298
[email protected]b6f2de32012-08-17 04:35:086299static bool SystemSupportsOCSP() {
[email protected]5c504192012-03-27 19:00:576300#if defined(USE_OPENSSL)
6301 // http://crbug.com/117478 - OpenSSL does not support OCSP.
6302 return false;
6303#elif defined(OS_WIN)
[email protected]a13234c2012-03-20 21:45:026304 return base::win::GetVersion() >= base::win::VERSION_VISTA;
6305#elif defined(OS_ANDROID)
6306 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
6307 return false;
6308#else
6309 return true;
6310#endif
6311}
6312
[email protected]dffe8242012-03-20 15:14:276313TEST_F(HTTPSOCSPTest, Valid) {
6314 if (!SystemSupportsOCSP()) {
6315 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6316 return;
6317 }
6318
[email protected]ce7d0cbc2013-05-03 18:57:226319 SpawnedTestServer::SSLOptions ssl_options(
6320 SpawnedTestServer::SSLOptions::CERT_AUTO);
6321 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]dffe8242012-03-20 15:14:276322
[email protected]924e9f92012-12-16 22:00:536323 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126324 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276325
6326 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6327
[email protected]a13234c2012-03-20 21:45:026328 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6329 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]dffe8242012-03-20 15:14:276330
6331 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6332}
6333
6334TEST_F(HTTPSOCSPTest, Revoked) {
6335 if (!SystemSupportsOCSP()) {
6336 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6337 return;
6338 }
6339
[email protected]ce7d0cbc2013-05-03 18:57:226340 SpawnedTestServer::SSLOptions ssl_options(
6341 SpawnedTestServer::SSLOptions::CERT_AUTO);
6342 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]dffe8242012-03-20 15:14:276343
6344 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126345 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276346
[email protected]a592c0432012-12-01 18:10:296347#if !(defined(OS_MACOSX) && !defined(OS_IOS))
[email protected]dffe8242012-03-20 15:14:276348 // Doesn't pass on OS X yet for reasons that need to be investigated.
6349 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6350#endif
6351 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6352 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6353}
6354
6355TEST_F(HTTPSOCSPTest, Invalid) {
6356 if (!SystemSupportsOCSP()) {
6357 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6358 return;
6359 }
6360
[email protected]ce7d0cbc2013-05-03 18:57:226361 SpawnedTestServer::SSLOptions ssl_options(
6362 SpawnedTestServer::SSLOptions::CERT_AUTO);
6363 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]dffe8242012-03-20 15:14:276364
[email protected]924e9f92012-12-16 22:00:536365 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126366 DoConnection(ssl_options, &cert_status);
[email protected]dffe8242012-03-20 15:14:276367
[email protected]a13234c2012-03-20 21:45:026368 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
[email protected]dffe8242012-03-20 15:14:276369 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]dffe8242012-03-20 15:14:276370
6371 // Without a positive OCSP response, we shouldn't show the EV status.
6372 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6373 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6374}
[email protected]a13234c2012-03-20 21:45:026375
[email protected]3a86a712013-07-30 07:16:206376class HTTPSHardFailTest : public HTTPSOCSPTest {
6377 protected:
6378 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6379 context->set_ssl_config_service(
6380 new TestSSLConfigService(false /* check for EV */,
6381 false /* online revocation checking */,
6382 true /* require rev. checking for local
6383 anchors */));
6384 }
6385};
6386
6387
6388TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
6389 if (!SystemSupportsOCSP()) {
6390 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6391 return;
6392 }
6393
6394 if (!SystemSupportsHardFailRevocationChecking()) {
6395 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
6396 << "revocation checking";
6397 return;
6398 }
6399
6400 SpawnedTestServer::SSLOptions ssl_options(
6401 SpawnedTestServer::SSLOptions::CERT_AUTO);
6402 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
6403
6404 CertStatus cert_status;
6405 DoConnection(ssl_options, &cert_status);
6406
6407 EXPECT_EQ(CERT_STATUS_REVOKED,
6408 cert_status & CERT_STATUS_REVOKED);
6409
6410 // Without a positive OCSP response, we shouldn't show the EV status.
6411 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6412}
6413
[email protected]a13234c2012-03-20 21:45:026414class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
6415 protected:
6416 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6417 context->set_ssl_config_service(
6418 new TestSSLConfigService(true /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206419 false /* online revocation checking */,
6420 false /* require rev. checking for local
6421 anchors */));
[email protected]a13234c2012-03-20 21:45:026422 }
6423};
6424
6425TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
6426 if (!SystemSupportsOCSP()) {
6427 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6428 return;
6429 }
6430
[email protected]ce7d0cbc2013-05-03 18:57:226431 SpawnedTestServer::SSLOptions ssl_options(
6432 SpawnedTestServer::SSLOptions::CERT_AUTO);
6433 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026434 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6435
[email protected]924e9f92012-12-16 22:00:536436 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126437 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026438
6439 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6440 cert_status & CERT_STATUS_ALL_ERRORS);
6441
6442 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:086443 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6444 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026445}
6446
[email protected]be0fff62013-08-29 23:37:486447TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
6448 if (!SystemSupportsOCSP()) {
6449 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6450 return;
6451 }
6452
6453 SpawnedTestServer::SSLOptions ssl_options(
6454 SpawnedTestServer::SSLOptions::CERT_AUTO);
6455 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
6456 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6457
6458 CertStatus cert_status;
6459 DoConnection(ssl_options, &cert_status);
6460
6461 // Currently only works for Windows. When using NSS or OS X, it's not
6462 // possible to determine whether the check failed because of actual
6463 // revocation or because there was an OCSP failure.
6464#if defined(OS_WIN)
6465 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6466#else
6467 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6468#endif
6469
6470 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6471 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6472 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6473}
6474
[email protected]a13234c2012-03-20 21:45:026475TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
6476 if (!SystemSupportsOCSP()) {
6477 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6478 return;
6479 }
6480
[email protected]ce7d0cbc2013-05-03 18:57:226481 SpawnedTestServer::SSLOptions ssl_options(
6482 SpawnedTestServer::SSLOptions::CERT_AUTO);
6483 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
[email protected]a13234c2012-03-20 21:45:026484 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
6485
6486 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126487 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026488
6489 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6490
6491 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6492 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
[email protected]b6f2de32012-08-17 04:35:086493 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6494 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026495}
6496
6497TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
6498 if (!SystemSupportsOCSP()) {
6499 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6500 return;
6501 }
6502
[email protected]ce7d0cbc2013-05-03 18:57:226503 SpawnedTestServer::SSLOptions ssl_options(
6504 SpawnedTestServer::SSLOptions::CERT_AUTO);
6505 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026506 SSLConfigService::SetCRLSet(
6507 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6508
6509 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126510 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026511
6512 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6513 cert_status & CERT_STATUS_ALL_ERRORS);
6514
6515 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]b6f2de32012-08-17 04:35:086516 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6517 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026518}
6519
[email protected]51523f52013-07-31 21:57:286520TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
6521 if (!SystemSupportsOCSP()) {
6522 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6523 return;
6524 }
6525
6526 SpawnedTestServer::SSLOptions ssl_options(
6527 SpawnedTestServer::SSLOptions::CERT_AUTO);
6528 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
6529 SSLConfigService::SetCRLSet(
6530 scoped_refptr<CRLSet>(CRLSet::ForTesting(
6531 false, &kOCSPTestCertSPKI, "")));
6532
6533 CertStatus cert_status;
6534 DoConnection(ssl_options, &cert_status);
6535
6536 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
6537 // revocation check for EV.
6538 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6539 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
6540 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
6541 EXPECT_FALSE(
6542 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6543}
6544
6545TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
6546 if (!SystemSupportsOCSP()) {
6547 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6548 return;
6549 }
6550
[email protected]ce7d0cbc2013-05-03 18:57:226551 SpawnedTestServer::SSLOptions ssl_options(
6552 SpawnedTestServer::SSLOptions::CERT_AUTO);
6553 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026554 SSLConfigService::SetCRLSet(
6555 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
6556
[email protected]51523f52013-07-31 21:57:286557 CertStatus cert_status = 0;
[email protected]295e5cd2012-08-23 01:05:126558 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026559
[email protected]51523f52013-07-31 21:57:286560 // Even with a fresh CRLSet, we should still do online revocation checks when
6561 // the certificate chain isn't covered by the CRLSet, which it isn't in this
6562 // test.
6563 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
6564 cert_status & CERT_STATUS_ALL_ERRORS);
[email protected]a13234c2012-03-20 21:45:026565
[email protected]51523f52013-07-31 21:57:286566 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
[email protected]a13234c2012-03-20 21:45:026567 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
[email protected]51523f52013-07-31 21:57:286568 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
[email protected]a13234c2012-03-20 21:45:026569}
6570
[email protected]b6f2de32012-08-17 04:35:086571TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
6572 // Test that when EV verification is requested, but online revocation
6573 // checking is disabled, and the leaf certificate is not in fact EV, that
6574 // no revocation checking actually happens.
6575 if (!SystemSupportsOCSP()) {
6576 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
6577 return;
6578 }
6579
6580 // Unmark the certificate's OID as EV, which should disable revocation
6581 // checking (as per the user preference)
6582 ev_test_policy_.reset();
6583
[email protected]ce7d0cbc2013-05-03 18:57:226584 SpawnedTestServer::SSLOptions ssl_options(
6585 SpawnedTestServer::SSLOptions::CERT_AUTO);
6586 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
[email protected]b6f2de32012-08-17 04:35:086587 SSLConfigService::SetCRLSet(
6588 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6589
6590 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126591 DoConnection(ssl_options, &cert_status);
[email protected]b6f2de32012-08-17 04:35:086592
6593 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6594
6595 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6596 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6597}
6598
[email protected]a13234c2012-03-20 21:45:026599class HTTPSCRLSetTest : public HTTPSOCSPTest {
6600 protected:
6601 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
6602 context->set_ssl_config_service(
6603 new TestSSLConfigService(false /* check for EV */,
[email protected]3a86a712013-07-30 07:16:206604 false /* online revocation checking */,
6605 false /* require rev. checking for local
6606 anchors */));
[email protected]a13234c2012-03-20 21:45:026607 }
6608};
6609
6610TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
[email protected]ce7d0cbc2013-05-03 18:57:226611 SpawnedTestServer::SSLOptions ssl_options(
6612 SpawnedTestServer::SSLOptions::CERT_AUTO);
6613 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
[email protected]a13234c2012-03-20 21:45:026614 SSLConfigService::SetCRLSet(
6615 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
6616
[email protected]924e9f92012-12-16 22:00:536617 CertStatus cert_status;
[email protected]295e5cd2012-08-23 01:05:126618 DoConnection(ssl_options, &cert_status);
[email protected]a13234c2012-03-20 21:45:026619
6620 // If we're not trying EV verification then, even if the CRLSet has expired,
6621 // we don't fall back to online revocation checks.
6622 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
6623 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6624 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
6625}
[email protected]51523f52013-07-31 21:57:286626
6627TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
6628#if defined(USE_OPENSSL)
6629 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
6630 return;
6631#endif
6632
6633 SpawnedTestServer::SSLOptions ssl_options(
6634 SpawnedTestServer::SSLOptions::CERT_AUTO);
6635 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
6636 ssl_options.cert_serial = 10;
6637 SSLConfigService::SetCRLSet(
6638 scoped_refptr<CRLSet>(CRLSet::ForTesting(
6639 false, &kOCSPTestCertSPKI, "\x0a")));
6640
6641 CertStatus cert_status = 0;
6642 DoConnection(ssl_options, &cert_status);
6643
6644 // If the certificate is recorded as revoked in the CRLSet, that should be
6645 // reflected without online revocation checking.
6646 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
6647 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
6648 EXPECT_FALSE(
6649 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
6650}
[email protected]316c1e5e2012-09-12 15:17:446651#endif // !defined(OS_IOS)
[email protected]dffe8242012-03-20 15:14:276652
[email protected]316c1e5e2012-09-12 15:17:446653#if !defined(DISABLE_FTP_SUPPORT)
[email protected]b89ca032009-08-31 21:41:316654class URLRequestTestFTP : public URLRequestTest {
[email protected]95409e12010-08-17 20:07:116655 public:
[email protected]d9fca99a2012-02-24 16:16:206656 URLRequestTestFTP()
[email protected]ce7d0cbc2013-05-03 18:57:226657 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
[email protected]6cdfd7f2013-02-08 20:40:156658 base::FilePath()) {
[email protected]95409e12010-08-17 20:07:116659 }
6660
[email protected]b89ca032009-08-31 21:41:316661 protected:
[email protected]ce7d0cbc2013-05-03 18:57:226662 SpawnedTestServer test_server_;
[email protected]b89ca032009-08-31 21:41:316663};
6664
[email protected]d2a133182012-08-05 16:44:086665// Make sure an FTP request using an unsafe ports fails.
[email protected]f2f31b32013-01-16 23:24:096666TEST_F(URLRequestTestFTP, UnsafePort) {
[email protected]d2a133182012-08-05 16:44:086667 ASSERT_TRUE(test_server_.Start());
6668
[email protected]9d5730b2012-08-24 17:42:496669 URLRequestJobFactoryImpl job_factory;
[email protected]e0f35c92013-05-08 16:04:346670 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
[email protected]d2a133182012-08-05 16:44:086671
6672 GURL url("ftp://127.0.0.1:7");
[email protected]d2a133182012-08-05 16:44:086673 job_factory.SetProtocolHandler(
6674 "ftp",
[email protected]e0f35c92013-05-08 16:04:346675 new FtpProtocolHandler(&ftp_transaction_factory));
[email protected]d2a133182012-08-05 16:44:086676 default_context_.set_job_factory(&job_factory);
6677
6678 TestDelegate d;
6679 {
6680 URLRequest r(url, &d, &default_context_);
6681 r.Start();
6682 EXPECT_TRUE(r.is_pending());
6683
[email protected]255620da2013-08-19 13:14:296684 base::RunLoop().Run();
[email protected]d2a133182012-08-05 16:44:086685
6686 EXPECT_FALSE(r.is_pending());
6687 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
6688 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
6689 }
6690}
6691
[email protected]5accf7332009-11-24 03:41:386692// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126693TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
[email protected]95409e12010-08-17 20:07:116694 ASSERT_TRUE(test_server_.Start());
6695
[email protected]a25e90e2009-09-09 17:05:376696 TestDelegate d;
6697 {
[email protected]94e2bbe2012-06-22 15:26:136698 URLRequest r(test_server_.GetURL("/"), &d, &default_context_);
[email protected]a25e90e2009-09-09 17:05:376699 r.Start();
6700 EXPECT_TRUE(r.is_pending());
6701
[email protected]255620da2013-08-19 13:14:296702 base::RunLoop().Run();
[email protected]a25e90e2009-09-09 17:05:376703
6704 EXPECT_FALSE(r.is_pending());
6705 EXPECT_EQ(1, d.response_started_count());
6706 EXPECT_FALSE(d.received_data_before_response());
6707 EXPECT_LT(0, d.bytes_received());
[email protected]6d81b482011-02-22 19:47:196708 EXPECT_EQ(test_server_.host_port_pair().host(),
6709 r.GetSocketAddress().host());
6710 EXPECT_EQ(test_server_.host_port_pair().port(),
6711 r.GetSocketAddress().port());
[email protected]a25e90e2009-09-09 17:05:376712 }
6713}
6714
[email protected]7df70012010-02-04 00:09:556715// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126716TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
[email protected]95409e12010-08-17 20:07:116717 ASSERT_TRUE(test_server_.Start());
6718
[email protected]6cdfd7f2013-02-08 20:40:156719 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276720 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026721 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276722 TestDelegate d;
6723 {
[email protected]94e2bbe2012-06-22 15:26:136724 URLRequest r(test_server_.GetURL("/LICENSE"), &d, &default_context_);
[email protected]dd265012009-01-08 20:45:276725 r.Start();
6726 EXPECT_TRUE(r.is_pending());
6727
[email protected]255620da2013-08-19 13:14:296728 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276729
6730 int64 file_size = 0;
6731 file_util::GetFileSize(app_path, &file_size);
6732
[email protected]ba2f3342009-07-30 18:08:426733 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276734 EXPECT_EQ(1, d.response_started_count());
6735 EXPECT_FALSE(d.received_data_before_response());
6736 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]6d81b482011-02-22 19:47:196737 EXPECT_EQ(test_server_.host_port_pair().host(),
6738 r.GetSocketAddress().host());
6739 EXPECT_EQ(test_server_.host_port_pair().port(),
6740 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:276741 }
6742}
6743
[email protected]e9ecbd12009-12-20 18:44:406744// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126745TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
[email protected]95409e12010-08-17 20:07:116746 ASSERT_TRUE(test_server_.Start());
6747
[email protected]6cdfd7f2013-02-08 20:40:156748 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276749 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026750 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276751 TestDelegate d;
6752 {
[email protected]ef2bf422012-05-11 03:27:096753 URLRequest r(
[email protected]95409e12010-08-17 20:07:116754 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136755 &d,
6756 &default_context_);
[email protected]dd265012009-01-08 20:45:276757 r.Start();
6758 EXPECT_TRUE(r.is_pending());
6759
[email protected]255620da2013-08-19 13:14:296760 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276761
6762 int64 file_size = 0;
6763 file_util::GetFileSize(app_path, &file_size);
6764
[email protected]ba2f3342009-07-30 18:08:426765 EXPECT_FALSE(r.is_pending());
[email protected]6d81b482011-02-22 19:47:196766 EXPECT_EQ(test_server_.host_port_pair().host(),
6767 r.GetSocketAddress().host());
6768 EXPECT_EQ(test_server_.host_port_pair().port(),
6769 r.GetSocketAddress().port());
[email protected]dd265012009-01-08 20:45:276770 EXPECT_EQ(1, d.response_started_count());
6771 EXPECT_FALSE(d.received_data_before_response());
6772 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
[email protected]58e32bb2013-01-21 18:23:256773
6774 LoadTimingInfo load_timing_info;
[email protected]0a703912013-02-02 04:25:176775 r.GetLoadTimingInfo(&load_timing_info);
[email protected]3b23a222013-05-15 21:33:256776 TestLoadTimingNoHttpResponse(load_timing_info);
[email protected]dd265012009-01-08 20:45:276777 }
6778}
6779
[email protected]49abd652010-08-05 05:04:536780// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126781TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
[email protected]95409e12010-08-17 20:07:116782 ASSERT_TRUE(test_server_.Start());
6783
[email protected]6cdfd7f2013-02-08 20:40:156784 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276785 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026786 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276787 TestDelegate d;
6788 {
[email protected]ef2bf422012-05-11 03:27:096789 URLRequest r(
[email protected]95409e12010-08-17 20:07:116790 test_server_.GetURLWithUserAndPassword("/LICENSE",
6791 "chrome",
6792 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136793 &d,
6794 &default_context_);
[email protected]dd265012009-01-08 20:45:276795 r.Start();
6796 EXPECT_TRUE(r.is_pending());
6797
[email protected]255620da2013-08-19 13:14:296798 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276799
6800 int64 file_size = 0;
6801 file_util::GetFileSize(app_path, &file_size);
6802
[email protected]ba2f3342009-07-30 18:08:426803 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276804 EXPECT_EQ(1, d.response_started_count());
6805 EXPECT_FALSE(d.received_data_before_response());
6806 EXPECT_EQ(d.bytes_received(), 0);
6807 }
6808}
6809
[email protected]cde4e80d2009-10-16 19:58:156810// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126811TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
[email protected]95409e12010-08-17 20:07:116812 ASSERT_TRUE(test_server_.Start());
6813
[email protected]6cdfd7f2013-02-08 20:40:156814 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:586815 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6816 app_path = app_path.AppendASCII("LICENSE");
6817 TestDelegate d;
6818 // Set correct login credentials. The delegate will be asked for them when
6819 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586820 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:586821 {
[email protected]ef2bf422012-05-11 03:27:096822 URLRequest r(
[email protected]95409e12010-08-17 20:07:116823 test_server_.GetURLWithUserAndPassword("/LICENSE",
6824 "chrome",
6825 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136826 &d,
6827 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:586828 r.Start();
6829 EXPECT_TRUE(r.is_pending());
6830
[email protected]255620da2013-08-19 13:14:296831 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:586832
6833 int64 file_size = 0;
6834 file_util::GetFileSize(app_path, &file_size);
6835
6836 EXPECT_FALSE(r.is_pending());
6837 EXPECT_EQ(1, d.response_started_count());
6838 EXPECT_FALSE(d.received_data_before_response());
6839 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
6840 }
6841}
6842
[email protected]49abd652010-08-05 05:04:536843// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126844TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
[email protected]95409e12010-08-17 20:07:116845 ASSERT_TRUE(test_server_.Start());
6846
[email protected]6cdfd7f2013-02-08 20:40:156847 base::FilePath app_path;
[email protected]dd265012009-01-08 20:45:276848 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
[email protected]399b8702009-05-01 20:34:026849 app_path = app_path.AppendASCII("LICENSE");
[email protected]dd265012009-01-08 20:45:276850 TestDelegate d;
6851 {
[email protected]ef2bf422012-05-11 03:27:096852 URLRequest r(
[email protected]95409e12010-08-17 20:07:116853 test_server_.GetURLWithUserAndPassword("/LICENSE",
6854 "wrong_user",
6855 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136856 &d,
6857 &default_context_);
[email protected]dd265012009-01-08 20:45:276858 r.Start();
6859 EXPECT_TRUE(r.is_pending());
6860
[email protected]255620da2013-08-19 13:14:296861 base::RunLoop().Run();
[email protected]dd265012009-01-08 20:45:276862
6863 int64 file_size = 0;
6864 file_util::GetFileSize(app_path, &file_size);
6865
[email protected]ba2f3342009-07-30 18:08:426866 EXPECT_FALSE(r.is_pending());
[email protected]dd265012009-01-08 20:45:276867 EXPECT_EQ(1, d.response_started_count());
6868 EXPECT_FALSE(d.received_data_before_response());
6869 EXPECT_EQ(d.bytes_received(), 0);
6870 }
6871}
[email protected]8b8a197d2009-08-26 15:57:586872
[email protected]cde4e80d2009-10-16 19:58:156873// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126874TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
[email protected]95409e12010-08-17 20:07:116875 ASSERT_TRUE(test_server_.Start());
6876
[email protected]6cdfd7f2013-02-08 20:40:156877 base::FilePath app_path;
[email protected]8b8a197d2009-08-26 15:57:586878 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6879 app_path = app_path.AppendASCII("LICENSE");
6880 TestDelegate d;
6881 // Set correct login credentials. The delegate will be asked for them when
6882 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586883 d.set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]8b8a197d2009-08-26 15:57:586884 {
[email protected]ef2bf422012-05-11 03:27:096885 URLRequest r(
[email protected]95409e12010-08-17 20:07:116886 test_server_.GetURLWithUserAndPassword("/LICENSE",
6887 "wrong_user",
6888 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136889 &d,
6890 &default_context_);
[email protected]8b8a197d2009-08-26 15:57:586891 r.Start();
6892 EXPECT_TRUE(r.is_pending());
6893
[email protected]255620da2013-08-19 13:14:296894 base::RunLoop().Run();
[email protected]8b8a197d2009-08-26 15:57:586895
6896 int64 file_size = 0;
6897 file_util::GetFileSize(app_path, &file_size);
6898
6899 EXPECT_FALSE(r.is_pending());
6900 EXPECT_EQ(1, d.response_started_count());
6901 EXPECT_FALSE(d.received_data_before_response());
6902 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
6903 }
6904}
[email protected]60a3df52009-09-22 16:13:246905
[email protected]cde4e80d2009-10-16 19:58:156906// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126907TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
[email protected]95409e12010-08-17 20:07:116908 ASSERT_TRUE(test_server_.Start());
6909
[email protected]6cdfd7f2013-02-08 20:40:156910 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:246911 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6912 app_path = app_path.AppendASCII("LICENSE");
6913
6914 scoped_ptr<TestDelegate> d(new TestDelegate);
6915 {
6916 // Pass correct login identity in the URL.
[email protected]ef2bf422012-05-11 03:27:096917 URLRequest r(
[email protected]95409e12010-08-17 20:07:116918 test_server_.GetURLWithUserAndPassword("/LICENSE",
6919 "chrome",
6920 "chrome"),
[email protected]94e2bbe2012-06-22 15:26:136921 d.get(),
6922 &default_context_);
[email protected]60a3df52009-09-22 16:13:246923 r.Start();
6924 EXPECT_TRUE(r.is_pending());
6925
[email protected]255620da2013-08-19 13:14:296926 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246927
6928 int64 file_size = 0;
6929 file_util::GetFileSize(app_path, &file_size);
6930
6931 EXPECT_FALSE(r.is_pending());
6932 EXPECT_EQ(1, d->response_started_count());
6933 EXPECT_FALSE(d->received_data_before_response());
6934 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6935 }
6936
6937 d.reset(new TestDelegate);
6938 {
6939 // This request should use cached identity from previous request.
[email protected]94e2bbe2012-06-22 15:26:136940 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:246941 r.Start();
6942 EXPECT_TRUE(r.is_pending());
6943
[email protected]255620da2013-08-19 13:14:296944 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246945
6946 int64 file_size = 0;
6947 file_util::GetFileSize(app_path, &file_size);
6948
6949 EXPECT_FALSE(r.is_pending());
6950 EXPECT_EQ(1, d->response_started_count());
6951 EXPECT_FALSE(d->received_data_before_response());
6952 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6953 }
6954}
6955
[email protected]cde4e80d2009-10-16 19:58:156956// Flaky, see http://crbug.com/25045.
[email protected]9ef1d98e2012-02-14 00:34:126957TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
[email protected]95409e12010-08-17 20:07:116958 ASSERT_TRUE(test_server_.Start());
6959
[email protected]6cdfd7f2013-02-08 20:40:156960 base::FilePath app_path;
[email protected]60a3df52009-09-22 16:13:246961 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
6962 app_path = app_path.AppendASCII("LICENSE");
6963
6964 scoped_ptr<TestDelegate> d(new TestDelegate);
6965 // Set correct login credentials. The delegate will be asked for them when
6966 // the initial login with wrong credentials will fail.
[email protected]f3cf9802011-10-28 18:44:586967 d->set_credentials(AuthCredentials(kChrome, kChrome));
[email protected]60a3df52009-09-22 16:13:246968 {
[email protected]ef2bf422012-05-11 03:27:096969 URLRequest r(
[email protected]95409e12010-08-17 20:07:116970 test_server_.GetURLWithUserAndPassword("/LICENSE",
6971 "chrome",
6972 "wrong_password"),
[email protected]94e2bbe2012-06-22 15:26:136973 d.get(),
6974 &default_context_);
[email protected]60a3df52009-09-22 16:13:246975 r.Start();
6976 EXPECT_TRUE(r.is_pending());
6977
[email protected]255620da2013-08-19 13:14:296978 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:246979
6980 int64 file_size = 0;
6981 file_util::GetFileSize(app_path, &file_size);
6982
6983 EXPECT_FALSE(r.is_pending());
6984 EXPECT_EQ(1, d->response_started_count());
6985 EXPECT_FALSE(d->received_data_before_response());
6986 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
6987 }
6988
6989 // Use a new delegate without explicit credentials. The cached ones should be
6990 // used.
6991 d.reset(new TestDelegate);
6992 {
6993 // Don't pass wrong credentials in the URL, they would override valid cached
6994 // ones.
[email protected]94e2bbe2012-06-22 15:26:136995 URLRequest r(test_server_.GetURL("/LICENSE"), d.get(), &default_context_);
[email protected]60a3df52009-09-22 16:13:246996 r.Start();
6997 EXPECT_TRUE(r.is_pending());
6998
[email protected]255620da2013-08-19 13:14:296999 base::RunLoop().Run();
[email protected]60a3df52009-09-22 16:13:247000
7001 int64 file_size = 0;
7002 file_util::GetFileSize(app_path, &file_size);
7003
7004 EXPECT_FALSE(r.is_pending());
7005 EXPECT_EQ(1, d->response_started_count());
7006 EXPECT_FALSE(d->received_data_before_response());
7007 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7008 }
7009}
[email protected]316c1e5e2012-09-12 15:17:447010#endif // !defined(DISABLE_FTP_SUPPORT)
[email protected]7461a402011-03-24 23:19:517011
7012} // namespace net