Fix ChromePublic icon and app name.
[chromium-blink-merge.git] / net / proxy / proxy_script_fetcher_impl_unittest.cc
blobdd49b56c68aa13c02bd41b6d9392ee109be1f2cf
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/proxy/proxy_script_fetcher_impl.h"
7 #include <string>
9 #include "base/compiler_specific.h"
10 #include "base/files/file_path.h"
11 #include "base/path_service.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "net/base/filename_util.h"
16 #include "net/base/load_flags.h"
17 #include "net/base/network_delegate_impl.h"
18 #include "net/base/test_completion_callback.h"
19 #include "net/cert/mock_cert_verifier.h"
20 #include "net/disk_cache/disk_cache.h"
21 #include "net/dns/mock_host_resolver.h"
22 #include "net/http/http_cache.h"
23 #include "net/http/http_network_session.h"
24 #include "net/http/http_server_properties_impl.h"
25 #include "net/http/transport_security_state.h"
26 #include "net/ssl/ssl_config_service_defaults.h"
27 #include "net/test/spawned_test_server/spawned_test_server.h"
28 #include "net/url_request/url_request_context_storage.h"
29 #include "net/url_request/url_request_file_job.h"
30 #include "net/url_request/url_request_job_factory_impl.h"
31 #include "net/url_request/url_request_test_util.h"
32 #include "testing/gtest/include/gtest/gtest.h"
33 #include "testing/platform_test.h"
35 #if !defined(DISABLE_FILE_SUPPORT)
36 #include "net/url_request/file_protocol_handler.h"
37 #endif
39 using base::ASCIIToUTF16;
41 // TODO(eroman):
42 // - Test canceling an outstanding request.
43 // - Test deleting ProxyScriptFetcher while a request is in progress.
45 namespace net {
47 namespace {
49 const base::FilePath::CharType kDocRoot[] =
50 FILE_PATH_LITERAL("net/data/proxy_script_fetcher_unittest");
52 struct FetchResult {
53 int code;
54 base::string16 text;
57 // A non-mock URL request which can access http:// and file:// urls, in the case
58 // the tests were built with file support.
59 class RequestContext : public URLRequestContext {
60 public:
61 RequestContext() : storage_(this) {
62 ProxyConfig no_proxy;
63 storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver));
64 storage_.set_cert_verifier(new MockCertVerifier);
65 storage_.set_transport_security_state(new TransportSecurityState);
66 storage_.set_proxy_service(ProxyService::CreateFixed(no_proxy));
67 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
68 storage_.set_http_server_properties(
69 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
71 HttpNetworkSession::Params params;
72 params.host_resolver = host_resolver();
73 params.cert_verifier = cert_verifier();
74 params.transport_security_state = transport_security_state();
75 params.proxy_service = proxy_service();
76 params.ssl_config_service = ssl_config_service();
77 params.http_server_properties = http_server_properties();
78 scoped_refptr<HttpNetworkSession> network_session(
79 new HttpNetworkSession(params));
80 storage_.set_http_transaction_factory(new HttpCache(
81 network_session.get(), HttpCache::DefaultBackend::InMemory(0)));
82 URLRequestJobFactoryImpl* job_factory = new URLRequestJobFactoryImpl();
83 #if !defined(DISABLE_FILE_SUPPORT)
84 job_factory->SetProtocolHandler(
85 "file", new FileProtocolHandler(base::ThreadTaskRunnerHandle::Get()));
86 #endif
87 storage_.set_job_factory(job_factory);
90 ~RequestContext() override { AssertNoURLRequests(); }
92 private:
93 URLRequestContextStorage storage_;
96 #if !defined(DISABLE_FILE_SUPPORT)
97 // Get a file:// url relative to net/data/proxy/proxy_script_fetcher_unittest.
98 GURL GetTestFileUrl(const std::string& relpath) {
99 base::FilePath path;
100 PathService::Get(base::DIR_SOURCE_ROOT, &path);
101 path = path.AppendASCII("net");
102 path = path.AppendASCII("data");
103 path = path.AppendASCII("proxy_script_fetcher_unittest");
104 GURL base_url = FilePathToFileURL(path);
105 return GURL(base_url.spec() + "/" + relpath);
107 #endif // !defined(DISABLE_FILE_SUPPORT)
109 // Really simple NetworkDelegate so we can allow local file access on ChromeOS
110 // without introducing layering violations. Also causes a test failure if a
111 // request is seen that doesn't set a load flag to bypass revocation checking.
113 class BasicNetworkDelegate : public NetworkDelegateImpl {
114 public:
115 BasicNetworkDelegate() {}
116 ~BasicNetworkDelegate() override {}
118 private:
119 int OnBeforeURLRequest(URLRequest* request,
120 const CompletionCallback& callback,
121 GURL* new_url) override {
122 EXPECT_TRUE(request->load_flags() & LOAD_DISABLE_CERT_REVOCATION_CHECKING);
123 return OK;
126 int OnBeforeSendHeaders(URLRequest* request,
127 const CompletionCallback& callback,
128 HttpRequestHeaders* headers) override {
129 return OK;
132 void OnSendHeaders(URLRequest* request,
133 const HttpRequestHeaders& headers) override {}
135 int OnHeadersReceived(
136 URLRequest* request,
137 const CompletionCallback& callback,
138 const HttpResponseHeaders* original_response_headers,
139 scoped_refptr<HttpResponseHeaders>* override_response_headers,
140 GURL* allowed_unsafe_redirect_url) override {
141 return OK;
144 void OnBeforeRedirect(URLRequest* request,
145 const GURL& new_location) override {}
147 void OnResponseStarted(URLRequest* request) override {}
149 void OnRawBytesRead(const URLRequest& request, int bytes_read) override {}
151 void OnCompleted(URLRequest* request, bool started) override {}
153 void OnURLRequestDestroyed(URLRequest* request) override {}
155 void OnPACScriptError(int line_number, const base::string16& error) override {
158 NetworkDelegate::AuthRequiredResponse OnAuthRequired(
159 URLRequest* request,
160 const AuthChallengeInfo& auth_info,
161 const AuthCallback& callback,
162 AuthCredentials* credentials) override {
163 return NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION;
166 bool OnCanGetCookies(const URLRequest& request,
167 const CookieList& cookie_list) override {
168 return true;
171 bool OnCanSetCookie(const URLRequest& request,
172 const std::string& cookie_line,
173 CookieOptions* options) override {
174 return true;
177 bool OnCanAccessFile(const URLRequest& request,
178 const base::FilePath& path) const override {
179 return true;
182 DISALLOW_COPY_AND_ASSIGN(BasicNetworkDelegate);
185 class ProxyScriptFetcherImplTest : public PlatformTest {
186 public:
187 ProxyScriptFetcherImplTest()
188 : test_server_(SpawnedTestServer::TYPE_HTTP,
189 SpawnedTestServer::kLocalhost,
190 base::FilePath(kDocRoot)) {
191 context_.set_network_delegate(&network_delegate_);
194 protected:
195 SpawnedTestServer test_server_;
196 BasicNetworkDelegate network_delegate_;
197 RequestContext context_;
200 #if !defined(DISABLE_FILE_SUPPORT)
201 TEST_F(ProxyScriptFetcherImplTest, FileUrl) {
202 ProxyScriptFetcherImpl pac_fetcher(&context_);
204 { // Fetch a non-existent file.
205 base::string16 text;
206 TestCompletionCallback callback;
207 int result = pac_fetcher.Fetch(GetTestFileUrl("does-not-exist"),
208 &text, callback.callback());
209 EXPECT_EQ(ERR_IO_PENDING, result);
210 EXPECT_EQ(ERR_FILE_NOT_FOUND, callback.WaitForResult());
211 EXPECT_TRUE(text.empty());
213 { // Fetch a file that exists.
214 base::string16 text;
215 TestCompletionCallback callback;
216 int result = pac_fetcher.Fetch(GetTestFileUrl("pac.txt"),
217 &text, callback.callback());
218 EXPECT_EQ(ERR_IO_PENDING, result);
219 EXPECT_EQ(OK, callback.WaitForResult());
220 EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text);
223 #endif // !defined(DISABLE_FILE_SUPPORT)
225 // Note that all mime types are allowed for PAC file, to be consistent
226 // with other browsers.
227 TEST_F(ProxyScriptFetcherImplTest, HttpMimeType) {
228 ASSERT_TRUE(test_server_.Start());
230 ProxyScriptFetcherImpl pac_fetcher(&context_);
232 { // Fetch a PAC with mime type "text/plain"
233 GURL url(test_server_.GetURL("files/pac.txt"));
234 base::string16 text;
235 TestCompletionCallback callback;
236 int result = pac_fetcher.Fetch(url, &text, callback.callback());
237 EXPECT_EQ(ERR_IO_PENDING, result);
238 EXPECT_EQ(OK, callback.WaitForResult());
239 EXPECT_EQ(ASCIIToUTF16("-pac.txt-\n"), text);
241 { // Fetch a PAC with mime type "text/html"
242 GURL url(test_server_.GetURL("files/pac.html"));
243 base::string16 text;
244 TestCompletionCallback callback;
245 int result = pac_fetcher.Fetch(url, &text, callback.callback());
246 EXPECT_EQ(ERR_IO_PENDING, result);
247 EXPECT_EQ(OK, callback.WaitForResult());
248 EXPECT_EQ(ASCIIToUTF16("-pac.html-\n"), text);
250 { // Fetch a PAC with mime type "application/x-ns-proxy-autoconfig"
251 GURL url(test_server_.GetURL("files/pac.nsproxy"));
252 base::string16 text;
253 TestCompletionCallback callback;
254 int result = pac_fetcher.Fetch(url, &text, callback.callback());
255 EXPECT_EQ(ERR_IO_PENDING, result);
256 EXPECT_EQ(OK, callback.WaitForResult());
257 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
261 TEST_F(ProxyScriptFetcherImplTest, HttpStatusCode) {
262 ASSERT_TRUE(test_server_.Start());
264 ProxyScriptFetcherImpl pac_fetcher(&context_);
266 { // Fetch a PAC which gives a 500 -- FAIL
267 GURL url(test_server_.GetURL("files/500.pac"));
268 base::string16 text;
269 TestCompletionCallback callback;
270 int result = pac_fetcher.Fetch(url, &text, callback.callback());
271 EXPECT_EQ(ERR_IO_PENDING, result);
272 EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
273 EXPECT_TRUE(text.empty());
275 { // Fetch a PAC which gives a 404 -- FAIL
276 GURL url(test_server_.GetURL("files/404.pac"));
277 base::string16 text;
278 TestCompletionCallback callback;
279 int result = pac_fetcher.Fetch(url, &text, callback.callback());
280 EXPECT_EQ(ERR_IO_PENDING, result);
281 EXPECT_EQ(ERR_PAC_STATUS_NOT_OK, callback.WaitForResult());
282 EXPECT_TRUE(text.empty());
286 TEST_F(ProxyScriptFetcherImplTest, ContentDisposition) {
287 ASSERT_TRUE(test_server_.Start());
289 ProxyScriptFetcherImpl pac_fetcher(&context_);
291 // Fetch PAC scripts via HTTP with a Content-Disposition header -- should
292 // have no effect.
293 GURL url(test_server_.GetURL("files/downloadable.pac"));
294 base::string16 text;
295 TestCompletionCallback callback;
296 int result = pac_fetcher.Fetch(url, &text, callback.callback());
297 EXPECT_EQ(ERR_IO_PENDING, result);
298 EXPECT_EQ(OK, callback.WaitForResult());
299 EXPECT_EQ(ASCIIToUTF16("-downloadable.pac-\n"), text);
302 // Verifies that PAC scripts are not being cached.
303 TEST_F(ProxyScriptFetcherImplTest, NoCache) {
304 ASSERT_TRUE(test_server_.Start());
306 ProxyScriptFetcherImpl pac_fetcher(&context_);
308 // Fetch a PAC script whose HTTP headers make it cacheable for 1 hour.
309 GURL url(test_server_.GetURL("files/cacheable_1hr.pac"));
311 base::string16 text;
312 TestCompletionCallback callback;
313 int result = pac_fetcher.Fetch(url, &text, callback.callback());
314 EXPECT_EQ(ERR_IO_PENDING, result);
315 EXPECT_EQ(OK, callback.WaitForResult());
316 EXPECT_EQ(ASCIIToUTF16("-cacheable_1hr.pac-\n"), text);
319 // Kill the HTTP server.
320 ASSERT_TRUE(test_server_.Stop());
322 // Try to fetch the file again. Since the server is not running anymore, the
323 // call should fail, thus indicating that the file was not fetched from the
324 // local cache.
326 base::string16 text;
327 TestCompletionCallback callback;
328 int result = pac_fetcher.Fetch(url, &text, callback.callback());
329 EXPECT_EQ(ERR_IO_PENDING, result);
331 // Expect any error. The exact error varies by platform.
332 EXPECT_NE(OK, callback.WaitForResult());
336 TEST_F(ProxyScriptFetcherImplTest, TooLarge) {
337 ASSERT_TRUE(test_server_.Start());
339 ProxyScriptFetcherImpl pac_fetcher(&context_);
341 // Set the maximum response size to 50 bytes.
342 int prev_size = pac_fetcher.SetSizeConstraint(50);
344 // These two URLs are the same file, but are http:// vs file://
345 GURL urls[] = {
346 test_server_.GetURL("files/large-pac.nsproxy"),
347 #if !defined(DISABLE_FILE_SUPPORT)
348 GetTestFileUrl("large-pac.nsproxy")
349 #endif
352 // Try fetching URLs that are 101 bytes large. We should abort the request
353 // after 50 bytes have been read, and fail with a too large error.
354 for (size_t i = 0; i < arraysize(urls); ++i) {
355 const GURL& url = urls[i];
356 base::string16 text;
357 TestCompletionCallback callback;
358 int result = pac_fetcher.Fetch(url, &text, callback.callback());
359 EXPECT_EQ(ERR_IO_PENDING, result);
360 EXPECT_EQ(ERR_FILE_TOO_BIG, callback.WaitForResult());
361 EXPECT_TRUE(text.empty());
364 // Restore the original size bound.
365 pac_fetcher.SetSizeConstraint(prev_size);
367 { // Make sure we can still fetch regular URLs.
368 GURL url(test_server_.GetURL("files/pac.nsproxy"));
369 base::string16 text;
370 TestCompletionCallback callback;
371 int result = pac_fetcher.Fetch(url, &text, callback.callback());
372 EXPECT_EQ(ERR_IO_PENDING, result);
373 EXPECT_EQ(OK, callback.WaitForResult());
374 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
378 TEST_F(ProxyScriptFetcherImplTest, Hang) {
379 ASSERT_TRUE(test_server_.Start());
381 ProxyScriptFetcherImpl pac_fetcher(&context_);
383 // Set the timeout period to 0.5 seconds.
384 base::TimeDelta prev_timeout = pac_fetcher.SetTimeoutConstraint(
385 base::TimeDelta::FromMilliseconds(500));
387 // Try fetching a URL which takes 1.2 seconds. We should abort the request
388 // after 500 ms, and fail with a timeout error.
390 GURL url(test_server_.GetURL("slow/proxy.pac?1.2"));
391 base::string16 text;
392 TestCompletionCallback callback;
393 int result = pac_fetcher.Fetch(url, &text, callback.callback());
394 EXPECT_EQ(ERR_IO_PENDING, result);
395 EXPECT_EQ(ERR_TIMED_OUT, callback.WaitForResult());
396 EXPECT_TRUE(text.empty());
399 // Restore the original timeout period.
400 pac_fetcher.SetTimeoutConstraint(prev_timeout);
402 { // Make sure we can still fetch regular URLs.
403 GURL url(test_server_.GetURL("files/pac.nsproxy"));
404 base::string16 text;
405 TestCompletionCallback callback;
406 int result = pac_fetcher.Fetch(url, &text, callback.callback());
407 EXPECT_EQ(ERR_IO_PENDING, result);
408 EXPECT_EQ(OK, callback.WaitForResult());
409 EXPECT_EQ(ASCIIToUTF16("-pac.nsproxy-\n"), text);
413 // The ProxyScriptFetcher should decode any content-codings
414 // (like gzip, bzip, etc.), and apply any charset conversions to yield
415 // UTF8.
416 TEST_F(ProxyScriptFetcherImplTest, Encodings) {
417 ASSERT_TRUE(test_server_.Start());
419 ProxyScriptFetcherImpl pac_fetcher(&context_);
421 // Test a response that is gzip-encoded -- should get inflated.
423 GURL url(test_server_.GetURL("files/gzipped_pac"));
424 base::string16 text;
425 TestCompletionCallback callback;
426 int result = pac_fetcher.Fetch(url, &text, callback.callback());
427 EXPECT_EQ(ERR_IO_PENDING, result);
428 EXPECT_EQ(OK, callback.WaitForResult());
429 EXPECT_EQ(ASCIIToUTF16("This data was gzipped.\n"), text);
432 // Test a response that was served as UTF-16 (BE). It should
433 // be converted to UTF8.
435 GURL url(test_server_.GetURL("files/utf16be_pac"));
436 base::string16 text;
437 TestCompletionCallback callback;
438 int result = pac_fetcher.Fetch(url, &text, callback.callback());
439 EXPECT_EQ(ERR_IO_PENDING, result);
440 EXPECT_EQ(OK, callback.WaitForResult());
441 EXPECT_EQ(ASCIIToUTF16("This was encoded as UTF-16BE.\n"), text);
445 TEST_F(ProxyScriptFetcherImplTest, DataURLs) {
446 ProxyScriptFetcherImpl pac_fetcher(&context_);
448 const char kEncodedUrl[] =
449 "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R"
450 "m9yVVJMKHVybCwgaG9zdCkgewogIGlmIChob3N0ID09ICdmb29iYXIuY29tJykKICAgIHJl"
451 "dHVybiAnUFJPWFkgYmxhY2tob2xlOjgwJzsKICByZXR1cm4gJ0RJUkVDVCc7Cn0=";
452 const char kPacScript[] =
453 "function FindProxyForURL(url, host) {\n"
454 " if (host == 'foobar.com')\n"
455 " return 'PROXY blackhole:80';\n"
456 " return 'DIRECT';\n"
457 "}";
459 // Test fetching a "data:"-url containing a base64 encoded PAC script.
461 GURL url(kEncodedUrl);
462 base::string16 text;
463 TestCompletionCallback callback;
464 int result = pac_fetcher.Fetch(url, &text, callback.callback());
465 EXPECT_EQ(OK, result);
466 EXPECT_EQ(ASCIIToUTF16(kPacScript), text);
469 const char kEncodedUrlBroken[] =
470 "data:application/x-ns-proxy-autoconfig;base64,ZnVuY3Rpb24gRmluZFByb3h5R";
472 // Test a broken "data:"-url containing a base64 encoded PAC script.
474 GURL url(kEncodedUrlBroken);
475 base::string16 text;
476 TestCompletionCallback callback;
477 int result = pac_fetcher.Fetch(url, &text, callback.callback());
478 EXPECT_EQ(ERR_FAILED, result);
482 } // namespace
484 } // namespace net