policy_browsertest.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
12a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Copyright (c) 2012 The Chromium Authors. All rights reserved.
22a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Use of this source code is governed by a BSD-style license that can be
32a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// found in the LICENSE file.
42a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
52a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <algorithm>
62a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <string>
72a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include <vector>
82a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
92a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "base/bind.h"
101320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tucci#include "base/bind_helpers.h"
112a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "base/command_line.h"
12f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "base/file_path.h"
13cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "base/file_util.h"
142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "base/memory/ref_counted.h"
15c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "base/path_service.h"
16c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)#include "base/scoped_temp_dir.h"
17f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "base/string16.h"
18f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "base/stringprintf.h"
192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "base/test/test_file_util.h"
207dbb3d5cf0c15f500944d211057644d6a2f37371Ben Murdoch#include "base/utf_string_conversions.h"
21f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "base/values.h"
2268043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)#include "chrome/app/chrome_command_ids.h"
23f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "chrome/browser/autocomplete/autocomplete_controller.h"
24f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "chrome/browser/browser_process.h"
252a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/debugger/devtools_window.h"
26a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "chrome/browser/download/download_prefs.h"
275d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "chrome/browser/extensions/crx_installer.h"
2823730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)#include "chrome/browser/extensions/extension_service.h"
29cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "chrome/browser/extensions/extension_system.h"
305d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "chrome/browser/infobars/infobar_tab_helper.h"
31a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "chrome/browser/net/url_request_mock_util.h"
32a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "chrome/browser/plugins/plugin_prefs.h"
3368043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)#include "chrome/browser/policy/browser_policy_connector.h"
34f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "chrome/browser/policy/mock_configuration_policy_provider.h"
355d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)#include "chrome/browser/policy/policy_map.h"
363551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)#include "chrome/browser/prefs/pref_service.h"
373551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)#include "chrome/browser/prefs/session_startup_pref.h"
38f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "chrome/browser/profiles/profile.h"
392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/search_engines/template_url.h"
40a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "chrome/browser/search_engines/template_url_service.h"
412a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/search_engines/template_url_service_factory.h"
422a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/translate/translate_infobar_delegate.h"
432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/ui/bookmarks/bookmark_bar.h"
44cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "chrome/browser/ui/browser.h"
452a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/ui/browser_commands.h"
46a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "chrome/browser/ui/browser_list.h"
473551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)#include "chrome/browser/ui/browser_tabstrip.h"
4890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/browser/ui/browser_window.h"
4990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/browser/ui/omnibox/location_bar.h"
5090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
5190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/browser/ui/omnibox/omnibox_view.h"
5290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/browser/ui/search/search.h"
53a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/browser/ui/tab_contents/tab_contents.h"
54a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/browser/ui/tabs/tab_strip_model.h"
55a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/common/chrome_notification_types.h"
56a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/common/chrome_switches.h"
57a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/common/content_settings.h"
58a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/common/extensions/extension.h"
59a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)#include "chrome/common/extensions/extension_constants.h"
6090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/common/pref_names.h"
6190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "chrome/common/url_constants.h"
622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/test/base/in_process_browser_test.h"
63f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "chrome/test/base/ui_test_utils.h"
642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/browser_child_process_host_iterator.h"
652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/browser_context.h"
662a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/browser_thread.h"
672a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/child_process_data.h"
68cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/browser/download_item.h"
692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/download_manager.h"
702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/notification_service.h"
712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/notification_source.h"
722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/notification_types.h"
732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "content/public/browser/plugin_service.h"
74cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/browser/render_view_host.h"
75cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/browser/web_contents.h"
76cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/common/content_paths.h"
77cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/common/page_transition_types.h"
78cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/common/process_type.h"
79cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/common/url_constants.h"
80cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/public/test/browser_test_utils.h"
815f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "content/public/test/download_test_observer.h"
825f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "content/public/test/test_navigation_observer.h"
835f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "content/public/test/test_utils.h"
845f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)#include "content/test/net/url_request_failed_job.h"
85cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#include "content/test/net/url_request_mock_http_job.h"
8623730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)#include "googleurl/src/gurl.h"
87a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "grit/generated_resources.h"
88a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "net/base/net_errors.h"
89a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "net/base/net_util.h"
90a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "net/http/http_stream_factory.h"
91a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "net/url_request/url_request.h"
92f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "net/url_request/url_request_filter.h"
93f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "policy/policy_constants.h"
94f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "testing/gmock/include/gmock/gmock.h"
95f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "testing/gtest/include/gtest/gtest.h"
96a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "ui/base/l10n/l10n_util.h"
97a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)#include "ui/base/resource/resource_bundle.h"
98f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "webkit/plugins/npapi/plugin_utils.h"
9990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "webkit/plugins/plugin_constants.h"
1002a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "webkit/plugins/webplugininfo.h"
101cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
102cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)#if defined(OS_CHROMEOS)
103f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#include "ash/accelerators/accelerator_controller.h"
10490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)#include "ash/accelerators/accelerator_table.h"
1052a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "ash/shell.h"
1062a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "ash/shell_delegate.h"
1072a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#include "chrome/browser/chromeos/audio/audio_handler.h"
1082a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#endif
1092a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
1102a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)using content::BrowserThread;
111cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)using content::URLRequestMockHTTPJob;
1126d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)using testing::Return;
1136d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)
11490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)namespace policy {
115cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
116a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)namespace {
117a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
118a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)const char kURL[] = "http://example.com";
119a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)const char kCookieValue[] = "converted=true";
120a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)// Assigned to Philip J. Fry to fix eventually.
1212a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
1222a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
123cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)const FilePath::CharType kTestExtensionsDir[] = FILE_PATH_LITERAL("extensions");
124cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)const FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
125cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)const FilePath::CharType kAdBlockCrxName[] = FILE_PATH_LITERAL("adblock.crx");
126cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
127cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
128cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
12923730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)
130f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)const FilePath::CharType kGoodCrxManifestName[] =
131f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    FILE_PATH_LITERAL("good_update_manifest.xml");
132f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
13390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)const char* kURLs[] = {
1342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  chrome::kChromeUINewTabURL,
135cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  chrome::kChromeUIAboutURL,
136cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  chrome::kChromeUICreditsURL,
137cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  chrome::kChromeUIPolicyURL,
138cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  chrome::kChromeUIVersionURL,
1392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)};
140cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)
141cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)// Filters requests to the hosts in |urls| and redirects them to the test data
1425f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)// dir through URLRequestMockHTTPJobs.
1435f1c94371a64b3196d4be9466099bb892df9b88eTorne (Richard Coles)void RedirectHostsToTestDataOnIOThread(const GURL* const urls[], size_t size) {
144cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  // Map the given hosts to the test data dir.
145cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
146cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)  for (size_t i = 0; i < size; ++i) {
147cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    const GURL* url = urls[i];
148cedac228d2dd51db4b79ea1e72c7f249408ee061Torne (Richard Coles)    EXPECT_TRUE(url->is_valid());
149f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    filter->AddHostnameHandler(url->scheme(), url->host(),
150a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                               URLRequestMockHTTPJob::Factory);
151f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
152a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)}
153a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)
15423730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)// Fails requests using ERR_CONNECTION_RESET.
15523730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)net::URLRequestJob* FailedJobFactory(
156a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    net::URLRequest* request,
15790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)    net::NetworkDelegate* network_delegate,
158a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    const std::string& scheme) {
159a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  return new content::URLRequestFailedJob(
160a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      request, network_delegate, net::ERR_CONNECTION_RESET);
161f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
162f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
163f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// Filters requests to the |host| such that they fail. Run on IO thread.
1641320f92c476a1ad9d19dba2a48c72b75566198e9Primiano Tuccivoid MakeRequestFailOnIO(const std::string& host) {
165f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
166f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  filter->AddHostnameHandler("http", host, &FailedJobFactory);
167f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  filter->AddHostnameHandler("https", host, &FailedJobFactory);
168f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
16990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
17090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// Sets up the filter on IO thread such that requests to |host| fail.
17190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)void MakeRequestFail(const std::string& host) {
17290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  BrowserThread::PostTaskAndReply(
17390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      BrowserThread::IO, FROM_HERE,
174a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)      base::Bind(MakeRequestFailOnIO, host),
175f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      MessageLoop::QuitClosure());
17690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  content::RunMessageLoop();
17790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)}
17890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
179f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// Verifies that the given |url| can be opened. This assumes that |url| points
180f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)// at empty.html in the test data dir.
181f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)void CheckCanOpenURL(Browser* browser, const GURL& url) {
182f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  ui_test_utils::NavigateToURL(browser, url);
183f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  content::WebContents* contents = chrome::GetActiveWebContents(browser);
184a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  EXPECT_EQ(url, contents->GetURL());
185a3f6a49ab37290eeeb8db0f41ec0f1cb74a68be7Torne (Richard Coles)  EXPECT_EQ(net::FormatUrl(url, std::string()), contents->GetTitle());
186f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
187f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
18890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)// Verifies that access to the given |url| is blocked.
189a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)void CheckURLIsBlocked(Browser* browser, const GURL& url) {
19090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  ui_test_utils::NavigateToURL(browser, url);
19190dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  content::WebContents* contents = chrome::GetActiveWebContents(browser);
192a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  EXPECT_EQ(url, contents->GetURL());
193f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  string16 title = UTF8ToUTF16(url.spec() + " is not available");
19490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  EXPECT_EQ(title, contents->GetTitle());
19590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)
19690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // Verify that the expected error page is being displayed.
19790dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  // (error 138 == NETWORK_ACCESS_DENIED)
19890dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  bool result = false;
1993551c9c881056c480085172ff9840cab31610854Torne (Richard Coles)  EXPECT_TRUE(content::ExecuteJavaScriptAndExtractBool(
2005d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      contents->GetRenderViewHost(),
2015d1f7b1de12d16ceb2c938c56701a3e8bfa558f7Torne (Richard Coles)      std::wstring(),
20290dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      L"var hasError = false;"
20390dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      L"var error = document.getElementById('errorDetails');"
20490dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      L"if (error)"
20590dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      L"  hasError = error.textContent.indexOf('Error 138') == 0;"
20690dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      L"domAutomationController.send(hasError);",
207f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      &result));
2087d4cd473f85ac64c3747c96c277f9e506a0d2246Torne (Richard Coles)  EXPECT_TRUE(result);
2096e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)}
2106e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)
2116e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)// Downloads a file named |file| and expects it to be saved to |dir|, which
2126e8cce623b6e4fe0c9e4af605d675dd9d0338c38Torne (Richard Coles)// must be empty.
213f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)void DownloadAndVerifyFile(
2142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    Browser* browser, const FilePath& dir, const FilePath& file) {
2152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::DownloadManager* download_manager =
216f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      content::BrowserContext::GetDownloadManager(browser->profile());
217f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  content::DownloadTestObserverTerminal observer(
218f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      download_manager, 1,
21990dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)      content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
22090dce4d38c5ff5333bea97d859d4e484e27edf0cTorne (Richard Coles)  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
221f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  FilePath downloaded = dir.Append(file);
222f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  EXPECT_FALSE(file_util::PathExists(downloaded));
223effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch  ui_test_utils::NavigateToURLWithDisposition(
224f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      browser, url, CURRENT_TAB,
225f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
226f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  observer.WaitForFinished();
22723730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  EXPECT_EQ(
22823730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)      1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
22923730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  EXPECT_TRUE(file_util::PathExists(downloaded));
23023730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)  file_util::FileEnumerator enumerator(
23123730a6e56a168d1879203e4b3819bb36e3d8f1fTorne (Richard Coles)      dir, false, file_util::FileEnumerator::FILES);
232f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  EXPECT_EQ(file, enumerator.Next().BaseName());
233f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  EXPECT_EQ(FilePath(), enumerator.Next());
2342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#if defined(OS_CHROMEOS)
237a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)int CountScreenshots() {
2382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
2392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      ash::Shell::GetInstance()->delegate()->GetCurrentBrowserContext());
240a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)  file_util::FileEnumerator enumerator(download_prefs->DownloadPath(),
241f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                                       false, file_util::FileEnumerator::FILES,
242a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)                                       "Screenshot*");
2432a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  int count = 0;
2442a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  while (!enumerator.Next().empty())
245a1401311d1ab56c4ed0a474bd38c108f75cb0cd9Torne (Richard Coles)    count++;
24668043e1e95eeb07d5cae7aca370b26518b0867d6Torne (Richard Coles)  return count;
247effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch}
2482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#endif
249f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
2502a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Checks if WebGL is enabled in the given WebContents.
2512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)bool IsWebGLEnabled(content::WebContents* contents) {
252f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  bool result = false;
253f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  EXPECT_TRUE(content::ExecuteJavaScriptAndExtractBool(
254f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      contents->GetRenderViewHost(),
255f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      std::wstring(),
256f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      L"var canvas = document.createElement('canvas');"
2572a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      L"var context = canvas.getContext('experimental-webgl');"
2582a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      L"domAutomationController.send(context != null);",
2592a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      &result));
260effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch  return result;
2612a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2622a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
2632a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)bool IsJavascriptEnabled(content::WebContents* contents) {
2642a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::RenderViewHost* rvh = contents->GetRenderViewHost();
2652a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  scoped_ptr<base::Value> value(rvh->ExecuteJavascriptAndGetValue(
266effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch      string16(),
267f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      ASCIIToUTF16("123")));
2682a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  int result = 0;
2692a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  if (!value->GetAsInteger(&result))
2702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)    EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
2712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return result == 123;
2722a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2732a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
274effb81e5f8246d0db0270817048dc992db66e9fbBen Murdochvoid CopyPluginListAndQuit(std::vector<webkit::WebPluginInfo>* out,
275f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                           const std::vector<webkit::WebPluginInfo>& in) {
2762a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  *out = in;
2772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  MessageLoop::current()->QuitWhenIdle();
2782a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
2792a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
280effb81e5f8246d0db0270817048dc992db66e9fbBen Murdochtemplate<typename T>
281f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)void CopyValueAndQuit(T* out, T in) {
282f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  *out = in;
283f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  MessageLoop::current()->QuitWhenIdle();
284f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
285f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
286f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)void GetPluginList(std::vector<webkit::WebPluginInfo>* plugins) {
287f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  content::PluginService* service = content::PluginService::GetInstance();
288f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
289f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  content::RunMessageLoop();
290f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
291f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
292effb81e5f8246d0db0270817048dc992db66e9fbBen Murdochconst webkit::WebPluginInfo* GetFlashPlugin(
293f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    const std::vector<webkit::WebPluginInfo>& plugins) {
294f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  const webkit::WebPluginInfo* flash = NULL;
295f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  for (size_t i = 0; i < plugins.size(); ++i) {
296f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    if (plugins[i].name == ASCIIToUTF16(kFlashPluginName)) {
297f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      flash = &plugins[i];
298f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      break;
299f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    }
3006d86b77056ed63eb6871182f42a9fd5f07550f90Torne (Richard Coles)  }
301f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#if defined(OFFICIAL_BUILD)
302f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  // Official builds bundle Flash.
303f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  EXPECT_TRUE(flash);
304f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#else
305f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  if (!flash)
306f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
307f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#endif
308f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  return flash;
309f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}
310f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
311f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)bool SetPluginEnabled(PluginPrefs* plugin_prefs,
312f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                      const webkit::WebPluginInfo* plugin,
313f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)                      bool enabled) {
3142a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  bool ok = false;
3152a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  plugin_prefs->EnablePlugin(enabled, plugin->path,
3162a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)                             base::Bind(CopyValueAndQuit<bool>, &ok));
3172a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::RunMessageLoop();
3182a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return ok;
3192a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
320effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch
321f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)int CountPluginsOnIOThread() {
322f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  int count = 0;
323f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
324f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    if (iter.GetData().type == content::PROCESS_TYPE_PLUGIN ||
325f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)        iter.GetData().type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
326f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)      count++;
327f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    }
328f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  }
329f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  return count;
3302a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
3312a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)
3322a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)int CountPlugins() {
3332a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  int count = -1;
3342a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  BrowserThread::PostTaskAndReplyWithResult(
3352a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      BrowserThread::IO, FROM_HERE,
3362a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      base::Bind(CountPluginsOnIOThread),
3372a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)      base::Bind(CopyValueAndQuit<int>, &count));
3382a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::RunMessageLoop();
3392a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  EXPECT_GE(count, 0);
3402a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  return count;
341effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch}
342f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
343f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)void FlushBlacklistPolicy() {
344f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  // Updates of the URLBlacklist are done on IO, after building the blacklist
345f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  // on FILE, which is initiated from IO.
346f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  content::RunAllPendingInMessageLoop(BrowserThread::IO);
3472a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::RunAllPendingInMessageLoop(BrowserThread::FILE);
3482a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  content::RunAllPendingInMessageLoop(BrowserThread::IO);
3492a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)}
350f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
3512a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)#if defined(OS_CHROMEOS)
3522a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)// Volume observer mock used by the audio policy tests.
3532a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)class TestVolumeObserver : public chromeos::AudioHandler::VolumeObserver {
3542a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles) public:
355effb81e5f8246d0db0270817048dc992db66e9fbBen Murdoch  TestVolumeObserver() {}
3562a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  virtual ~TestVolumeObserver() {}
357f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
358f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  MOCK_METHOD0(OnVolumeChanged, void());
359f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  MOCK_METHOD0(OnMuteToggled, void());
360f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
361f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) private:
362f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  DISALLOW_COPY_AND_ASSIGN(TestVolumeObserver);
363f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)};
364f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)#endif
365f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
366f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)}  // namespace
367f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
368f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)class PolicyTest : public InProcessBrowserTest {
369f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles) protected:
3702a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  PolicyTest() {}
3712a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  virtual ~PolicyTest() {}
372f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)
373f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
374f2477e01787aa58f445919b809d89e252beef54fTorne (Richard Coles)    EXPECT_CALL(provider_, IsInitializationComplete())
375c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)        .WillRepeatedly(Return(true));
376c2e0dbddbe15c98d52c4786dac06cb8952a8ae6dTorne (Richard Coles)    BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
3772a99a7e74a7f215066514fe81d2bfa6639d9edddTorne (Richard Coles)  }
378
379  virtual void SetUpOnMainThread() OVERRIDE {
380    BrowserThread::PostTask(
381        BrowserThread::IO, FROM_HERE,
382        base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
383  }
384
385  // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
386  // instead of chrome::DIR_TEST_DATA.
387  void ServeContentTestData() {
388    FilePath root_http;
389    PathService::Get(content::DIR_TEST_DATA, &root_http);
390    BrowserThread::PostTaskAndReply(
391        BrowserThread::IO, FROM_HERE,
392        base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http),
393        MessageLoop::current()->QuitWhenIdleClosure());
394    content::RunMessageLoop();
395  }
396
397  void SetScreenshotPolicy(bool enabled) {
398    PolicyMap policies;
399    policies.Set(key::kDisableScreenshots, POLICY_LEVEL_MANDATORY,
400                 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(!enabled));
401    provider_.UpdateChromePolicy(policies);
402  }
403
404  void TestScreenshotFeedback(bool enabled) {
405    SetScreenshotPolicy(enabled);
406
407    // Wait for feedback page to load.
408    content::WindowedNotificationObserver observer(
409        content::NOTIFICATION_LOAD_STOP,
410        content::NotificationService::AllSources());
411    EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_FEEDBACK));
412    observer.Wait();
413    content::WebContents* web_contents =
414        static_cast<content::Source<content::NavigationController> >(
415            observer.source())->GetWebContents();
416
417    // Wait for feedback page to fully initialize.
418    // setupCurrentScreenshot is called when feedback page loads and (among
419    // other things) adds current-screenshots-thumbnailDiv-0-image element.
420    // The code below executes either before setupCurrentScreenshot was called
421    // (setupCurrentScreenshot is replaced with our hook) or after it has
422    // completed (in that case send result immediately).
423    bool result = false;
424    EXPECT_TRUE(content::ExecuteJavaScriptAndExtractBool(
425        web_contents->GetRenderViewHost(),
426        std::wstring(),
427        L"function btest_initCompleted(url) {"
428        L"  var img = new Image();"
429        L"  img.src = url;"
430        L"  img.onload = function() {"
431        L"    domAutomationController.send(img.width * img.height > 0);"
432        L"  };"
433        L"  img.onerror = function() {"
434        L"    domAutomationController.send(false);"
435        L"  };"
436        L"}"
437        L"function setupCurrentScreenshot(url) {"
438        L"  btest_initCompleted(url);"
439        L"}"
440        L"var img = document.getElementById("
441        L"    'current-screenshots-thumbnailDiv-0-image');"
442        L"if (img)"
443        L"  btest_initCompleted(img.src);",
444        &result));
445    EXPECT_EQ(enabled, result);
446
447    // Feedback page is a singleton page, so close so future calls to this
448    // function work as expected.
449    web_contents->Close();
450  }
451
452#if defined(OS_CHROMEOS)
453  void TestScreenshotFile(bool enabled) {
454    SetScreenshotPolicy(enabled);
455    ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
456        ash::TAKE_SCREENSHOT, ui::Accelerator());
457
458    // TAKE_SCREENSHOT handler posts write file task on success, wait for it.
459    BrowserThread::PostTaskAndReply(
460        BrowserThread::IO,
461        FROM_HERE,
462        base::Bind(base::DoNothing),
463        MessageLoop::QuitClosure());
464    content::RunMessageLoop();
465  }
466#endif
467
468  ExtensionService* extension_service() {
469    extensions::ExtensionSystem* system =
470        extensions::ExtensionSystem::Get(browser()->profile());
471    return system->extension_service();
472  }
473
474  const extensions::Extension* InstallExtension(
475      const FilePath::StringType& name) {
476    FilePath extension_path(ui_test_utils::GetTestFilePath(
477        FilePath(kTestExtensionsDir), FilePath(name)));
478    scoped_refptr<extensions::CrxInstaller> installer =
479        extensions::CrxInstaller::Create(extension_service(), NULL);
480    installer->set_allow_silent_install(true);
481    installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
482    installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
483
484    content::WindowedNotificationObserver observer(
485        chrome::NOTIFICATION_CRX_INSTALLER_DONE,
486        content::NotificationService::AllSources());
487    installer->InstallCrx(extension_path);
488    observer.Wait();
489    content::Details<const extensions::Extension> details = observer.details();
490    return details.ptr();
491  }
492
493  void UninstallExtension(const std::string& id, bool expect_success) {
494    content::WindowedNotificationObserver observer(
495        expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED
496                       : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
497        content::NotificationService::AllSources());
498    extension_service()->UninstallExtension(id, false, NULL);
499    observer.Wait();
500  }
501
502  MockConfigurationPolicyProvider provider_;
503};
504
505#if defined(OS_WIN)
506// This policy only exists on Windows.
507
508// Sets the locale policy before the browser is started.
509class LocalePolicyTest : public PolicyTest {
510 public:
511  LocalePolicyTest() {}
512  virtual ~LocalePolicyTest() {}
513
514  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
515    PolicyTest::SetUpInProcessBrowserTestFixture();
516    PolicyMap policies;
517    policies.Set(
518        key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
519        base::Value::CreateStringValue("fr"));
520    provider_.UpdateChromePolicy(policies);
521    // The "en-US" ResourceBundle is always loaded before this step for tests,
522    // but in this test we want the browser to load the bundle as it
523    // normally would.
524    ResourceBundle::CleanupSharedInstance();
525  }
526};
527
528IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
529  // Verifies that the default locale can be overridden with policy.
530  EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
531  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
532  string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
533  string16 title;
534  EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
535  EXPECT_EQ(french_title, title);
536
537  // Make sure this is really French and differs from the English title.
538  std::string loaded =
539      ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
540  EXPECT_EQ("en-US", loaded);
541  string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
542  EXPECT_NE(french_title, english_title);
543}
544#endif
545
546IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
547  // Verifies that the bookmarks bar can be forced to always or never show up.
548
549  // Test starts in about:blank.
550  PrefService* prefs = browser()->profile()->GetPrefs();
551  EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
552  EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
553  EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
554
555  PolicyMap policies;
556  policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
557               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
558  provider_.UpdateChromePolicy(policies);
559  EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
560  EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar));
561  EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
562
563  // The NTP has special handling of the bookmark bar.
564  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
565  EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
566
567  policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
568               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
569  provider_.UpdateChromePolicy(policies);
570  EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
571  EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
572  // The bookmark bar is hidden in the NTP when disabled by policy.
573  EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
574
575  policies.Clear();
576  provider_.UpdateChromePolicy(policies);
577  EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
578  EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
579  // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
580  EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
581}
582
583IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_ClearSiteDataOnExit) {
584  // Verifies that cookies are deleted on shutdown. This test is split in 3
585  // parts because it spans 2 browser restarts.
586
587  Profile* profile = browser()->profile();
588  GURL url(kURL);
589  // No cookies at startup.
590  EXPECT_TRUE(content::GetCookies(profile, url).empty());
591  // Set a cookie now.
592  std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
593  EXPECT_TRUE(content::SetCookie(profile, url, value));
594  // Verify it was set.
595  EXPECT_EQ(kCookieValue, GetCookies(profile, url));
596}
597
598IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_ClearSiteDataOnExit) {
599  // Verify that the cookie persists across restarts.
600  EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
601  // Now set the policy and the cookie should be gone after another restart.
602  PolicyMap policies;
603  policies.Set(key::kClearSiteDataOnExit, POLICY_LEVEL_MANDATORY,
604               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
605  provider_.UpdateChromePolicy(policies);
606}
607
608IN_PROC_BROWSER_TEST_F(PolicyTest, ClearSiteDataOnExit) {
609  // Verify that the cookie is gone.
610  EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
611}
612
613IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
614  MakeRequestFail("search.example");
615
616  // Verifies that a default search is made using the provider configured via
617  // policy. Also checks that default search can be completely disabled.
618  const string16 kKeyword(ASCIIToUTF16("testsearch"));
619  const std::string kSearchURL("http://search.example/search?q={searchTerms}");
620  const std::string kAlternateURL0(
621      "http://search.example/search#q={searchTerms}");
622  const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
623
624  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
625      browser()->profile());
626  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
627  TemplateURL* default_search = service->GetDefaultSearchProvider();
628  ASSERT_TRUE(default_search);
629  EXPECT_NE(kKeyword, default_search->keyword());
630  EXPECT_NE(kSearchURL, default_search->url());
631  EXPECT_FALSE(
632    default_search->alternate_urls().size() == 2 &&
633    default_search->alternate_urls()[0] == kAlternateURL0 &&
634    default_search->alternate_urls()[1] == kAlternateURL1);
635
636  // Override the default search provider using policies.
637  PolicyMap policies;
638  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
639               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
640  policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY,
641               POLICY_SCOPE_USER, base::Value::CreateStringValue(kKeyword));
642  policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY,
643               POLICY_SCOPE_USER, base::Value::CreateStringValue(kSearchURL));
644  base::ListValue* alternate_urls = new base::ListValue();
645  alternate_urls->AppendString(kAlternateURL0);
646  alternate_urls->AppendString(kAlternateURL1);
647  policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
648               POLICY_SCOPE_USER, alternate_urls);
649  provider_.UpdateChromePolicy(policies);
650  default_search = service->GetDefaultSearchProvider();
651  ASSERT_TRUE(default_search);
652  EXPECT_EQ(kKeyword, default_search->keyword());
653  EXPECT_EQ(kSearchURL, default_search->url());
654  EXPECT_EQ(2U, default_search->alternate_urls().size());
655  EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
656  EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
657
658  // Verify that searching from the omnibox uses kSearchURL.
659  chrome::FocusLocationBar(browser());
660  LocationBar* location_bar = browser()->window()->GetLocationBar();
661  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
662  OmniboxEditModel* model = location_bar->GetLocationEntry()->model();
663  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
664  content::WebContents* web_contents = chrome::GetActiveWebContents(browser());
665  GURL expected("http://search.example/search?q=stuff+to+search+for");
666  EXPECT_EQ(expected, web_contents->GetURL());
667
668  // Verify that searching from the omnibox can be disabled.
669  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
670  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
671               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
672  EXPECT_TRUE(service->GetDefaultSearchProvider());
673  provider_.UpdateChromePolicy(policies);
674  EXPECT_FALSE(service->GetDefaultSearchProvider());
675  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
676  // This means that submitting won't trigger any action.
677  EXPECT_FALSE(model->CurrentMatch().destination_url.is_valid());
678  EXPECT_EQ(GURL(chrome::kAboutBlankURL), web_contents->GetURL());
679}
680
681IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
682  // Makes the requests fail since all we want to check is that the redirection
683  // is done properly.
684  MakeRequestFail("google.com");
685
686  // Verifies that requests to Google Search engine with the SafeSearch
687  // enabled set the safe=active&ssui=on parameters at the end of the query.
688  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
689      browser()->profile());
690  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
691
692  // First check that nothing happens.
693  content::TestNavigationObserver no_safesearch_observer(
694      content::NotificationService::AllSources());
695  chrome::FocusLocationBar(browser());
696  LocationBar* location_bar = browser()->window()->GetLocationBar();
697  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
698  OmniboxEditModel* model = location_bar->GetLocationEntry()->model();
699  no_safesearch_observer.Wait();
700  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
701  content::WebContents* web_contents = chrome::GetActiveWebContents(browser());
702  GURL expected_without("http://google.com/");
703  EXPECT_EQ(expected_without, web_contents->GetURL());
704
705  PrefService* prefs = browser()->profile()->GetPrefs();
706  EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
707  EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
708
709  // Override the default SafeSearch setting using policies.
710  PolicyMap policies;
711  policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
712               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
713  provider_.UpdateChromePolicy(policies);
714
715  EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
716  EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
717
718  content::TestNavigationObserver safesearch_observer(
719      content::NotificationService::AllSources());
720
721  // Verify that searching from google.com works.
722  chrome::FocusLocationBar(browser());
723  location_bar = browser()->window()->GetLocationBar();
724  ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
725  safesearch_observer.Wait();
726  model = location_bar->GetLocationEntry()->model();
727  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
728  web_contents = chrome::GetActiveWebContents(browser());
729  std::string expected_url("http://google.com/?");
730  expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
731                  chrome::kSafeSearchSsuiParameter;
732  GURL expected_with_parameters(expected_url);
733  EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
734}
735
736IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
737  MakeRequestFail("search.example");
738
739  CommandLine::ForCurrentProcess()->AppendSwitch(
740      switches::kEnableInstantExtendedAPI);
741
742  // Adding the kEnableInstantExtendedAPI is not enough since
743  // IsInstantExtendedAPIEnabled does not return true on CHANNEL_DEV.
744  if (!chrome::search::IsInstantExtendedAPIEnabled(browser()->profile()))
745    return;
746
747  // Verifies that a default search is made using the provider configured via
748  // policy. Also checks that default search can be completely disabled.
749  const string16 kKeyword(ASCIIToUTF16("testsearch"));
750  const std::string kSearchURL("https://search.example/search?q={searchTerms}");
751  const std::string kAlternateURL0(
752      "https://search.example/search#q={searchTerms}");
753  const std::string kAlternateURL1("https://search.example/#q={searchTerms}");
754
755  TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
756      browser()->profile());
757  ui_test_utils::WaitForTemplateURLServiceToLoad(service);
758  TemplateURL* default_search = service->GetDefaultSearchProvider();
759  ASSERT_TRUE(default_search);
760  EXPECT_NE(kKeyword, default_search->keyword());
761  EXPECT_NE(kSearchURL, default_search->url());
762  EXPECT_FALSE(
763    default_search->alternate_urls().size() == 2 &&
764    default_search->alternate_urls()[0] == kAlternateURL0 &&
765    default_search->alternate_urls()[1] == kAlternateURL1);
766
767  // Override the default search provider using policies.
768  PolicyMap policies;
769  policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
770               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
771  policies.Set(key::kDefaultSearchProviderKeyword, POLICY_LEVEL_MANDATORY,
772               POLICY_SCOPE_USER, base::Value::CreateStringValue(kKeyword));
773  policies.Set(key::kDefaultSearchProviderSearchURL, POLICY_LEVEL_MANDATORY,
774               POLICY_SCOPE_USER, base::Value::CreateStringValue(kSearchURL));
775  base::ListValue* alternate_urls = new base::ListValue();
776  alternate_urls->AppendString(kAlternateURL0);
777  alternate_urls->AppendString(kAlternateURL1);
778  policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
779               POLICY_SCOPE_USER, alternate_urls);
780  provider_.UpdateChromePolicy(policies);
781  default_search = service->GetDefaultSearchProvider();
782  ASSERT_TRUE(default_search);
783  EXPECT_EQ(kKeyword, default_search->keyword());
784  EXPECT_EQ(kSearchURL, default_search->url());
785  EXPECT_EQ(2U, default_search->alternate_urls().size());
786  EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
787  EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
788
789  // Verify that searching from the omnibox does search term replacement with
790  // first URL pattern.
791  chrome::FocusLocationBar(browser());
792  LocationBar* location_bar = browser()->window()->GetLocationBar();
793  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
794      "https://search.example/#q=foobar");
795  OmniboxEditModel* model = location_bar->GetLocationEntry()->model();
796  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
797  EXPECT_EQ(ASCIIToUTF16("foobar"), model->CurrentMatch().contents);
798
799  // Verify that searching from the omnibox does search term replacement with
800  // second URL pattern.
801  chrome::FocusLocationBar(browser());
802  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
803      "https://search.example/search#q=banana");
804  model = location_bar->GetLocationEntry()->model();
805  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
806  EXPECT_EQ(ASCIIToUTF16("banana"), model->CurrentMatch().contents);
807
808  // Verify that searching from the omnibox does search term replacement with
809  // standard search URL pattern.
810  chrome::FocusLocationBar(browser());
811  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
812      "https://search.example/search?q=tractor+parts");
813  model = location_bar->GetLocationEntry()->model();
814  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
815  EXPECT_EQ(ASCIIToUTF16("tractor parts"), model->CurrentMatch().contents);
816
817  // Verify that searching from the omnibox prioritizes hash over query.
818  chrome::FocusLocationBar(browser());
819  ui_test_utils::SendToOmniboxAndSubmit(location_bar,
820      "https://search.example/search?q=tractor+parts#q=foobar");
821  model = location_bar->GetLocationEntry()->model();
822  EXPECT_TRUE(model->CurrentMatch().destination_url.is_valid());
823  EXPECT_EQ(ASCIIToUTF16("foobar"), model->CurrentMatch().contents);
824}
825
826// The linux and win  bots can't create a GL context. http://crbug.com/103379
827#if defined(OS_MACOSX)
828IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
829  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
830  // WebGL is enabled by default.
831  content::WebContents* contents = chrome::GetActiveWebContents(browser());
832  EXPECT_TRUE(IsWebGLEnabled(contents));
833  // Disable with a policy.
834  PolicyMap policies;
835  policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
836               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
837  provider_.UpdateChromePolicy(policies);
838  // Crash and reload the tab to get a new renderer.
839  content::CrashTab(contents);
840  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
841  EXPECT_FALSE(IsWebGLEnabled(contents));
842  // Enable with a policy.
843  policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
844               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
845  provider_.UpdateChromePolicy(policies);
846  content::CrashTab(contents);
847  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
848  EXPECT_TRUE(IsWebGLEnabled(contents));
849}
850#endif
851
852IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
853  // Verifies that SPDY can be disable by policy.
854  EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
855  PolicyMap policies;
856  policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
857               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
858  provider_.UpdateChromePolicy(policies);
859  content::RunAllPendingInMessageLoop();
860  EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
861  // Verify that it can be force-enabled too.
862  browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
863  policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
864               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
865  provider_.UpdateChromePolicy(policies);
866  content::RunAllPendingInMessageLoop();
867  EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
868}
869
870IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
871  // Verifies that plugins can be forced to be disabled by policy.
872
873  // Verify that the Flash plugin exists and that it can be enabled and disabled
874  // by the user.
875  std::vector<webkit::WebPluginInfo> plugins;
876  GetPluginList(&plugins);
877  const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins);
878  if (!flash)
879    return;
880  PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile());
881  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
882  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
883  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
884  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
885  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
886
887  // Now disable it with a policy.
888  base::ListValue disabled_plugins;
889  disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
890  PolicyMap policies;
891  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
892               POLICY_SCOPE_USER, disabled_plugins.DeepCopy());
893  provider_.UpdateChromePolicy(policies);
894  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
895  // The user shouldn't be able to enable it.
896  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
897  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
898}
899
900IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
901  // Verifies that plugins with an exception in the blacklist can be enabled.
902
903  // Verify that the Flash plugin exists and that it can be enabled and disabled
904  // by the user.
905  std::vector<webkit::WebPluginInfo> plugins;
906  GetPluginList(&plugins);
907  const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins);
908  if (!flash)
909    return;
910  PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile());
911  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
912
913  // Disable all plugins.
914  base::ListValue disabled_plugins;
915  disabled_plugins.Append(base::Value::CreateStringValue("*"));
916  PolicyMap policies;
917  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
918               POLICY_SCOPE_USER, disabled_plugins.DeepCopy());
919  provider_.UpdateChromePolicy(policies);
920  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
921  // The user shouldn't be able to enable it.
922  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
923  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
924
925  // Now open an exception for flash.
926  base::ListValue disabled_plugins_exceptions;
927  disabled_plugins_exceptions.Append(
928      base::Value::CreateStringValue("*Flash*"));
929  policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
930               POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy());
931  provider_.UpdateChromePolicy(policies);
932  // It should revert to the user's preference automatically.
933  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
934  // And the user should be able to disable and enable again.
935  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
936  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
937  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
938  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
939}
940
941IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
942  // Verifies that a plugin can be force-installed with a policy.
943  std::vector<webkit::WebPluginInfo> plugins;
944  GetPluginList(&plugins);
945  const webkit::WebPluginInfo* flash = GetFlashPlugin(plugins);
946  if (!flash)
947    return;
948  PluginPrefs* plugin_prefs = PluginPrefs::GetForProfile(browser()->profile());
949  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
950
951  // The user disables it and then a policy forces it to be enabled.
952  EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
953  EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
954  base::ListValue plugin_list;
955  plugin_list.Append(base::Value::CreateStringValue(kFlashPluginName));
956  PolicyMap policies;
957  policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
958               POLICY_SCOPE_USER, plugin_list.DeepCopy());
959  provider_.UpdateChromePolicy(policies);
960  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
961  // The user can't disable it anymore.
962  EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
963  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
964
965  // When a plugin is both enabled and disabled, the whitelist takes precedence.
966  policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
967               POLICY_SCOPE_USER, plugin_list.DeepCopy());
968  provider_.UpdateChromePolicy(policies);
969  EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
970}
971
972IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
973  // Verifies that dangerous plugins can be always authorized to run with
974  // a policy.
975
976  // Verify that the test page exists. It is only present in checkouts with
977  // src-internal.
978  if (!file_util::PathExists(ui_test_utils::GetTestFilePath(
979      FilePath(FILE_PATH_LITERAL("plugin")),
980      FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
981    LOG(INFO) <<
982        "Test skipped because plugin/quicktime.html test file wasn't found.";
983    return;
984  }
985
986  ServeContentTestData();
987  // No plugins at startup.
988  EXPECT_EQ(0, CountPlugins());
989
990  content::WebContents* contents = chrome::GetActiveWebContents(browser());
991  ASSERT_TRUE(contents);
992  InfoBarTabHelper* infobar_helper =
993      InfoBarTabHelper::FromWebContents(contents);
994  ASSERT_TRUE(infobar_helper);
995  EXPECT_EQ(0u, infobar_helper->GetInfoBarCount());
996
997  FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
998  GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
999  ui_test_utils::NavigateToURL(browser(), url);
1000  // This should have triggered the dangerous plugin infobar.
1001  ASSERT_EQ(1u, infobar_helper->GetInfoBarCount());
1002  InfoBarDelegate* infobar_delegate =
1003      infobar_helper->GetInfoBarDelegateAt(0);
1004  EXPECT_TRUE(infobar_delegate->AsConfirmInfoBarDelegate());
1005  // And the plugin isn't running.
1006  EXPECT_EQ(0, CountPlugins());
1007
1008  // Now set a policy to always authorize this.
1009  PolicyMap policies;
1010  policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1011               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1012  provider_.UpdateChromePolicy(policies);
1013  // Reloading the page shouldn't trigger the infobar this time.
1014  ui_test_utils::NavigateToURL(browser(), url);
1015  EXPECT_EQ(0u, infobar_helper->GetInfoBarCount());
1016  // And the plugin started automatically.
1017  EXPECT_EQ(1, CountPlugins());
1018}
1019
1020IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1021  // Verifies that access to the developer tools can be disabled.
1022
1023  // Open devtools.
1024  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1025  content::WebContents* contents = chrome::GetActiveWebContents(browser());
1026  EXPECT_TRUE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1027
1028  // Disable devtools via policy.
1029  PolicyMap policies;
1030  policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1031               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1032  provider_.UpdateChromePolicy(policies);
1033  // The existing devtools window should have closed.
1034  EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1035  // And it's not possible to open it again.
1036  EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1037  EXPECT_FALSE(DevToolsWindow::GetDockedInstanceForInspectedTab(contents));
1038}
1039
1040// This policy isn't available on Chrome OS.
1041#if !defined(OS_CHROMEOS)
1042IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1043  // Verifies that the download directory can be forced by policy.
1044
1045  // Set the initial download directory.
1046  ScopedTempDir initial_dir;
1047  ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1048  browser()->profile()->GetPrefs()->SetFilePath(
1049      prefs::kDownloadDefaultDirectory, initial_dir.path());
1050  // Don't prompt for the download location during this test.
1051  browser()->profile()->GetPrefs()->SetBoolean(
1052      prefs::kPromptForDownload, false);
1053
1054  // Verify that downloads end up on the default directory.
1055  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1056  DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1057  file_util::DieFileDie(initial_dir.path().Append(file), false);
1058
1059  // Override the download directory with the policy and verify a download.
1060  ScopedTempDir forced_dir;
1061  ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1062  PolicyMap policies;
1063  policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1064               POLICY_SCOPE_USER,
1065               base::Value::CreateStringValue(forced_dir.path().value()));
1066  provider_.UpdateChromePolicy(policies);
1067  DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1068  // Verify that the first download location wasn't affected.
1069  EXPECT_FALSE(file_util::PathExists(initial_dir.path().Append(file)));
1070}
1071#endif
1072
1073IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklist) {
1074  // Verifies that blacklisted extensions can't be installed.
1075  ExtensionService* service = extension_service();
1076  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1077  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1078  base::ListValue blacklist;
1079  blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1080  PolicyMap policies;
1081  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1082               POLICY_SCOPE_USER, blacklist.DeepCopy());
1083  provider_.UpdateChromePolicy(policies);
1084
1085  // "good.crx" is blacklisted.
1086  EXPECT_FALSE(InstallExtension(kGoodCrxName));
1087  EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1088
1089  // "adblock.crx" is not.
1090  const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1091  ASSERT_TRUE(adblock);
1092  EXPECT_EQ(kAdBlockCrxId, adblock->id());
1093  EXPECT_EQ(adblock,
1094            service->GetExtensionById(kAdBlockCrxId, true));
1095
1096  // Now blacklist all extensions.
1097  blacklist.Clear();
1098  blacklist.Append(base::Value::CreateStringValue("*"));
1099  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1100               POLICY_SCOPE_USER, blacklist.DeepCopy());
1101  provider_.UpdateChromePolicy(policies);
1102  // AdBlock was automatically removed.
1103  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1104  // And can't be installed again, nor can good.crx.
1105  EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1106  EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1107  EXPECT_FALSE(InstallExtension(kGoodCrxName));
1108  EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1109}
1110
1111IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1112  // Verifies that the whitelist can open exceptions to the blacklist.
1113  ExtensionService* service = extension_service();
1114  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1115  ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1116  base::ListValue blacklist;
1117  blacklist.Append(base::Value::CreateStringValue("*"));
1118  base::ListValue whitelist;
1119  whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1120  PolicyMap policies;
1121  policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1122               POLICY_SCOPE_USER, blacklist.DeepCopy());
1123  policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1124               POLICY_SCOPE_USER, whitelist.DeepCopy());
1125  provider_.UpdateChromePolicy(policies);
1126  // "adblock.crx" is blacklisted.
1127  EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1128  EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1129  // "good.crx" has a whitelist exception.
1130  const extensions::Extension* good = InstallExtension(kGoodCrxName);
1131  ASSERT_TRUE(good);
1132  EXPECT_EQ(kGoodCrxId, good->id());
1133  EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1134  // The user can also remove this extension.
1135  UninstallExtension(kGoodCrxId, true);
1136}
1137
1138IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1139  // Verifies that extensions that are force-installed by policies are
1140  // installed and can't be uninstalled.
1141  ExtensionService* service = extension_service();
1142  ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1143
1144  // Extensions that are force-installed come from an update URL, which defaults
1145  // to the webstore. Use a mock URL for this test with an update manifest
1146  // that includes "good.crx".
1147  FilePath path = FilePath(kTestExtensionsDir).Append(kGoodCrxManifestName);
1148  GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1149
1150  // Setting the forcelist extension should install "good.crx".
1151  base::ListValue forcelist;
1152  forcelist.Append(base::Value::CreateStringValue(StringPrintf(
1153      "%s;%s", kGoodCrxId, url.spec().c_str())));
1154  PolicyMap policies;
1155  policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1156               POLICY_SCOPE_USER, forcelist.DeepCopy());
1157  content::WindowedNotificationObserver observer(
1158      chrome::NOTIFICATION_EXTENSION_INSTALLED,
1159      content::NotificationService::AllSources());
1160  provider_.UpdateChromePolicy(policies);
1161  observer.Wait();
1162  content::Details<const extensions::Extension> details = observer.details();
1163  EXPECT_EQ(kGoodCrxId, details->id());
1164  EXPECT_EQ(details.ptr(), service->GetExtensionById(kGoodCrxId, true));
1165  // The user is not allowed to uninstall force-installed extensions.
1166  UninstallExtension(kGoodCrxId, false);
1167}
1168
1169IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1170  // Verifies that the homepage can be configured with policies.
1171  // Set a default, and check that the home button navigates there.
1172  browser()->profile()->GetPrefs()->SetString(
1173      prefs::kHomePage, chrome::kChromeUIPolicyURL);
1174  browser()->profile()->GetPrefs()->SetBoolean(
1175      prefs::kHomePageIsNewTabPage, false);
1176  EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1177            browser()->profile()->GetHomePage());
1178  content::WebContents* contents = chrome::GetActiveWebContents(browser());
1179  EXPECT_EQ(GURL(chrome::kAboutBlankURL), contents->GetURL());
1180  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1181  EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1182
1183  // Now override with policy.
1184  PolicyMap policies;
1185  policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1186               POLICY_SCOPE_USER,
1187               base::Value::CreateStringValue(chrome::kChromeUICreditsURL));
1188  provider_.UpdateChromePolicy(policies);
1189  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1190  content::WaitForLoadStop(contents);
1191  EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1192
1193  policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1194               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1195  provider_.UpdateChromePolicy(policies);
1196  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1197  content::WaitForLoadStop(contents);
1198  EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1199}
1200
1201IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1202  // Verifies that incognito windows can't be opened when disabled by policy.
1203
1204  // Disable incognito via policy and verify that incognito windows can't be
1205  // opened.
1206  EXPECT_EQ(1u, BrowserList::size());
1207  EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1208  PolicyMap policies;
1209  policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1210               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
1211  provider_.UpdateChromePolicy(policies);
1212  EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1213  EXPECT_EQ(1u, BrowserList::size());
1214  EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1215
1216  // Enable via policy and verify that incognito windows can be opened.
1217  policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1218               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1219  provider_.UpdateChromePolicy(policies);
1220  EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1221  EXPECT_EQ(2u, BrowserList::size());
1222  EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1223}
1224
1225IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1226  // Verifies that Javascript can be disabled.
1227  content::WebContents* contents = chrome::GetActiveWebContents(browser());
1228  EXPECT_TRUE(IsJavascriptEnabled(contents));
1229  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1230  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1231
1232  // Disable Javascript via policy.
1233  PolicyMap policies;
1234  policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1235               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
1236  provider_.UpdateChromePolicy(policies);
1237  // Reload the page.
1238  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
1239  EXPECT_FALSE(IsJavascriptEnabled(contents));
1240  // Developer tools still work when javascript is disabled.
1241  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1242  EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1243  // Javascript is always enabled for the internal pages.
1244  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1245  EXPECT_TRUE(IsJavascriptEnabled(contents));
1246
1247  // The javascript content setting policy overrides the javascript policy.
1248  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
1249  EXPECT_FALSE(IsJavascriptEnabled(contents));
1250  policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1251               POLICY_SCOPE_USER,
1252               base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW));
1253  provider_.UpdateChromePolicy(policies);
1254  ui_test_utils::NavigateToURL(browser(), GURL(chrome::kAboutBlankURL));
1255  EXPECT_TRUE(IsJavascriptEnabled(contents));
1256}
1257
1258IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1259  // Verifies that browsing history is not saved.
1260  PolicyMap policies;
1261  policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1262               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1263  provider_.UpdateChromePolicy(policies);
1264  GURL url = ui_test_utils::GetTestUrl(
1265      FilePath(FilePath::kCurrentDirectory),
1266      FilePath(FILE_PATH_LITERAL("empty.html")));
1267  ui_test_utils::NavigateToURL(browser(), url);
1268  // Verify that the navigation wasn't saved in the history.
1269  ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1270  EXPECT_EQ(0u, enumerator1.urls().size());
1271
1272  // Now flip the policy and try again.
1273  policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1274               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
1275  provider_.UpdateChromePolicy(policies);
1276  ui_test_utils::NavigateToURL(browser(), url);
1277  // Verify that the navigation was saved in the history.
1278  ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1279  ASSERT_EQ(1u, enumerator2.urls().size());
1280  EXPECT_EQ(url, enumerator2.urls()[0]);
1281}
1282
1283IN_PROC_BROWSER_TEST_F(PolicyTest, TranslateEnabled) {
1284  // Verifies that translate can be forced enabled or disabled by policy.
1285
1286  // Get the |infobar_helper|, and verify that there are no infobars on startup.
1287  content::WebContents* contents = chrome::GetActiveWebContents(browser());
1288  ASSERT_TRUE(contents);
1289  InfoBarTabHelper* infobar_helper =
1290      InfoBarTabHelper::FromWebContents(contents);
1291  ASSERT_TRUE(infobar_helper);
1292  EXPECT_EQ(0u, infobar_helper->GetInfoBarCount());
1293
1294  // Force enable the translate feature.
1295  PolicyMap policies;
1296  policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1297               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1298  provider_.UpdateChromePolicy(policies);
1299  // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
1300  // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
1301  // TranslateManager observes. This allows checking that an infobar is NOT
1302  // shown below, without polling for infobars for some indeterminate amount
1303  // of time.
1304  GURL url = ui_test_utils::GetTestUrl(
1305      FilePath(), FilePath(FILE_PATH_LITERAL("french_page.html")));
1306  content::WindowedNotificationObserver language_observer1(
1307      chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1308      content::NotificationService::AllSources());
1309  ui_test_utils::NavigateToURL(browser(), url);
1310  language_observer1.Wait();
1311  // Verify that the translate infobar showed up.
1312  ASSERT_EQ(1u, infobar_helper->GetInfoBarCount());
1313  InfoBarDelegate* infobar_delegate =
1314      infobar_helper->GetInfoBarDelegateAt(0);
1315  TranslateInfoBarDelegate* delegate =
1316      infobar_delegate->AsTranslateInfoBarDelegate();
1317  ASSERT_TRUE(delegate);
1318  EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE, delegate->type());
1319  EXPECT_EQ("fr", delegate->original_language_code());
1320
1321  // Now force disable translate.
1322  infobar_helper->RemoveInfoBar(infobar_delegate);
1323  EXPECT_EQ(0u, infobar_helper->GetInfoBarCount());
1324  policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1325               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
1326  provider_.UpdateChromePolicy(policies);
1327  // Navigating to the same URL now doesn't trigger an infobar.
1328  content::WindowedNotificationObserver language_observer2(
1329      chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1330      content::NotificationService::AllSources());
1331  ui_test_utils::NavigateToURL(browser(), url);
1332  language_observer2.Wait();
1333  EXPECT_EQ(0u, infobar_helper->GetInfoBarCount());
1334}
1335
1336IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
1337  // Checks that URLs can be blacklisted, and that exceptions can be made to
1338  // the blacklist.
1339  const GURL kAAA("http://aaa.com/empty.html");
1340  const GURL kBBB("http://bbb.com/empty.html");
1341  const GURL kSUB_BBB("http://sub.bbb.com/empty.html");
1342  const GURL kBBB_PATH("http://bbb.com/policy/device_management");
1343  // Filter |kURLS| on IO thread, so that requests to those hosts end up
1344  // as URLRequestMockHTTPJobs.
1345  const GURL* kURLS[] = {
1346    &kAAA,
1347    &kBBB,
1348    &kSUB_BBB,
1349    &kBBB_PATH,
1350  };
1351  BrowserThread::PostTaskAndReply(
1352      BrowserThread::IO, FROM_HERE,
1353      base::Bind(RedirectHostsToTestDataOnIOThread, kURLS, arraysize(kURLS)),
1354      MessageLoop::QuitClosure());
1355  content::RunMessageLoop();
1356
1357  // Verify that all the URLs can be opened without a blacklist.
1358  for (size_t i = 0; i < arraysize(kURLS); ++i)
1359    CheckCanOpenURL(browser(), *kURLS[i]);
1360
1361  // Set a blacklist.
1362  base::ListValue blacklist;
1363  blacklist.Append(base::Value::CreateStringValue("bbb.com"));
1364  PolicyMap policies;
1365  policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1366               POLICY_SCOPE_USER, blacklist.DeepCopy());
1367  provider_.UpdateChromePolicy(policies);
1368  FlushBlacklistPolicy();
1369  // All bbb.com URLs are blocked.
1370  CheckCanOpenURL(browser(), kAAA);
1371  for (size_t i = 1; i < arraysize(kURLS); ++i)
1372    CheckURLIsBlocked(browser(), *kURLS[i]);
1373
1374  // Whitelist some sites of bbb.com.
1375  base::ListValue whitelist;
1376  whitelist.Append(base::Value::CreateStringValue("sub.bbb.com"));
1377  whitelist.Append(base::Value::CreateStringValue("bbb.com/policy"));
1378  policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1379               POLICY_SCOPE_USER, whitelist.DeepCopy());
1380  provider_.UpdateChromePolicy(policies);
1381  FlushBlacklistPolicy();
1382  CheckCanOpenURL(browser(), kAAA);
1383  CheckURLIsBlocked(browser(), kBBB);
1384  CheckCanOpenURL(browser(), kSUB_BBB);
1385  CheckCanOpenURL(browser(), kBBB_PATH);
1386}
1387
1388// Flaky on Linux. http://crbug.com/155459
1389#if defined(OS_LINUX)
1390#define MAYBE_DisableScreenshotsFeedback DISABLED_DisableScreenshotsFeedback
1391#else
1392#define MAYBE_DisableScreenshotsFeedback DisableScreenshotsFeedback
1393#endif
1394IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_DisableScreenshotsFeedback) {
1395  // Make sure current screenshot can be taken and displayed on feedback page.
1396  TestScreenshotFeedback(true);
1397
1398  // Check if banning screenshots disabled feedback page's ability to grab a
1399  // screenshot.
1400  TestScreenshotFeedback(false);
1401}
1402
1403#if defined(OS_CHROMEOS)
1404IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
1405  int screenshot_count = CountScreenshots();
1406
1407  // Make sure screenshots are counted correctly.
1408  TestScreenshotFile(true);
1409  ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
1410
1411  // Check if trying to take a screenshot fails when disabled by policy.
1412  TestScreenshotFile(false);
1413  ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
1414}
1415
1416IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
1417  // Set up the mock observer.
1418  chromeos::AudioHandler* audio_handler = chromeos::AudioHandler::GetInstance();
1419  scoped_ptr<TestVolumeObserver> mock(new TestVolumeObserver());
1420  audio_handler->AddVolumeObserver(mock.get());
1421
1422  bool prior_state = audio_handler->IsMuted();
1423  // Make sure we are not muted and then toggle the policy and observe if the
1424  // trigger was successful.
1425  EXPECT_CALL(*mock, OnMuteToggled()).Times(1);
1426  audio_handler->SetMuted(false);
1427  EXPECT_FALSE(audio_handler->IsMuted());
1428  EXPECT_CALL(*mock, OnMuteToggled()).Times(1);
1429  PolicyMap policies;
1430  policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
1431               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false));
1432  provider_.UpdateChromePolicy(policies);
1433  EXPECT_TRUE(audio_handler->IsMuted());
1434  // This should not change the state now and should not trigger OnMuteToggled.
1435  audio_handler->SetMuted(false);
1436  EXPECT_TRUE(audio_handler->IsMuted());
1437
1438  // Toggle back and observe if the trigger was successful.
1439  EXPECT_CALL(*mock, OnMuteToggled()).Times(1);
1440  policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
1441               POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true));
1442  provider_.UpdateChromePolicy(policies);
1443  EXPECT_FALSE(audio_handler->IsMuted());
1444  EXPECT_CALL(*mock, OnMuteToggled()).Times(1);
1445  audio_handler->SetMuted(true);
1446  EXPECT_TRUE(audio_handler->IsMuted());
1447  // Revert the prior state.
1448  EXPECT_CALL(*mock, OnMuteToggled()).Times(1);
1449  audio_handler->SetMuted(prior_state);
1450  audio_handler->RemoveVolumeObserver(mock.get());
1451}
1452#endif
1453
1454namespace {
1455
1456bool IsNonSwitchArgument(const CommandLine::StringType& s) {
1457  return s.empty() || s[0] != '-';
1458}
1459
1460}  // namespace
1461
1462// Similar to PolicyTest but allows setting policies before the browser is
1463// created. Each test parameter is a method that sets up the early policies
1464// and stores the expected startup URLs in |expected_urls_|.
1465class RestoreOnStartupPolicyTest
1466    : public PolicyTest,
1467      public testing::WithParamInterface<
1468          void (RestoreOnStartupPolicyTest::*)(void)> {
1469 public:
1470  RestoreOnStartupPolicyTest() {}
1471  virtual ~RestoreOnStartupPolicyTest() {}
1472
1473#if defined(OS_CHROMEOS)
1474  virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
1475    // TODO(nkostylev): Investigate if we can remove this switch.
1476    command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
1477    PolicyTest::SetUpCommandLine(command_line);
1478  }
1479#endif
1480
1481  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
1482    PolicyTest::SetUpInProcessBrowserTestFixture();
1483    // Set early policies now, before the browser is created.
1484    (this->*(GetParam()))();
1485
1486    // Remove the non-switch arguments, so that session restore kicks in for
1487    // these tests.
1488    CommandLine* command_line = CommandLine::ForCurrentProcess();
1489    CommandLine::StringVector argv = command_line->argv();
1490    argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
1491               argv.end());
1492    command_line->InitFromArgv(argv);
1493    ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
1494                           command_line->argv().begin()));
1495  }
1496
1497  void HomepageIsNotNTP() {
1498    // Verifies that policy can set the startup pages to the homepage, when
1499    // the homepage is not the NTP.
1500    PolicyMap policies;
1501    policies.Set(
1502        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1503        base::Value::CreateIntegerValue(
1504            SessionStartupPref::kPrefValueHomePage));
1505    policies.Set(
1506        key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1507        base::Value::CreateBooleanValue(false));
1508    policies.Set(
1509        key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1510        base::Value::CreateStringValue(kURLs[1]));
1511    provider_.UpdateChromePolicy(policies);
1512
1513    expected_urls_.push_back(GURL(kURLs[1]));
1514  }
1515
1516  void HomepageIsNTP() {
1517    // Verifies that policy can set the startup pages to the homepage, when
1518    // the homepage is the NTP.
1519    PolicyMap policies;
1520    policies.Set(
1521        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1522        base::Value::CreateIntegerValue(
1523            SessionStartupPref::kPrefValueHomePage));
1524    policies.Set(
1525        key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1526        base::Value::CreateBooleanValue(true));
1527    provider_.UpdateChromePolicy(policies);
1528
1529    expected_urls_.push_back(GURL(kURLs[0]));
1530  }
1531
1532  void ListOfURLs() {
1533    // Verifies that policy can set the startup pages to a list of URLs.
1534    base::ListValue urls;
1535    for (size_t i = 0; i < arraysize(kURLs); ++i) {
1536      urls.Append(base::Value::CreateStringValue(kURLs[i]));
1537      expected_urls_.push_back(GURL(kURLs[i]));
1538    }
1539    PolicyMap policies;
1540    policies.Set(
1541        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1542        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs));
1543    policies.Set(
1544        key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1545        urls.DeepCopy());
1546    provider_.UpdateChromePolicy(policies);
1547  }
1548
1549  void NTP() {
1550    // Verifies that policy can set the startup page to the NTP.
1551    PolicyMap policies;
1552    policies.Set(
1553        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1554        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab));
1555    provider_.UpdateChromePolicy(policies);
1556    expected_urls_.push_back(GURL(kURLs[0]));
1557  }
1558
1559  void Last() {
1560    // Verifies that policy can set the startup pages to the last session.
1561    PolicyMap policies;
1562    policies.Set(
1563        key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1564        base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast));
1565    provider_.UpdateChromePolicy(policies);
1566    // This should restore the tabs opened at PRE_RunTest below.
1567    for (size_t i = 0; i < arraysize(kURLs); ++i)
1568      expected_urls_.push_back(GURL(kURLs[i]));
1569  }
1570
1571  std::vector<GURL> expected_urls_;
1572};
1573
1574IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
1575  // Open some tabs to verify if they are restored after the browser restarts.
1576  // Most policy settings override this, except kPrefValueLast which enforces
1577  // a restore.
1578  ui_test_utils::NavigateToURL(browser(), GURL(kURLs[0]));
1579  for (size_t i = 1; i < arraysize(kURLs); ++i) {
1580    content::WindowedNotificationObserver observer(
1581        content::NOTIFICATION_LOAD_STOP,
1582        content::NotificationService::AllSources());
1583    chrome::AddSelectedTabWithURL(browser(), GURL(kURLs[i]),
1584                                  content::PAGE_TRANSITION_LINK);
1585    observer.Wait();
1586  }
1587}
1588
1589IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
1590  TabStripModel* model = browser()->tab_strip_model();
1591  int size = static_cast<int>(expected_urls_.size());
1592  EXPECT_EQ(size, model->count());
1593  for (int i = 0; i < size && i < model->count(); ++i) {
1594    EXPECT_EQ(expected_urls_[i],
1595              model->GetTabContentsAt(i)->web_contents()->GetURL());
1596  }
1597}
1598
1599INSTANTIATE_TEST_CASE_P(
1600    RestoreOnStartupPolicyTestInstance,
1601    RestoreOnStartupPolicyTest,
1602    testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
1603                    &RestoreOnStartupPolicyTest::HomepageIsNTP,
1604                    &RestoreOnStartupPolicyTest::ListOfURLs,
1605                    &RestoreOnStartupPolicyTest::NTP,
1606                    &RestoreOnStartupPolicyTest::Last));
1607
1608// Similar to PolicyTest but sets a couple of policies before the browser is
1609// started.
1610class PolicyStatisticsCollectorTest : public PolicyTest {
1611 public:
1612  PolicyStatisticsCollectorTest() {}
1613  virtual ~PolicyStatisticsCollectorTest() {}
1614
1615  virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
1616    PolicyTest::SetUpInProcessBrowserTestFixture();
1617    PolicyMap policies;
1618    policies.Set(
1619        key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1620        base::Value::CreateBooleanValue(true));
1621    policies.Set(
1622        key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1623        base::Value::CreateBooleanValue(false));
1624    policies.Set(
1625        key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1626        base::Value::CreateStringValue("http://chromium.org"));
1627    provider_.UpdateChromePolicy(policies);
1628  }
1629};
1630
1631IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
1632  // Verifies that policy usage histograms are collected at startup.
1633
1634  // BrowserPolicyConnector::Init() has already been called. Make sure the
1635  // CompleteInitialization() task has executed as well.
1636  content::RunAllPendingInMessageLoop();
1637
1638  GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) +
1639                               std::string(content::kStandardSchemeSeparator) +
1640                               std::string(chrome::kChromeUIHistogramHost));
1641  ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
1642  content::WebContents* contents = chrome::GetActiveWebContents(browser());
1643  std::string text;
1644  ASSERT_TRUE(content::ExecuteJavaScriptAndExtractString(
1645      contents->GetRenderViewHost(),
1646      std::wstring(),
1647      L"var nodes = document.querySelectorAll('body > pre');"
1648      L"var result = '';"
1649      L"for (var i = 0; i < nodes.length; ++i) {"
1650      L"  var text = nodes[i].innerHTML;"
1651      L"  if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
1652      L"    result = text;"
1653      L"    break;"
1654      L"  }"
1655      L"}"
1656      L"domAutomationController.send(result);",
1657      &text));
1658  ASSERT_FALSE(text.empty());
1659  const std::string kExpectedLabel =
1660      "Histogram: Enterprise.Policies recorded 3 samples";
1661  EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
1662  // HomepageLocation has policy ID 1.
1663  EXPECT_NE(std::string::npos, text.find("<br>1   ---"));
1664  // ShowHomeButton has policy ID 35.
1665  EXPECT_NE(std::string::npos, text.find("<br>35  ---"));
1666  // BookmarkBarEnabled has policy ID 82.
1667  EXPECT_NE(std::string::npos, text.find("<br>82  ---"));
1668}
1669
1670}  // namespace policy
1671