1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/test/test_file_util.h"
26 #include "base/time/time.h"
27 #include "base/values.h"
28 #include "chrome/app/chrome_command_ids.h"
29 #include "chrome/browser/autocomplete/autocomplete_controller.h"
30 #include "chrome/browser/background/background_contents_service.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
34 #include "chrome/browser/devtools/devtools_window.h"
35 #include "chrome/browser/download/download_prefs.h"
36 #include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
37 #include "chrome/browser/extensions/crx_installer.h"
38 #include "chrome/browser/extensions/extension_host.h"
39 #include "chrome/browser/extensions/extension_service.h"
40 #include "chrome/browser/extensions/unpacked_installer.h"
41 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
42 #include "chrome/browser/extensions/updater/extension_updater.h"
43 #include "chrome/browser/infobars/infobar.h"
44 #include "chrome/browser/infobars/infobar_service.h"
45 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
46 #include "chrome/browser/media/media_stream_devices_controller.h"
47 #include "chrome/browser/metrics/variations/variations_service.h"
48 #include "chrome/browser/net/url_request_mock_util.h"
49 #include "chrome/browser/plugins/plugin_prefs.h"
50 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
51 #include "chrome/browser/policy/profile_policy_connector.h"
52 #include "chrome/browser/policy/profile_policy_connector_factory.h"
53 #include "chrome/browser/prefs/session_startup_pref.h"
54 #include "chrome/browser/profiles/profile.h"
55 #include "chrome/browser/search/instant_service.h"
56 #include "chrome/browser/search/instant_service_factory.h"
57 #include "chrome/browser/search/search.h"
58 #include "chrome/browser/search_engines/template_url.h"
59 #include "chrome/browser/search_engines/template_url_service.h"
60 #include "chrome/browser/search_engines/template_url_service_factory.h"
61 #include "chrome/browser/translate/translate_infobar_delegate.h"
62 #include "chrome/browser/translate/translate_service.h"
63 #include "chrome/browser/translate/translate_tab_helper.h"
64 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
65 #include "chrome/browser/ui/browser.h"
66 #include "chrome/browser/ui/browser_commands.h"
67 #include "chrome/browser/ui/browser_list.h"
68 #include "chrome/browser/ui/browser_tabstrip.h"
69 #include "chrome/browser/ui/browser_window.h"
70 #include "chrome/browser/ui/host_desktop.h"
71 #include "chrome/browser/ui/omnibox/location_bar.h"
72 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
73 #include "chrome/browser/ui/omnibox/omnibox_view.h"
74 #include "chrome/browser/ui/tabs/tab_strip_model.h"
75 #include "chrome/common/chrome_paths.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/content_settings.h"
78 #include "chrome/common/content_settings_pattern.h"
79 #include "chrome/common/extensions/extension_constants.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/test/base/in_process_browser_test.h"
83 #include "chrome/test/base/test_switches.h"
84 #include "chrome/test/base/ui_test_utils.h"
85 #include "components/policy/core/browser/browser_policy_connector.h"
86 #include "components/policy/core/common/external_data_fetcher.h"
87 #include "components/policy/core/common/mock_configuration_policy_provider.h"
88 #include "components/policy/core/common/policy_map.h"
89 #include "components/policy/core/common/policy_pref_names.h"
90 #include "components/policy/core/common/policy_service.h"
91 #include "components/policy/core/common/policy_service_impl.h"
92 #include "content/public/browser/browser_child_process_host_iterator.h"
93 #include "content/public/browser/browser_context.h"
94 #include "content/public/browser/browser_thread.h"
95 #include "content/public/browser/child_process_data.h"
96 #include "content/public/browser/download_item.h"
97 #include "content/public/browser/download_manager.h"
98 #include "content/public/browser/gpu_data_manager.h"
99 #include "content/public/browser/notification_details.h"
100 #include "content/public/browser/notification_observer.h"
101 #include "content/public/browser/notification_registrar.h"
102 #include "content/public/browser/notification_service.h"
103 #include "content/public/browser/notification_source.h"
104 #include "content/public/browser/notification_types.h"
105 #include "content/public/browser/plugin_service.h"
106 #include "content/public/browser/render_process_host.h"
107 #include "content/public/browser/render_view_host.h"
108 #include "content/public/browser/web_contents.h"
109 #include "content/public/common/content_constants.h"
110 #include "content/public/common/content_paths.h"
111 #include "content/public/common/page_transition_types.h"
112 #include "content/public/common/process_type.h"
113 #include "content/public/common/result_codes.h"
114 #include "content/public/common/url_constants.h"
115 #include "content/public/common/webplugininfo.h"
116 #include "content/public/test/browser_test_utils.h"
117 #include "content/public/test/download_test_observer.h"
118 #include "content/public/test/mock_notification_observer.h"
119 #include "content/public/test/test_navigation_observer.h"
120 #include "content/public/test/test_utils.h"
121 #include "content/test/net/url_request_failed_job.h"
122 #include "content/test/net/url_request_mock_http_job.h"
123 #include "extensions/browser/extension_system.h"
124 #include "extensions/browser/process_manager.h"
125 #include "extensions/common/constants.h"
126 #include "extensions/common/extension.h"
127 #include "extensions/common/extension_set.h"
128 #include "grit/generated_resources.h"
129 #include "net/base/net_errors.h"
130 #include "net/base/net_util.h"
131 #include "net/base/url_util.h"
132 #include "net/http/http_stream_factory.h"
133 #include "net/url_request/url_request.h"
134 #include "net/url_request/url_request_filter.h"
135 #include "policy/policy_constants.h"
136 #include "testing/gmock/include/gmock/gmock.h"
137 #include "testing/gtest/include/gtest/gtest.h"
138 #include "third_party/WebKit/public/web/WebInputEvent.h"
139 #include "ui/base/l10n/l10n_util.h"
140 #include "ui/base/resource/resource_bundle.h"
141 #include "url/gurl.h"
143 #if defined(OS_CHROMEOS)
144 #include "ash/accelerators/accelerator_controller.h"
145 #include "ash/accelerators/accelerator_table.h"
146 #include "ash/magnifier/magnifier_constants.h"
147 #include "ash/shell.h"
148 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
149 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
150 #include "chrome/browser/profiles/profile_manager.h"
151 #include "chrome/browser/ui/ash/screenshot_taker.h"
152 #include "chromeos/audio/cras_audio_handler.h"
155 #if !defined(OS_MACOSX)
156 #include "apps/app_window.h"
157 #include "apps/app_window_registry.h"
158 #include "apps/ui/native_app_window.h"
159 #include "base/basictypes.h"
160 #include "base/compiler_specific.h"
161 #include "chrome/browser/ui/extensions/application_launch.h"
162 #include "ui/base/window_open_disposition.h"
165 using content::BrowserThread;
166 using content::URLRequestMockHTTPJob;
168 using testing::Return;
175 #if defined(OS_CHROMEOS)
176 const int kOneHourInMs = 60 * 60 * 1000;
177 const int kThreeHoursInMs = 180 * 60 * 1000;
180 const char kURL[] = "http://example.com";
181 const char kCookieValue[] = "converted=true";
182 // Assigned to Philip J. Fry to fix eventually.
183 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
185 const base::FilePath::CharType kTestExtensionsDir[] =
186 FILE_PATH_LITERAL("extensions");
187 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
188 const base::FilePath::CharType kAdBlockCrxName[] =
189 FILE_PATH_LITERAL("adblock.crx");
190 const base::FilePath::CharType kHostedAppCrxName[] =
191 FILE_PATH_LITERAL("hosted_app.crx");
193 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
194 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
195 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
197 const base::FilePath::CharType kGood2CrxManifestName[] =
198 FILE_PATH_LITERAL("good2_update_manifest.xml");
199 const base::FilePath::CharType kGoodV1CrxManifestName[] =
200 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
201 const base::FilePath::CharType kGoodUnpackedExt[] =
202 FILE_PATH_LITERAL("good_unpacked");
203 const base::FilePath::CharType kAppUnpackedExt[] =
204 FILE_PATH_LITERAL("app");
206 #if !defined(OS_MACOSX)
207 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
208 FILE_PATH_LITERAL("fullscreen_app");
209 #endif // !defined(OS_MACOSX)
211 // Filters requests to the hosts in |urls| and redirects them to the test data
212 // dir through URLRequestMockHTTPJobs.
213 void RedirectHostsToTestData(const char* const urls[], size_t size) {
214 // Map the given hosts to the test data dir.
215 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
216 base::FilePath base_path;
217 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
218 for (size_t i = 0; i < size; ++i) {
219 const GURL url(urls[i]);
220 EXPECT_TRUE(url.is_valid());
221 filter->AddUrlProtocolHandler(url,
222 URLRequestMockHTTPJob::CreateProtocolHandler(base_path));
226 // Remove filters for requests to the hosts in |urls|.
227 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
228 // Map the given hosts to the test data dir.
229 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
230 for (size_t i = 0; i < size; ++i) {
231 const GURL url(urls[i]);
232 EXPECT_TRUE(url.is_valid());
233 filter->RemoveUrlHandler(url);
237 // Fails requests using ERR_CONNECTION_RESET.
238 net::URLRequestJob* FailedJobFactory(
239 net::URLRequest* request,
240 net::NetworkDelegate* network_delegate,
241 const std::string& scheme) {
242 return new content::URLRequestFailedJob(
243 request, network_delegate, net::ERR_CONNECTION_RESET);
246 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
247 class MakeRequestFail {
249 // Sets up the filter on IO thread such that requests to |host| fail.
250 explicit MakeRequestFail(const std::string& host) : host_(host) {
251 BrowserThread::PostTaskAndReply(
252 BrowserThread::IO, FROM_HERE,
253 base::Bind(MakeRequestFailOnIO, host_),
254 base::MessageLoop::QuitClosure());
255 content::RunMessageLoop();
258 BrowserThread::PostTaskAndReply(
259 BrowserThread::IO, FROM_HERE,
260 base::Bind(UndoMakeRequestFailOnIO, host_),
261 base::MessageLoop::QuitClosure());
262 content::RunMessageLoop();
266 // Filters requests to the |host| such that they fail. Run on IO thread.
267 static void MakeRequestFailOnIO(const std::string& host) {
268 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
269 filter->AddHostnameHandler("http", host, &FailedJobFactory);
270 filter->AddHostnameHandler("https", host, &FailedJobFactory);
273 // Remove filters for requests to the |host|. Run on IO thread.
274 static void UndoMakeRequestFailOnIO(const std::string& host) {
275 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
276 filter->RemoveHostnameHandler("http", host);
277 filter->RemoveHostnameHandler("https", host);
280 const std::string host_;
283 // Verifies that the given url |spec| can be opened. This assumes that |spec|
284 // points at empty.html in the test data dir.
285 void CheckCanOpenURL(Browser* browser, const char* spec) {
287 ui_test_utils::NavigateToURL(browser, url);
288 content::WebContents* contents =
289 browser->tab_strip_model()->GetActiveWebContents();
290 EXPECT_EQ(url, contents->GetURL());
291 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
292 EXPECT_NE(title, contents->GetTitle());
295 // Verifies that access to the given url |spec| is blocked.
296 void CheckURLIsBlocked(Browser* browser, const char* spec) {
298 ui_test_utils::NavigateToURL(browser, url);
299 content::WebContents* contents =
300 browser->tab_strip_model()->GetActiveWebContents();
301 EXPECT_EQ(url, contents->GetURL());
302 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
303 EXPECT_EQ(title, contents->GetTitle());
305 // Verify that the expected error page is being displayed.
307 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
309 "var textContent = document.body.textContent;"
310 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
311 "domAutomationController.send(hasError);",
316 #if !defined(OS_CHROMEOS)
317 // Downloads a file named |file| and expects it to be saved to |dir|, which
319 void DownloadAndVerifyFile(
320 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
321 content::DownloadManager* download_manager =
322 content::BrowserContext::GetDownloadManager(browser->profile());
323 content::DownloadTestObserverTerminal observer(
325 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
326 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
327 base::FilePath downloaded = dir.Append(file);
328 EXPECT_FALSE(base::PathExists(downloaded));
329 ui_test_utils::NavigateToURLWithDisposition(
330 browser, url, CURRENT_TAB,
331 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
332 observer.WaitForFinished();
334 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
335 EXPECT_TRUE(base::PathExists(downloaded));
336 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
337 EXPECT_EQ(file, enumerator.Next().BaseName());
338 EXPECT_EQ(base::FilePath(), enumerator.Next());
343 int CountScreenshots() {
344 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
345 ProfileManager::GetActiveUserProfile());
346 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
347 false, base::FileEnumerator::FILES,
350 while (!enumerator.Next().empty())
356 // Checks if WebGL is enabled in the given WebContents.
357 bool IsWebGLEnabled(content::WebContents* contents) {
359 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
361 "var canvas = document.createElement('canvas');"
362 "var context = canvas.getContext('webgl');"
363 "domAutomationController.send(context != null);",
368 bool IsJavascriptEnabled(content::WebContents* contents) {
369 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
370 contents->GetRenderViewHost(), "123");
372 if (!value->GetAsInteger(&result))
373 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
374 return result == 123;
377 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
378 const std::vector<content::WebPluginInfo>& in) {
380 base::MessageLoop::current()->QuitWhenIdle();
384 void CopyValueAndQuit(T* out, T in) {
386 base::MessageLoop::current()->QuitWhenIdle();
389 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
390 content::PluginService* service = content::PluginService::GetInstance();
391 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
392 content::RunMessageLoop();
395 const content::WebPluginInfo* GetFlashPlugin(
396 const std::vector<content::WebPluginInfo>& plugins) {
397 const content::WebPluginInfo* flash = NULL;
398 for (size_t i = 0; i < plugins.size(); ++i) {
399 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
404 #if defined(OFFICIAL_BUILD)
405 // Official builds bundle Flash.
409 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
414 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
415 const content::WebPluginInfo* plugin,
418 plugin_prefs->EnablePlugin(enabled, plugin->path,
419 base::Bind(CopyValueAndQuit<bool>, &ok));
420 content::RunMessageLoop();
424 int CountPluginsOnIOThread() {
426 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
427 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
428 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
437 BrowserThread::PostTaskAndReplyWithResult(
438 BrowserThread::IO, FROM_HERE,
439 base::Bind(CountPluginsOnIOThread),
440 base::Bind(CopyValueAndQuit<int>, &count));
441 content::RunMessageLoop();
446 void FlushBlacklistPolicy() {
447 // Updates of the URLBlacklist are done on IO, after building the blacklist
448 // on FILE, which is initiated from IO.
449 content::RunAllPendingInMessageLoop(BrowserThread::IO);
450 content::RunAllPendingInMessageLoop(BrowserThread::FILE);
451 content::RunAllPendingInMessageLoop(BrowserThread::IO);
454 bool ContainsVisibleElement(content::WebContents* contents,
455 const std::string& id) {
457 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
459 "var elem = document.getElementById('" + id + "');"
460 "domAutomationController.send(!!elem && !elem.hidden);",
465 #if defined(OS_CHROMEOS)
466 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
468 TestAudioObserver() : output_mute_changed_count_(0) {
471 int output_mute_changed_count() const {
472 return output_mute_changed_count_;
475 virtual ~TestAudioObserver() {}
478 // chromeos::CrasAudioHandler::AudioObserver overrides.
479 virtual void OnOutputMuteChanged() OVERRIDE {
480 ++output_mute_changed_count_;
484 int output_mute_changed_count_;
486 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
490 // This class waits until either a load stops or the WebContents is destroyed.
491 class WebContentsLoadedOrDestroyedWatcher
492 : public content::WebContentsObserver {
494 explicit WebContentsLoadedOrDestroyedWatcher(
495 content::WebContents* web_contents);
496 virtual ~WebContentsLoadedOrDestroyedWatcher();
498 // Waits until the WebContents's load is done or until it is destroyed.
501 // Overridden WebContentsObserver methods.
502 virtual void WebContentsDestroyed(
503 content::WebContents* web_contents) OVERRIDE;
504 virtual void DidStopLoading(
505 content::RenderViewHost* render_view_host) OVERRIDE;
508 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
510 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
513 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
514 content::WebContents* web_contents)
515 : content::WebContentsObserver(web_contents),
516 message_loop_runner_(new content::MessageLoopRunner) {
519 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
521 void WebContentsLoadedOrDestroyedWatcher::Wait() {
522 message_loop_runner_->Run();
525 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed(
526 content::WebContents* web_contents) {
527 message_loop_runner_->Quit();
530 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
531 content::RenderViewHost* render_view_host) {
532 message_loop_runner_->Quit();
535 #if !defined(OS_MACOSX)
537 // Observer used to wait for the creation of a new app window.
538 class TestAddAppWindowObserver : public apps::AppWindowRegistry::Observer {
540 explicit TestAddAppWindowObserver(apps::AppWindowRegistry* registry);
541 virtual ~TestAddAppWindowObserver();
543 // apps::AppWindowRegistry::Observer:
544 virtual void OnAppWindowAdded(apps::AppWindow* app_window) OVERRIDE;
545 virtual void OnAppWindowIconChanged(apps::AppWindow* app_window) OVERRIDE;
546 virtual void OnAppWindowRemoved(apps::AppWindow* app_window) OVERRIDE;
548 apps::AppWindow* WaitForAppWindow();
551 apps::AppWindowRegistry* registry_; // Not owned.
552 apps::AppWindow* window_; // Not owned.
553 base::RunLoop run_loop_;
555 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
558 TestAddAppWindowObserver::TestAddAppWindowObserver(
559 apps::AppWindowRegistry* registry)
560 : registry_(registry), window_(NULL) {
561 registry_->AddObserver(this);
564 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
565 registry_->RemoveObserver(this);
568 void TestAddAppWindowObserver::OnAppWindowAdded(apps::AppWindow* app_window) {
569 window_ = app_window;
573 void TestAddAppWindowObserver::OnAppWindowIconChanged(
574 apps::AppWindow* app_window) {}
576 void TestAddAppWindowObserver::OnAppWindowRemoved(apps::AppWindow* app_window) {
579 apps::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
588 class PolicyTest : public InProcessBrowserTest {
591 virtual ~PolicyTest() {}
593 virtual void SetUp() OVERRIDE {
594 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
595 InProcessBrowserTest::SetUp();
598 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
599 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
600 EXPECT_CALL(provider_, IsInitializationComplete(_))
601 .WillRepeatedly(Return(true));
602 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
605 virtual void SetUpOnMainThread() OVERRIDE {
606 BrowserThread::PostTask(
607 BrowserThread::IO, FROM_HERE,
608 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
611 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
612 // instead of chrome::DIR_TEST_DATA.
613 void ServeContentTestData() {
614 base::FilePath root_http;
615 PathService::Get(content::DIR_TEST_DATA, &root_http);
616 BrowserThread::PostTaskAndReply(
617 BrowserThread::IO, FROM_HERE,
618 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http),
619 base::MessageLoop::current()->QuitWhenIdleClosure());
620 content::RunMessageLoop();
623 void SetScreenshotPolicy(bool enabled) {
625 policies.Set(key::kDisableScreenshots,
626 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
627 base::Value::CreateBooleanValue(!enabled), NULL);
628 UpdateProviderPolicy(policies);
631 #if defined(OS_CHROMEOS)
632 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
634 virtual void OnScreenshotCompleted(
635 ScreenshotTakerObserver::Result screenshot_result,
636 const base::FilePath& screenshot_path) OVERRIDE {
637 BrowserThread::PostTaskAndReply(BrowserThread::IO,
639 base::Bind(base::DoNothing),
640 base::MessageLoop::QuitClosure());
643 virtual ~QuitMessageLoopAfterScreenshot() {}
646 void TestScreenshotFile(bool enabled) {
647 // AddObserver is an ash-specific method, so just replace the screenshot
648 // taker with one we've created here.
649 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
650 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
651 // is tied to the test instead.
652 screenshot_taker->AddObserver(&observer_);
653 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
654 screenshot_taker.PassAs<ash::ScreenshotDelegate>());
656 SetScreenshotPolicy(enabled);
657 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
658 ash::TAKE_SCREENSHOT, ui::Accelerator());
660 content::RunMessageLoop();
664 ExtensionService* extension_service() {
665 extensions::ExtensionSystem* system =
666 extensions::ExtensionSystem::Get(browser()->profile());
667 return system->extension_service();
670 const extensions::Extension* InstallExtension(
671 const base::FilePath::StringType& name) {
672 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
673 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
674 scoped_refptr<extensions::CrxInstaller> installer =
675 extensions::CrxInstaller::CreateSilent(extension_service());
676 installer->set_allow_silent_install(true);
677 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
678 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
680 content::WindowedNotificationObserver observer(
681 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
682 content::NotificationService::AllSources());
683 installer->InstallCrx(extension_path);
685 content::Details<const extensions::Extension> details = observer.details();
686 return details.ptr();
689 const extensions::Extension* LoadUnpackedExtension(
690 const base::FilePath::StringType& name, bool expect_success) {
691 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
692 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
693 scoped_refptr<extensions::UnpackedInstaller> installer =
694 extensions::UnpackedInstaller::Create(extension_service());
695 content::WindowedNotificationObserver observer(
696 expect_success ? chrome::NOTIFICATION_EXTENSION_LOADED
697 : chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
698 content::NotificationService::AllSources());
699 installer->Load(extension_path);
702 const extensions::ExtensionSet* extensions =
703 extension_service()->extensions();
704 for (extensions::ExtensionSet::const_iterator it = extensions->begin();
705 it != extensions->end(); ++it) {
706 if ((*it)->path() == extension_path)
712 void UninstallExtension(const std::string& id, bool expect_success) {
713 content::WindowedNotificationObserver observer(
714 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED
715 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
716 content::NotificationService::AllSources());
717 extension_service()->UninstallExtension(id, false, NULL);
721 void UpdateProviderPolicy(const PolicyMap& policy) {
722 provider_.UpdateChromePolicy(policy);
723 DCHECK(base::MessageLoop::current());
728 // Sends a mouse click at the given coordinates to the current renderer.
729 void PerformClick(int x, int y) {
730 content::WebContents* contents =
731 browser()->tab_strip_model()->GetActiveWebContents();
732 blink::WebMouseEvent click_event;
733 click_event.type = blink::WebInputEvent::MouseDown;
734 click_event.button = blink::WebMouseEvent::ButtonLeft;
735 click_event.clickCount = 1;
738 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
739 click_event.type = blink::WebInputEvent::MouseUp;
740 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
743 MockConfigurationPolicyProvider provider_;
744 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
745 #if defined(OS_CHROMEOS)
746 QuitMessageLoopAfterScreenshot observer_;
751 // This policy only exists on Windows.
753 // Sets the locale policy before the browser is started.
754 class LocalePolicyTest : public PolicyTest {
756 LocalePolicyTest() {}
757 virtual ~LocalePolicyTest() {}
759 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
760 PolicyTest::SetUpInProcessBrowserTestFixture();
763 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
764 base::Value::CreateStringValue("fr"), NULL);
765 provider_.UpdateChromePolicy(policies);
766 // The "en-US" ResourceBundle is always loaded before this step for tests,
767 // but in this test we want the browser to load the bundle as it
769 ResourceBundle::CleanupSharedInstance();
773 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
774 // Verifies that the default locale can be overridden with policy.
775 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
776 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
777 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
778 base::string16 title;
779 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
780 EXPECT_EQ(french_title, title);
782 // Make sure this is really French and differs from the English title.
784 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
785 EXPECT_EQ("en-US", loaded);
786 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
787 EXPECT_NE(french_title, english_title);
791 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
792 #if defined(OS_WIN) && defined(USE_ASH)
793 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
794 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
798 // Verifies that the bookmarks bar can be forced to always or never show up.
800 // Test starts in about:blank.
801 PrefService* prefs = browser()->profile()->GetPrefs();
802 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
803 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
804 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
807 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
808 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
809 UpdateProviderPolicy(policies);
810 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
811 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar));
812 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
814 // The NTP has special handling of the bookmark bar.
815 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
816 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
818 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
819 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
820 UpdateProviderPolicy(policies);
821 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
822 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
823 // The bookmark bar is hidden in the NTP when disabled by policy.
824 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
827 UpdateProviderPolicy(policies);
828 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
829 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
830 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
831 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
834 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
835 // Verifies that cookies are deleted on shutdown. This test is split in 3
836 // parts because it spans 2 browser restarts.
838 Profile* profile = browser()->profile();
840 // No cookies at startup.
841 EXPECT_TRUE(content::GetCookies(profile, url).empty());
843 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
844 EXPECT_TRUE(content::SetCookie(profile, url, value));
845 // Verify it was set.
846 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
849 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
850 // Verify that the cookie persists across restarts.
851 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
852 // Now set the policy and the cookie should be gone after another restart.
854 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY,
855 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4), NULL);
856 UpdateProviderPolicy(policies);
859 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
860 // Verify that the cookie is gone.
861 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
864 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
865 MakeRequestFail make_request_fail("search.example");
867 // Verifies that a default search is made using the provider configured via
868 // policy. Also checks that default search can be completely disabled.
869 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
870 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
871 const std::string kAlternateURL0(
872 "http://search.example/search#q={searchTerms}");
873 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
874 const std::string kSearchTermsReplacementKey("zekey");
875 const std::string kImageURL("http://test.com/searchbyimage/upload");
876 const std::string kImageURLPostParams(
877 "image_content=content,image_url=http://test.com/test.png");
878 const std::string kNewTabURL("http://search.example/newtab");
880 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
881 browser()->profile());
882 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
883 TemplateURL* default_search = service->GetDefaultSearchProvider();
884 ASSERT_TRUE(default_search);
885 EXPECT_NE(kKeyword, default_search->keyword());
886 EXPECT_NE(kSearchURL, default_search->url());
888 default_search->alternate_urls().size() == 2 &&
889 default_search->alternate_urls()[0] == kAlternateURL0 &&
890 default_search->alternate_urls()[1] == kAlternateURL1 &&
891 default_search->search_terms_replacement_key() ==
892 kSearchTermsReplacementKey &&
893 default_search->image_url() == kImageURL &&
894 default_search->image_url_post_params() == kImageURLPostParams &&
895 default_search->new_tab_url() == kNewTabURL);
897 // Override the default search provider using policies.
899 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
900 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
901 policies.Set(key::kDefaultSearchProviderKeyword,
902 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
903 base::Value::CreateStringValue(kKeyword), NULL);
904 policies.Set(key::kDefaultSearchProviderSearchURL,
905 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
906 base::Value::CreateStringValue(kSearchURL), NULL);
907 base::ListValue* alternate_urls = new base::ListValue();
908 alternate_urls->AppendString(kAlternateURL0);
909 alternate_urls->AppendString(kAlternateURL1);
910 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
911 POLICY_SCOPE_USER, alternate_urls, NULL);
912 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
913 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
914 base::Value::CreateStringValue(kSearchTermsReplacementKey),
916 policies.Set(key::kDefaultSearchProviderImageURL,
917 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
918 base::Value::CreateStringValue(kImageURL),
920 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
921 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
922 base::Value::CreateStringValue(kImageURLPostParams),
924 policies.Set(key::kDefaultSearchProviderNewTabURL,
925 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
926 base::Value::CreateStringValue(kNewTabURL),
928 UpdateProviderPolicy(policies);
929 default_search = service->GetDefaultSearchProvider();
930 ASSERT_TRUE(default_search);
931 EXPECT_EQ(kKeyword, default_search->keyword());
932 EXPECT_EQ(kSearchURL, default_search->url());
933 EXPECT_EQ(2U, default_search->alternate_urls().size());
934 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
935 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
936 EXPECT_EQ(kSearchTermsReplacementKey,
937 default_search->search_terms_replacement_key());
938 EXPECT_EQ(kImageURL, default_search->image_url());
939 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
940 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
942 // Verify that searching from the omnibox uses kSearchURL.
943 chrome::FocusLocationBar(browser());
944 LocationBar* location_bar = browser()->window()->GetLocationBar();
945 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
946 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
947 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
948 content::WebContents* web_contents =
949 browser()->tab_strip_model()->GetActiveWebContents();
950 GURL expected("http://search.example/search?q=stuff+to+search+for");
951 EXPECT_EQ(expected, web_contents->GetURL());
953 // Verify that searching from the omnibox can be disabled.
954 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
955 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
956 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
957 EXPECT_TRUE(service->GetDefaultSearchProvider());
958 UpdateProviderPolicy(policies);
959 EXPECT_FALSE(service->GetDefaultSearchProvider());
960 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
961 // This means that submitting won't trigger any action.
962 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
963 EXPECT_EQ(GURL(content::kAboutBlankURL), web_contents->GetURL());
966 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
967 // Add an individual proxy policy value.
969 policies.Set(key::kProxyServerMode,
970 POLICY_LEVEL_MANDATORY,
972 base::Value::CreateIntegerValue(3),
974 UpdateProviderPolicy(policies);
976 // It should be removed and replaced with a dictionary.
978 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
979 expected_value->SetInteger(key::kProxyServerMode, 3);
980 expected.Set(key::kProxySettings,
981 POLICY_LEVEL_MANDATORY,
983 expected_value.release(),
986 // Check both the browser and the profile.
987 const PolicyMap& actual_from_browser =
988 g_browser_process->browser_policy_connector()
990 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
991 EXPECT_TRUE(expected.Equals(actual_from_browser));
992 const PolicyMap& actual_from_profile =
993 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
995 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
996 EXPECT_TRUE(expected.Equals(actual_from_profile));
999 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1000 // Makes the requests fail since all we want to check is that the redirection
1001 // is done properly.
1002 MakeRequestFail make_request_fail("google.com");
1004 // Verifies that requests to Google Search engine with the SafeSearch
1005 // enabled set the safe=active&ssui=on parameters at the end of the query.
1006 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1007 browser()->profile());
1008 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1010 // First check that nothing happens.
1011 content::TestNavigationObserver no_safesearch_observer(
1012 browser()->tab_strip_model()->GetActiveWebContents());
1013 chrome::FocusLocationBar(browser());
1014 LocationBar* location_bar = browser()->window()->GetLocationBar();
1015 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1016 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1017 no_safesearch_observer.Wait();
1018 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1019 content::WebContents* web_contents =
1020 browser()->tab_strip_model()->GetActiveWebContents();
1021 GURL expected_without("http://google.com/");
1022 EXPECT_EQ(expected_without, web_contents->GetURL());
1024 PrefService* prefs = browser()->profile()->GetPrefs();
1025 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1026 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1028 // Override the default SafeSearch setting using policies.
1030 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
1031 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1032 UpdateProviderPolicy(policies);
1034 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1035 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1037 content::TestNavigationObserver safesearch_observer(
1038 browser()->tab_strip_model()->GetActiveWebContents());
1040 // Verify that searching from google.com works.
1041 chrome::FocusLocationBar(browser());
1042 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1043 safesearch_observer.Wait();
1044 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1045 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1046 std::string expected_url("http://google.com/?");
1047 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1048 chrome::kSafeSearchSsuiParameter;
1049 GURL expected_with_parameters(expected_url);
1050 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1053 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1054 MakeRequestFail make_request_fail("search.example");
1056 chrome::EnableQueryExtractionForTesting();
1058 // Verifies that a default search is made using the provider configured via
1059 // policy. Also checks that default search can be completely disabled.
1060 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1061 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1062 const std::string kInstantURL("http://does/not/exist");
1063 const std::string kAlternateURL0(
1064 "https://www.google.com/search#q={searchTerms}");
1065 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1066 const std::string kSearchTermsReplacementKey(
1067 "{google:instantExtendedEnabledKey}");
1069 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1070 browser()->profile());
1071 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1072 TemplateURL* default_search = service->GetDefaultSearchProvider();
1073 ASSERT_TRUE(default_search);
1074 EXPECT_NE(kKeyword, default_search->keyword());
1075 EXPECT_NE(kSearchURL, default_search->url());
1076 EXPECT_NE(kInstantURL, default_search->instant_url());
1078 default_search->alternate_urls().size() == 2 &&
1079 default_search->alternate_urls()[0] == kAlternateURL0 &&
1080 default_search->alternate_urls()[1] == kAlternateURL1);
1082 // Override the default search provider using policies.
1084 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1085 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1086 policies.Set(key::kDefaultSearchProviderKeyword,
1087 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1088 base::Value::CreateStringValue(kKeyword), NULL);
1089 policies.Set(key::kDefaultSearchProviderSearchURL,
1090 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1091 base::Value::CreateStringValue(kSearchURL), NULL);
1092 policies.Set(key::kDefaultSearchProviderInstantURL,
1093 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1094 base::Value::CreateStringValue(kInstantURL), NULL);
1095 base::ListValue* alternate_urls = new base::ListValue();
1096 alternate_urls->AppendString(kAlternateURL0);
1097 alternate_urls->AppendString(kAlternateURL1);
1098 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1099 POLICY_SCOPE_USER, alternate_urls, NULL);
1100 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1101 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1102 base::Value::CreateStringValue(kSearchTermsReplacementKey),
1104 UpdateProviderPolicy(policies);
1105 default_search = service->GetDefaultSearchProvider();
1106 ASSERT_TRUE(default_search);
1107 EXPECT_EQ(kKeyword, default_search->keyword());
1108 EXPECT_EQ(kSearchURL, default_search->url());
1109 EXPECT_EQ(kInstantURL, default_search->instant_url());
1110 EXPECT_EQ(2U, default_search->alternate_urls().size());
1111 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1112 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1114 // Query terms replacement requires that the renderer process be a recognized
1115 // Instant renderer. Fake it.
1116 InstantService* instant_service =
1117 InstantServiceFactory::GetForProfile(browser()->profile());
1118 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1119 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1121 // Verify that searching from the omnibox does search term replacement with
1122 // first URL pattern.
1123 chrome::FocusLocationBar(browser());
1124 LocationBar* location_bar = browser()->window()->GetLocationBar();
1125 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1126 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1127 "https://www.google.com/?espv=1#q=foobar");
1129 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1130 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1132 // Verify that not using espv=1 does not do search term replacement.
1133 chrome::FocusLocationBar(browser());
1134 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1135 "https://www.google.com/?q=foobar");
1137 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1138 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1139 omnibox_view->GetText());
1141 // Verify that searching from the omnibox does search term replacement with
1142 // second URL pattern.
1143 chrome::FocusLocationBar(browser());
1144 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1145 "https://www.google.com/search?espv=1#q=banana");
1147 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1148 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1150 // Verify that searching from the omnibox does search term replacement with
1151 // standard search URL pattern.
1152 chrome::FocusLocationBar(browser());
1153 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1154 "https://www.google.com/search?q=tractor+parts&espv=1");
1156 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1157 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1159 // Verify that searching from the omnibox prioritizes hash over query.
1160 chrome::FocusLocationBar(browser());
1161 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1162 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1164 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1165 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1168 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1169 // This test assumes Gpu access.
1170 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1173 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1174 // WebGL is enabled by default.
1175 content::WebContents* contents =
1176 browser()->tab_strip_model()->GetActiveWebContents();
1177 EXPECT_TRUE(IsWebGLEnabled(contents));
1178 // Disable with a policy.
1180 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1181 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1182 UpdateProviderPolicy(policies);
1183 // Crash and reload the tab to get a new renderer.
1184 content::CrashTab(contents);
1185 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1186 EXPECT_FALSE(IsWebGLEnabled(contents));
1187 // Enable with a policy.
1188 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1189 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1190 UpdateProviderPolicy(policies);
1191 content::CrashTab(contents);
1192 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1193 EXPECT_TRUE(IsWebGLEnabled(contents));
1196 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1197 // Verifies that SPDY can be disable by policy.
1198 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1200 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1201 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1202 UpdateProviderPolicy(policies);
1203 content::RunAllPendingInMessageLoop();
1204 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1205 // Verify that it can be force-enabled too.
1206 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1207 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1208 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1209 UpdateProviderPolicy(policies);
1210 content::RunAllPendingInMessageLoop();
1211 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1214 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1215 // Verifies that plugins can be forced to be disabled by policy.
1217 // Verify that the Flash plugin exists and that it can be enabled and disabled
1219 std::vector<content::WebPluginInfo> plugins;
1220 GetPluginList(&plugins);
1221 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1224 PluginPrefs* plugin_prefs =
1225 PluginPrefs::GetForProfile(browser()->profile()).get();
1226 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1227 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1228 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1229 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1230 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1232 // Now disable it with a policy.
1233 base::ListValue disabled_plugins;
1234 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
1236 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1237 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1238 UpdateProviderPolicy(policies);
1239 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1240 // The user shouldn't be able to enable it.
1241 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1242 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1245 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1246 // Verifies that plugins with an exception in the blacklist can be enabled.
1248 // Verify that the Flash plugin exists and that it can be enabled and disabled
1250 std::vector<content::WebPluginInfo> plugins;
1251 GetPluginList(&plugins);
1252 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1255 PluginPrefs* plugin_prefs =
1256 PluginPrefs::GetForProfile(browser()->profile()).get();
1257 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1259 // Disable all plugins.
1260 base::ListValue disabled_plugins;
1261 disabled_plugins.Append(base::Value::CreateStringValue("*"));
1263 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1264 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1265 UpdateProviderPolicy(policies);
1266 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1267 // The user shouldn't be able to enable it.
1268 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1269 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1271 // Now open an exception for flash.
1272 base::ListValue disabled_plugins_exceptions;
1273 disabled_plugins_exceptions.Append(
1274 base::Value::CreateStringValue("*Flash*"));
1275 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1276 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1277 UpdateProviderPolicy(policies);
1278 // It should revert to the user's preference automatically.
1279 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1280 // And the user should be able to disable and enable again.
1281 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1282 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1283 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1284 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1287 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1288 // Verifies that a plugin can be force-installed with a policy.
1289 std::vector<content::WebPluginInfo> plugins;
1290 GetPluginList(&plugins);
1291 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1294 PluginPrefs* plugin_prefs =
1295 PluginPrefs::GetForProfile(browser()->profile()).get();
1296 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1298 // The user disables it and then a policy forces it to be enabled.
1299 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1300 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1301 base::ListValue plugin_list;
1302 plugin_list.Append(base::Value::CreateStringValue(content::kFlashPluginName));
1304 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1305 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1306 UpdateProviderPolicy(policies);
1307 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1308 // The user can't disable it anymore.
1309 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1310 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1312 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1313 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1314 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1315 UpdateProviderPolicy(policies);
1316 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1319 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1320 // Verifies that dangerous plugins can be always authorized to run with
1323 // Verify that the test page exists. It is only present in checkouts with
1325 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1326 base::FilePath(FILE_PATH_LITERAL("plugin")),
1327 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1329 "Test skipped because plugin/quicktime.html test file wasn't found.";
1333 ServeContentTestData();
1334 // No plugins at startup.
1335 EXPECT_EQ(0, CountPlugins());
1337 content::WebContents* contents =
1338 browser()->tab_strip_model()->GetActiveWebContents();
1339 ASSERT_TRUE(contents);
1340 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1341 ASSERT_TRUE(infobar_service);
1342 EXPECT_EQ(0u, infobar_service->infobar_count());
1344 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1345 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1346 ui_test_utils::NavigateToURL(browser(), url);
1347 // This should have triggered the dangerous plugin infobar.
1348 ASSERT_EQ(1u, infobar_service->infobar_count());
1350 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1351 // And the plugin isn't running.
1352 EXPECT_EQ(0, CountPlugins());
1354 // Now set a policy to always authorize this.
1356 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1357 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1358 UpdateProviderPolicy(policies);
1359 // Reloading the page shouldn't trigger the infobar this time.
1360 ui_test_utils::NavigateToURL(browser(), url);
1361 EXPECT_EQ(0u, infobar_service->infobar_count());
1362 // And the plugin started automatically.
1363 EXPECT_EQ(1, CountPlugins());
1366 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1367 // Verifies that access to the developer tools can be disabled.
1370 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1371 content::WebContents* contents =
1372 browser()->tab_strip_model()->GetActiveWebContents();
1373 DevToolsWindow *devtools_window =
1374 DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1375 contents->GetRenderViewHost());
1376 EXPECT_TRUE(devtools_window);
1378 // Disable devtools via policy.
1380 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1381 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1382 content::WindowedNotificationObserver close_observer(
1383 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1384 content::Source<content::WebContents>(devtools_window->web_contents()));
1385 UpdateProviderPolicy(policies);
1386 // wait for devtools close
1387 close_observer.Wait();
1388 // The existing devtools window should have closed.
1389 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1390 contents->GetRenderViewHost()));
1391 // And it's not possible to open it again.
1392 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1393 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1394 contents->GetRenderViewHost()));
1397 // TODO(samarth): remove along with rest of NTP4 code.
1398 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1399 #if defined(OS_WIN) && defined(USE_ASH)
1400 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1401 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1405 // Verifies that the web store icons can be hidden from the new tab page.
1407 // Open new tab page and look for the web store icons.
1408 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1409 content::WebContents* contents =
1410 browser()->tab_strip_model()->GetActiveWebContents();
1412 #if !defined(OS_CHROMEOS)
1413 // Look for web store's app ID in the apps page.
1414 EXPECT_TRUE(ContainsVisibleElement(contents,
1415 "ahfgeienlihckogmohjhadlkjgocpleb"));
1418 // The next NTP has no footer.
1419 if (ContainsVisibleElement(contents, "footer"))
1420 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1422 // Turn off the web store icons.
1424 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
1425 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1426 UpdateProviderPolicy(policies);
1428 // The web store icons should now be hidden.
1429 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1430 EXPECT_FALSE(ContainsVisibleElement(contents,
1431 "ahfgeienlihckogmohjhadlkjgocpleb"));
1432 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1435 // This policy isn't available on Chrome OS.
1436 #if !defined(OS_CHROMEOS)
1437 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1438 // Verifies that the download directory can be forced by policy.
1440 // Set the initial download directory.
1441 base::ScopedTempDir initial_dir;
1442 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1443 browser()->profile()->GetPrefs()->SetFilePath(
1444 prefs::kDownloadDefaultDirectory, initial_dir.path());
1445 // Don't prompt for the download location during this test.
1446 browser()->profile()->GetPrefs()->SetBoolean(
1447 prefs::kPromptForDownload, false);
1449 // Verify that downloads end up on the default directory.
1450 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1451 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1452 file_util::DieFileDie(initial_dir.path().Append(file), false);
1454 // Override the download directory with the policy and verify a download.
1455 base::ScopedTempDir forced_dir;
1456 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1458 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1460 base::Value::CreateStringValue(forced_dir.path().value()), NULL);
1461 UpdateProviderPolicy(policies);
1462 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1463 // Verify that the first download location wasn't affected.
1464 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1468 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1469 // Verifies that blacklisted extensions can't be installed.
1470 ExtensionService* service = extension_service();
1471 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1472 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1473 base::ListValue blacklist;
1474 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1476 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1477 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1478 UpdateProviderPolicy(policies);
1480 // "good.crx" is blacklisted.
1481 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1482 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1484 // "adblock.crx" is not.
1485 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1486 ASSERT_TRUE(adblock);
1487 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1489 service->GetExtensionById(kAdBlockCrxId, true));
1492 // Flaky on windows; http://crbug.com/307994.
1494 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1496 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1498 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1499 // Verify that a wildcard blacklist takes effect.
1500 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1501 ExtensionService* service = extension_service();
1502 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1503 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1504 base::ListValue blacklist;
1505 blacklist.Append(base::Value::CreateStringValue("*"));
1507 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1508 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1509 UpdateProviderPolicy(policies);
1511 // AdBlock was automatically removed.
1512 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1514 // And can't be installed again, nor can good.crx.
1515 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1516 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1517 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1518 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1521 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1522 // Verifies that the whitelist can open exceptions to the blacklist.
1523 ExtensionService* service = extension_service();
1524 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1525 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1526 base::ListValue blacklist;
1527 blacklist.Append(base::Value::CreateStringValue("*"));
1528 base::ListValue whitelist;
1529 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1531 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1532 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1533 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1534 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1535 UpdateProviderPolicy(policies);
1536 // "adblock.crx" is blacklisted.
1537 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1538 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1539 // "good.crx" has a whitelist exception.
1540 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1542 EXPECT_EQ(kGoodCrxId, good->id());
1543 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1544 // The user can also remove this extension.
1545 UninstallExtension(kGoodCrxId, true);
1548 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1549 // Verifies that extensions that are force-installed by policies are
1550 // installed and can't be uninstalled.
1551 ExtensionService* service = extension_service();
1552 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1554 // Extensions that are force-installed come from an update URL, which defaults
1555 // to the webstore. Use a mock URL for this test with an update manifest
1556 // that includes "good_v1.crx".
1557 base::FilePath path =
1558 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1559 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1561 // Setting the forcelist extension should install "good_v1.crx".
1562 base::ListValue forcelist;
1563 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf(
1564 "%s;%s", kGoodCrxId, url.spec().c_str())));
1566 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1567 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1568 content::WindowedNotificationObserver observer(
1569 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1570 content::NotificationService::AllSources());
1571 UpdateProviderPolicy(policies);
1573 // Note: Cannot check that the notification details match the expected
1574 // exception, since the details object has already been freed prior to
1575 // the completion of observer.Wait().
1577 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1579 // The user is not allowed to uninstall force-installed extensions.
1580 UninstallExtension(kGoodCrxId, false);
1582 // The user is not allowed to load an unpacked extension with the
1583 // same ID as a force-installed extension.
1584 LoadUnpackedExtension(kGoodUnpackedExt, false);
1586 // Loading other unpacked extensions are not blocked.
1587 LoadUnpackedExtension(kAppUnpackedExt, true);
1589 const std::string old_version_number =
1590 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1592 base::FilePath test_path;
1593 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1595 TestRequestInterceptor interceptor(
1597 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1598 interceptor.PushJobCallback(
1599 TestRequestInterceptor::FileJob(
1600 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1602 // Updating the force-installed extension.
1603 extensions::ExtensionUpdater* updater = service->updater();
1604 extensions::ExtensionUpdater::CheckParams params;
1605 params.install_immediately = true;
1606 content::WindowedNotificationObserver update_observer(
1607 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1608 content::NotificationService::AllSources());
1609 updater->CheckNow(params);
1610 update_observer.Wait();
1612 const base::Version* new_version =
1613 service->GetExtensionById(kGoodCrxId, true)->version();
1614 ASSERT_TRUE(new_version->IsValid());
1615 base::Version old_version(old_version_number);
1616 ASSERT_TRUE(old_version.IsValid());
1618 EXPECT_EQ(1, new_version->CompareTo(old_version));
1620 EXPECT_EQ(0u, interceptor.GetPendingSize());
1622 // Wait until any background pages belonging to force-installed extensions
1623 // have been loaded.
1624 extensions::ProcessManager* manager =
1625 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1626 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1627 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1629 iter != all_views.end();) {
1630 if (!(*iter)->IsLoading()) {
1633 content::WebContents* web_contents =
1634 content::WebContents::FromRenderViewHost(*iter);
1635 ASSERT_TRUE(web_contents);
1636 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1638 // Test activity may have modified the set of extension processes during
1639 // message processing, so re-start the iteration to catch added/removed
1641 all_views = manager->GetAllViews();
1642 iter = all_views.begin();
1646 // Test policy-installed extensions are reloaded when killed.
1647 BackgroundContentsService::
1648 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1649 content::WindowedNotificationObserver extension_crashed_observer(
1650 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1651 content::NotificationService::AllSources());
1652 content::WindowedNotificationObserver extension_loaded_observer(
1653 chrome::NOTIFICATION_EXTENSION_LOADED,
1654 content::NotificationService::AllSources());
1655 extensions::ExtensionHost* extension_host =
1656 extensions::ExtensionSystem::Get(browser()->profile())->
1657 process_manager()->GetBackgroundHostForExtension(kGoodCrxId);
1658 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1659 content::RESULT_CODE_KILLED, false);
1660 extension_crashed_observer.Wait();
1661 extension_loaded_observer.Wait();
1664 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1665 // Verifies that extensions are blocked if policy specifies an allowed types
1666 // list and the extension's type is not on that list.
1667 ExtensionService* service = extension_service();
1668 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1669 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1671 base::ListValue allowed_types;
1672 allowed_types.AppendString("hosted_app");
1674 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1675 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1676 UpdateProviderPolicy(policies);
1678 // "good.crx" is blocked.
1679 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1680 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1682 // "hosted_app.crx" is of a whitelisted type.
1683 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1684 ASSERT_TRUE(hosted_app);
1685 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1686 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1688 // The user can remove the extension.
1689 UninstallExtension(kHostedAppCrxId, true);
1692 // Checks that a click on an extension CRX download triggers the extension
1693 // installation prompt without further user interaction when the source is
1694 // whitelisted by policy.
1695 // Flaky on windows; http://crbug.com/295729 .
1697 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1699 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1701 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1702 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1703 switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
1705 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1706 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1707 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1708 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1710 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1711 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1712 ui_test_utils::NavigateToURL(browser(), download_page_url);
1714 // As long as the policy is not present, extensions are considered dangerous.
1715 content::DownloadTestObserverTerminal download_observer(
1716 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1717 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1719 download_observer.WaitForFinished();
1721 // Install the policy and trigger another download.
1722 base::ListValue install_sources;
1723 install_sources.AppendString(install_source_url.spec());
1724 install_sources.AppendString(referrer_url.spec());
1726 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1727 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1728 UpdateProviderPolicy(policies);
1730 content::WindowedNotificationObserver observer(
1731 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1732 content::NotificationService::AllSources());
1735 // Note: Cannot check that the notification details match the expected
1736 // exception, since the details object has already been freed prior to
1737 // the completion of observer.Wait().
1739 // The first extension shouldn't be present, the second should be there.
1740 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1741 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1744 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1745 #if defined(OS_WIN) && defined(USE_ASH)
1746 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1747 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1751 // Verifies that the homepage can be configured with policies.
1752 // Set a default, and check that the home button navigates there.
1753 browser()->profile()->GetPrefs()->SetString(
1754 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1755 browser()->profile()->GetPrefs()->SetBoolean(
1756 prefs::kHomePageIsNewTabPage, false);
1757 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1758 browser()->profile()->GetHomePage());
1759 content::WebContents* contents =
1760 browser()->tab_strip_model()->GetActiveWebContents();
1761 EXPECT_EQ(GURL(content::kAboutBlankURL), contents->GetURL());
1762 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1763 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1765 // Now override with policy.
1767 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1769 base::Value::CreateStringValue(chrome::kChromeUICreditsURL),
1771 UpdateProviderPolicy(policies);
1772 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1773 content::WaitForLoadStop(contents);
1774 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1776 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1777 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1778 UpdateProviderPolicy(policies);
1779 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1780 content::WaitForLoadStop(contents);
1781 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1784 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1785 // Verifies that incognito windows can't be opened when disabled by policy.
1787 const BrowserList* active_browser_list =
1788 BrowserList::GetInstance(chrome::GetActiveDesktop());
1790 // Disable incognito via policy and verify that incognito windows can't be
1792 EXPECT_EQ(1u, active_browser_list->size());
1793 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1795 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1796 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1797 UpdateProviderPolicy(policies);
1798 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1799 EXPECT_EQ(1u, active_browser_list->size());
1800 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1802 // Enable via policy and verify that incognito windows can be opened.
1803 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1804 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1805 UpdateProviderPolicy(policies);
1806 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1807 EXPECT_EQ(2u, active_browser_list->size());
1808 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1811 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1812 // Verifies that Javascript can be disabled.
1813 content::WebContents* contents =
1814 browser()->tab_strip_model()->GetActiveWebContents();
1815 EXPECT_TRUE(IsJavascriptEnabled(contents));
1816 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1817 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1818 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1820 // Disable Javascript via policy.
1822 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1823 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1824 UpdateProviderPolicy(policies);
1826 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1827 EXPECT_FALSE(IsJavascriptEnabled(contents));
1828 // Developer tools still work when javascript is disabled.
1829 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1830 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1831 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1832 // Javascript is always enabled for the internal pages.
1833 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1834 EXPECT_TRUE(IsJavascriptEnabled(contents));
1836 // The javascript content setting policy overrides the javascript policy.
1837 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1838 EXPECT_FALSE(IsJavascriptEnabled(contents));
1839 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1841 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL);
1842 UpdateProviderPolicy(policies);
1843 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1844 EXPECT_TRUE(IsJavascriptEnabled(contents));
1847 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1848 // Verifies that browsing history is not saved.
1850 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1851 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1852 UpdateProviderPolicy(policies);
1853 GURL url = ui_test_utils::GetTestUrl(
1854 base::FilePath(base::FilePath::kCurrentDirectory),
1855 base::FilePath(FILE_PATH_LITERAL("empty.html")));
1856 ui_test_utils::NavigateToURL(browser(), url);
1857 // Verify that the navigation wasn't saved in the history.
1858 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1859 EXPECT_EQ(0u, enumerator1.urls().size());
1861 // Now flip the policy and try again.
1862 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1863 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1864 UpdateProviderPolicy(policies);
1865 ui_test_utils::NavigateToURL(browser(), url);
1866 // Verify that the navigation was saved in the history.
1867 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1868 ASSERT_EQ(1u, enumerator2.urls().size());
1869 EXPECT_EQ(url, enumerator2.urls()[0]);
1872 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
1873 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
1874 TranslateService::SetUseInfobar(true);
1876 // Verifies that translate can be forced enabled or disabled by policy.
1878 // Get the InfoBarService, and verify that there are no infobars on startup.
1879 content::WebContents* contents =
1880 browser()->tab_strip_model()->GetActiveWebContents();
1881 ASSERT_TRUE(contents);
1882 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1883 ASSERT_TRUE(infobar_service);
1884 EXPECT_EQ(0u, infobar_service->infobar_count());
1886 // Force enable the translate feature.
1888 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1889 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1890 UpdateProviderPolicy(policies);
1891 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
1892 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
1893 // TranslateManager observes. This allows checking that an infobar is NOT
1894 // shown below, without polling for infobars for some indeterminate amount
1896 GURL url = ui_test_utils::GetTestUrl(
1898 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
1899 content::WindowedNotificationObserver language_observer1(
1900 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1901 content::NotificationService::AllSources());
1902 ui_test_utils::NavigateToURL(browser(), url);
1903 language_observer1.Wait();
1905 // Verify the translation detected for this tab.
1906 TranslateTabHelper* translate_tab_helper =
1907 TranslateTabHelper::FromWebContents(contents);
1908 ASSERT_TRUE(translate_tab_helper);
1909 LanguageState& language_state = translate_tab_helper->GetLanguageState();
1910 EXPECT_EQ("fr", language_state.original_language());
1911 EXPECT_TRUE(language_state.page_needs_translation());
1912 EXPECT_FALSE(language_state.translation_pending());
1913 EXPECT_FALSE(language_state.translation_declined());
1914 EXPECT_FALSE(language_state.IsPageTranslated());
1916 // Verify that the translate infobar showed up.
1917 ASSERT_EQ(1u, infobar_service->infobar_count());
1918 InfoBar* infobar = infobar_service->infobar_at(0);
1919 TranslateInfoBarDelegate* translate_infobar_delegate =
1920 infobar->delegate()->AsTranslateInfoBarDelegate();
1921 ASSERT_TRUE(translate_infobar_delegate);
1922 EXPECT_EQ(TranslateTabHelper::BEFORE_TRANSLATE,
1923 translate_infobar_delegate->translate_step());
1924 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
1926 // Now force disable translate.
1927 infobar_service->RemoveInfoBar(infobar);
1928 EXPECT_EQ(0u, infobar_service->infobar_count());
1929 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1930 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1931 UpdateProviderPolicy(policies);
1932 // Navigating to the same URL now doesn't trigger an infobar.
1933 content::WindowedNotificationObserver language_observer2(
1934 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1935 content::NotificationService::AllSources());
1936 ui_test_utils::NavigateToURL(browser(), url);
1937 language_observer2.Wait();
1938 EXPECT_EQ(0u, infobar_service->infobar_count());
1941 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
1942 // Checks that URLs can be blacklisted, and that exceptions can be made to
1945 // Filter |kURLS| on IO thread, so that requests to those hosts end up
1946 // as URLRequestMockHTTPJobs.
1947 const char* kURLS[] = {
1948 "http://aaa.com/empty.html",
1949 "http://bbb.com/empty.html",
1950 "http://sub.bbb.com/empty.html",
1951 "http://bbb.com/policy/blank.html",
1955 BrowserThread::PostTaskAndReply(
1956 BrowserThread::IO, FROM_HERE,
1957 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
1958 loop.QuitClosure());
1962 // Verify that "bbb.com" opens before applying the blacklist.
1963 CheckCanOpenURL(browser(), kURLS[1]);
1966 base::ListValue blacklist;
1967 blacklist.Append(base::Value::CreateStringValue("bbb.com"));
1969 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1970 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1971 UpdateProviderPolicy(policies);
1972 FlushBlacklistPolicy();
1973 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
1974 CheckCanOpenURL(browser(), kURLS[0]);
1975 for (size_t i = 1; i < arraysize(kURLS); ++i)
1976 CheckURLIsBlocked(browser(), kURLS[i]);
1978 // Whitelist some sites of bbb.com.
1979 base::ListValue whitelist;
1980 whitelist.Append(base::Value::CreateStringValue("sub.bbb.com"));
1981 whitelist.Append(base::Value::CreateStringValue("bbb.com/policy"));
1982 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1983 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1984 UpdateProviderPolicy(policies);
1985 FlushBlacklistPolicy();
1986 CheckURLIsBlocked(browser(), kURLS[1]);
1987 CheckCanOpenURL(browser(), kURLS[2]);
1988 CheckCanOpenURL(browser(), kURLS[3]);
1992 BrowserThread::PostTaskAndReply(
1993 BrowserThread::IO, FROM_HERE,
1994 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
1995 loop.QuitClosure());
2000 // This test is flaky on all platforms; see http://crbug.com/339240
2001 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_FileURLBlacklist) {
2002 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2003 // with URLblacklisting and URLwhitelisting.
2005 base::FilePath test_path;
2006 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2007 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2008 const std::string folder_path = base_path + "apptest/";
2009 const std::string file_path1 = base_path + "title1.html";
2010 const std::string file_path2 = folder_path + "basic.html";
2012 CheckCanOpenURL(browser(), file_path1.c_str());
2013 CheckCanOpenURL(browser(), file_path2.c_str());
2015 // Set a blacklist for all the files.
2016 base::ListValue blacklist;
2017 blacklist.Append(base::Value::CreateStringValue("file://*"));
2019 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2020 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2021 UpdateProviderPolicy(policies);
2022 FlushBlacklistPolicy();
2024 CheckURLIsBlocked(browser(), file_path1.c_str());
2025 CheckURLIsBlocked(browser(), file_path2.c_str());
2027 // Replace the URLblacklist with disabling the file scheme.
2028 blacklist.Remove(base::StringValue("file://*"), NULL);
2029 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2030 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2031 UpdateProviderPolicy(policies);
2032 FlushBlacklistPolicy();
2034 PrefService* prefs = browser()->profile()->GetPrefs();
2035 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2036 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2039 base::ListValue disabledscheme;
2040 disabledscheme.Append(base::Value::CreateStringValue("file"));
2041 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2042 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2043 UpdateProviderPolicy(policies);
2044 FlushBlacklistPolicy();
2046 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2047 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2050 // Whitelist one folder and blacklist an another just inside.
2051 base::ListValue whitelist;
2052 whitelist.Append(base::Value::CreateStringValue(base_path));
2053 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2054 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2055 blacklist.Append(base::Value::CreateStringValue(folder_path));
2056 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2057 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2058 UpdateProviderPolicy(policies);
2059 FlushBlacklistPolicy();
2061 CheckCanOpenURL(browser(), file_path1.c_str());
2062 CheckURLIsBlocked(browser(), file_path2.c_str());
2065 #if !defined(OS_MACOSX)
2066 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2068 policies.Set(key::kFullscreenAllowed,
2069 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2070 base::Value::CreateBooleanValue(false), NULL);
2071 UpdateProviderPolicy(policies);
2073 BrowserWindow* browser_window = browser()->window();
2074 ASSERT_TRUE(browser_window);
2076 EXPECT_FALSE(browser_window->IsFullscreen());
2077 chrome::ToggleFullscreenMode(browser());
2078 EXPECT_FALSE(browser_window->IsFullscreen());
2081 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2083 policies.Set(key::kFullscreenAllowed,
2084 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2085 base::Value::CreateBooleanValue(false), NULL);
2086 UpdateProviderPolicy(policies);
2088 const extensions::Extension* extension =
2089 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2090 ASSERT_TRUE(extension);
2092 // Launch an app that tries to open a fullscreen window.
2093 TestAddAppWindowObserver add_window_observer(
2094 apps::AppWindowRegistry::Get(browser()->profile()));
2095 OpenApplication(AppLaunchParams(browser()->profile(),
2097 extensions::LAUNCH_CONTAINER_NONE,
2099 apps::AppWindow* window = add_window_observer.WaitForAppWindow();
2100 ASSERT_TRUE(window);
2102 // Verify that the window is not in fullscreen mode.
2103 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2105 // Verify that the window cannot be toggled into fullscreen mode via apps
2107 EXPECT_TRUE(content::ExecuteScript(
2108 window->web_contents(),
2109 "chrome.app.window.current().fullscreen();"));
2110 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2112 // Verify that the window cannot be toggled into fullscreen mode from within
2113 // Chrome (e.g., using keyboard accelerators).
2114 window->Fullscreen();
2115 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2119 #if defined(OS_CHROMEOS)
2120 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2121 int screenshot_count = CountScreenshots();
2123 // Make sure screenshots are counted correctly.
2124 TestScreenshotFile(true);
2125 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2127 // Check if trying to take a screenshot fails when disabled by policy.
2128 TestScreenshotFile(false);
2129 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2132 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2133 // Set up the mock observer.
2134 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2135 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2136 audio_handler->AddAudioObserver(test_observer.get());
2138 bool prior_state = audio_handler->IsOutputMuted();
2139 // Make sure the audio is not muted and then toggle the policy and observe
2140 // if the output mute changed event is fired.
2141 audio_handler->SetOutputMute(false);
2142 EXPECT_FALSE(audio_handler->IsOutputMuted());
2143 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2145 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2146 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
2147 UpdateProviderPolicy(policies);
2148 EXPECT_TRUE(audio_handler->IsOutputMuted());
2149 // This should not change the state now and should not trigger output mute
2151 audio_handler->SetOutputMute(false);
2152 EXPECT_TRUE(audio_handler->IsOutputMuted());
2153 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2155 // Toggle back and observe if the output mute changed event is fired.
2156 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2157 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
2158 UpdateProviderPolicy(policies);
2159 EXPECT_FALSE(audio_handler->IsOutputMuted());
2160 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2161 audio_handler->SetOutputMute(true);
2162 EXPECT_TRUE(audio_handler->IsOutputMuted());
2163 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2164 // Revert the prior state.
2165 audio_handler->SetOutputMute(prior_state);
2166 audio_handler->RemoveAudioObserver(test_observer.get());
2169 // Disabled, see http://crbug.com/315308.
2170 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2171 // Indicate that the session started 2 hours ago and no user activity has
2173 g_browser_process->local_state()->SetInt64(
2174 prefs::kSessionStartTime,
2175 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2176 .ToInternalValue());
2179 // Disabled, see http://crbug.com/315308.
2180 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2181 content::MockNotificationObserver observer;
2182 content::NotificationRegistrar registrar;
2183 registrar.Add(&observer,
2184 chrome::NOTIFICATION_APP_TERMINATING,
2185 content::NotificationService::AllSources());
2187 // Set the session length limit to 3 hours. Verify that the session is not
2189 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2192 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2194 base::Value::CreateIntegerValue(kThreeHoursInMs),
2196 UpdateProviderPolicy(policies);
2197 base::RunLoop().RunUntilIdle();
2198 Mock::VerifyAndClearExpectations(&observer);
2200 // Decrease the session length limit to 1 hour. Verify that the session is
2201 // terminated immediately.
2202 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2203 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2205 base::Value::CreateIntegerValue(kOneHourInMs),
2207 UpdateProviderPolicy(policies);
2208 base::RunLoop().RunUntilIdle();
2209 Mock::VerifyAndClearExpectations(&observer);
2212 // Disabled, see http://crbug.com/315308.
2213 IN_PROC_BROWSER_TEST_F(PolicyTest,
2214 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2215 // Indicate that the session started 2 hours ago and no user activity has
2217 g_browser_process->local_state()->SetInt64(
2218 prefs::kSessionStartTime,
2219 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2220 .ToInternalValue());
2223 // Disabled, see http://crbug.com/315308.
2224 IN_PROC_BROWSER_TEST_F(PolicyTest,
2225 DISABLED_WaitForInitialUserActivityUsatisfied) {
2226 content::MockNotificationObserver observer;
2227 content::NotificationRegistrar registrar;
2228 registrar.Add(&observer,
2229 chrome::NOTIFICATION_APP_TERMINATING,
2230 content::NotificationService::AllSources());
2232 // Require initial user activity.
2234 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2236 new base::FundamentalValue(true),
2238 UpdateProviderPolicy(policies);
2239 base::RunLoop().RunUntilIdle();
2241 // Set the session length limit to 1 hour. Verify that the session is not
2243 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2245 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2247 base::Value::CreateIntegerValue(kOneHourInMs),
2249 UpdateProviderPolicy(policies);
2250 base::RunLoop().RunUntilIdle();
2251 Mock::VerifyAndClearExpectations(&observer);
2254 // Disabled, see http://crbug.com/315308.
2255 IN_PROC_BROWSER_TEST_F(PolicyTest,
2256 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2257 // Indicate that initial user activity in this session occurred 2 hours ago.
2258 g_browser_process->local_state()->SetInt64(
2259 prefs::kSessionStartTime,
2260 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2261 .ToInternalValue());
2262 g_browser_process->local_state()->SetBoolean(
2263 prefs::kSessionUserActivitySeen,
2267 // Disabled, see http://crbug.com/315308.
2268 IN_PROC_BROWSER_TEST_F(PolicyTest,
2269 DISABLED_WaitForInitialUserActivitySatisfied) {
2270 content::MockNotificationObserver observer;
2271 content::NotificationRegistrar registrar;
2272 registrar.Add(&observer,
2273 chrome::NOTIFICATION_APP_TERMINATING,
2274 content::NotificationService::AllSources());
2276 // Require initial user activity and set the session length limit to 3 hours.
2277 // Verify that the session is not terminated.
2278 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2281 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2283 new base::FundamentalValue(true),
2285 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2287 base::Value::CreateIntegerValue(kThreeHoursInMs),
2289 UpdateProviderPolicy(policies);
2290 base::RunLoop().RunUntilIdle();
2291 Mock::VerifyAndClearExpectations(&observer);
2293 // Decrease the session length limit to 1 hour. Verify that the session is
2294 // terminated immediately.
2295 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2296 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2298 base::Value::CreateIntegerValue(kOneHourInMs),
2300 UpdateProviderPolicy(policies);
2301 base::RunLoop().RunUntilIdle();
2302 Mock::VerifyAndClearExpectations(&observer);
2305 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2306 // Verifies that the large cursor accessibility feature can be controlled
2308 chromeos::AccessibilityManager* accessibility_manager =
2309 chromeos::AccessibilityManager::Get();
2311 // Manually enable the large cursor.
2312 accessibility_manager->EnableLargeCursor(true);
2313 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2315 // Verify that policy overrides the manual setting.
2317 policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY,
2319 base::Value::CreateBooleanValue(false), NULL);
2320 UpdateProviderPolicy(policies);
2321 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2323 // Verify that the large cursor cannot be enabled manually anymore.
2324 accessibility_manager->EnableLargeCursor(true);
2325 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2328 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2329 // Verifies that the spoken feedback accessibility feature can be controlled
2331 chromeos::AccessibilityManager* accessibility_manager =
2332 chromeos::AccessibilityManager::Get();
2334 // Manually enable spoken feedback.
2335 accessibility_manager->EnableSpokenFeedback(
2336 true, ash::A11Y_NOTIFICATION_NONE);
2337 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2339 // Verify that policy overrides the manual setting.
2341 policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY,
2343 base::Value::CreateBooleanValue(false), NULL);
2344 UpdateProviderPolicy(policies);
2345 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2347 // Verify that spoken feedback cannot be enabled manually anymore.
2348 accessibility_manager->EnableSpokenFeedback(
2349 true, ash::A11Y_NOTIFICATION_NONE);
2350 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2353 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2354 // Verifies that the high contrast mode accessibility feature can be
2355 // controlled through policy.
2356 chromeos::AccessibilityManager* accessibility_manager =
2357 chromeos::AccessibilityManager::Get();
2359 // Manually enable high contrast mode.
2360 accessibility_manager->EnableHighContrast(true);
2361 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2363 // Verify that policy overrides the manual setting.
2365 policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY,
2367 base::Value::CreateBooleanValue(false), NULL);
2368 UpdateProviderPolicy(policies);
2369 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2371 // Verify that high contrast mode cannot be enabled manually anymore.
2372 accessibility_manager->EnableHighContrast(true);
2373 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2376 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2377 // Verifies that the screen magnifier can be disabled through policy.
2378 chromeos::MagnificationManager* magnification_manager =
2379 chromeos::MagnificationManager::Get();
2381 // Manually enable the full-screen magnifier.
2382 magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL);
2383 magnification_manager->SetMagnifierEnabled(true);
2384 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2385 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2387 // Verify that policy overrides the manual setting.
2389 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2391 base::Value::CreateIntegerValue(0), NULL);
2392 UpdateProviderPolicy(policies);
2393 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2395 // Verify that the screen magnifier cannot be enabled manually anymore.
2396 magnification_manager->SetMagnifierEnabled(true);
2397 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2400 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2401 // Verifies that the full-screen magnifier can be enabled through policy.
2402 chromeos::MagnificationManager* magnification_manager =
2403 chromeos::MagnificationManager::Get();
2405 // Verify that the screen magnifier is initially disabled.
2406 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2408 // Verify that policy can enable the full-screen magnifier.
2410 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2412 base::Value::CreateIntegerValue(ash::MAGNIFIER_FULL), NULL);
2413 UpdateProviderPolicy(policies);
2414 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2415 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2417 // Verify that the screen magnifier cannot be disabled manually anymore.
2418 magnification_manager->SetMagnifierEnabled(false);
2419 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2422 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2423 // Verifies that the on-screen keyboard accessibility feature can be
2424 // controlled through policy.
2425 chromeos::AccessibilityManager* accessibility_manager =
2426 chromeos::AccessibilityManager::Get();
2428 // Manually enable the on-screen keyboard.
2429 accessibility_manager->EnableVirtualKeyboard(true);
2430 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2432 // Verify that policy overrides the manual setting.
2434 policies.Set(key::kVirtualKeyboardEnabled, POLICY_LEVEL_MANDATORY,
2436 base::Value::CreateBooleanValue(false), NULL);
2437 UpdateProviderPolicy(policies);
2438 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2440 // Verify that the on-screen keyboard cannot be enabled manually anymore.
2441 accessibility_manager->EnableVirtualKeyboard(true);
2442 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2449 static const char* kRestoredURLs[] = {
2450 "http://aaa.com/empty.html",
2451 "http://bbb.com/empty.html",
2454 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2455 return s.empty() || s[0] != '-';
2460 // Similar to PolicyTest but allows setting policies before the browser is
2461 // created. Each test parameter is a method that sets up the early policies
2462 // and stores the expected startup URLs in |expected_urls_|.
2463 class RestoreOnStartupPolicyTest
2464 : public PolicyTest,
2465 public testing::WithParamInterface<
2466 void (RestoreOnStartupPolicyTest::*)(void)> {
2468 RestoreOnStartupPolicyTest() {}
2469 virtual ~RestoreOnStartupPolicyTest() {}
2471 #if defined(OS_CHROMEOS)
2472 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2473 // TODO(nkostylev): Investigate if we can remove this switch.
2474 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2475 PolicyTest::SetUpCommandLine(command_line);
2479 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2480 PolicyTest::SetUpInProcessBrowserTestFixture();
2481 // Set early policies now, before the browser is created.
2482 (this->*(GetParam()))();
2484 // Remove the non-switch arguments, so that session restore kicks in for
2486 CommandLine* command_line = CommandLine::ForCurrentProcess();
2487 CommandLine::StringVector argv = command_line->argv();
2488 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2490 command_line->InitFromArgv(argv);
2491 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2492 command_line->argv().begin()));
2494 // Redirect the test URLs to the test data directory.
2495 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs));
2498 void HomepageIsNotNTP() {
2499 // Verifies that policy can set the startup pages to the homepage, when
2500 // the homepage is not the NTP.
2503 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2504 base::Value::CreateIntegerValue(
2505 SessionStartupPref::kPrefValueHomePage),
2508 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2509 base::Value::CreateBooleanValue(false), NULL);
2511 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2512 base::Value::CreateStringValue(kRestoredURLs[1]), NULL);
2513 provider_.UpdateChromePolicy(policies);
2515 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2518 void HomepageIsNTP() {
2519 // Verifies that policy can set the startup pages to the homepage, when
2520 // the homepage is the NTP.
2523 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2524 base::Value::CreateIntegerValue(
2525 SessionStartupPref::kPrefValueHomePage),
2528 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2529 base::Value::CreateBooleanValue(true), NULL);
2530 provider_.UpdateChromePolicy(policies);
2532 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2536 // Verifies that policy can set the startup pages to a list of URLs.
2537 base::ListValue urls;
2538 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2539 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i]));
2540 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2544 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2545 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs),
2548 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2549 urls.DeepCopy(), NULL);
2550 provider_.UpdateChromePolicy(policies);
2554 // Verifies that policy can set the startup page to the NTP.
2557 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2558 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab),
2560 provider_.UpdateChromePolicy(policies);
2561 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2565 // Verifies that policy can set the startup pages to the last session.
2568 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2569 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast),
2571 provider_.UpdateChromePolicy(policies);
2572 // This should restore the tabs opened at PRE_RunTest below.
2573 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2574 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2577 std::vector<GURL> expected_urls_;
2580 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2581 // Open some tabs to verify if they are restored after the browser restarts.
2582 // Most policy settings override this, except kPrefValueLast which enforces
2584 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2585 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2586 content::WindowedNotificationObserver observer(
2587 content::NOTIFICATION_LOAD_STOP,
2588 content::NotificationService::AllSources());
2589 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2590 content::PAGE_TRANSITION_LINK);
2595 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2596 #if defined(OS_WIN) && defined(USE_ASH)
2597 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2598 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2602 TabStripModel* model = browser()->tab_strip_model();
2603 int size = static_cast<int>(expected_urls_.size());
2604 EXPECT_EQ(size, model->count());
2605 for (int i = 0; i < size && i < model->count(); ++i) {
2606 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2610 INSTANTIATE_TEST_CASE_P(
2611 RestoreOnStartupPolicyTestInstance,
2612 RestoreOnStartupPolicyTest,
2613 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2614 &RestoreOnStartupPolicyTest::HomepageIsNTP,
2615 &RestoreOnStartupPolicyTest::ListOfURLs,
2616 &RestoreOnStartupPolicyTest::NTP,
2617 &RestoreOnStartupPolicyTest::Last));
2619 // Similar to PolicyTest but sets a couple of policies before the browser is
2621 class PolicyStatisticsCollectorTest : public PolicyTest {
2623 PolicyStatisticsCollectorTest() {}
2624 virtual ~PolicyStatisticsCollectorTest() {}
2626 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2627 PolicyTest::SetUpInProcessBrowserTestFixture();
2630 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2631 base::Value::CreateBooleanValue(true), NULL);
2633 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2634 base::Value::CreateBooleanValue(false), NULL);
2636 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2637 base::Value::CreateStringValue("http://chromium.org"), NULL);
2638 provider_.UpdateChromePolicy(policies);
2642 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2643 // Verifies that policy usage histograms are collected at startup.
2645 // BrowserPolicyConnector::Init() has already been called. Make sure the
2646 // CompleteInitialization() task has executed as well.
2647 content::RunAllPendingInMessageLoop();
2649 GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) +
2650 std::string(content::kStandardSchemeSeparator) +
2651 std::string(content::kChromeUIHistogramHost));
2652 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
2653 content::WebContents* contents =
2654 browser()->tab_strip_model()->GetActiveWebContents();
2656 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2658 "var nodes = document.querySelectorAll('body > pre');"
2660 "for (var i = 0; i < nodes.length; ++i) {"
2661 " var text = nodes[i].innerHTML;"
2662 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
2667 "domAutomationController.send(result);",
2669 ASSERT_FALSE(text.empty());
2670 const std::string kExpectedLabel =
2671 "Histogram: Enterprise.Policies recorded 3 samples";
2672 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
2673 // HomepageLocation has policy ID 1.
2674 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
2675 // ShowHomeButton has policy ID 35.
2676 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
2677 // BookmarkBarEnabled has policy ID 82.
2678 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
2681 class MediaStreamDevicesControllerBrowserTest
2682 : public PolicyTest,
2683 public testing::WithParamInterface<bool> {
2685 MediaStreamDevicesControllerBrowserTest()
2686 : request_url_allowed_via_whitelist_(false) {
2687 policy_value_ = GetParam();
2689 virtual ~MediaStreamDevicesControllerBrowserTest() {}
2691 // Configure a given policy map.
2692 // The |policy_name| is the name of either the audio or video capture allow
2693 // policy and must never be NULL.
2694 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
2695 // policy is set. If non-NULL, the request_url_ will be set to be non empty
2696 // and the whitelist policy is set to contain either the |allow_rule| (if
2697 // non-NULL) or an "allow all" wildcard.
2698 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
2699 const char* whitelist_policy,
2700 const char* allow_rule) {
2701 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2702 base::Value::CreateBooleanValue(policy_value_), NULL);
2704 if (whitelist_policy) {
2705 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
2706 // in the media exceptions UI.
2707 // See discussion here: https://codereview.chromium.org/15738004/
2708 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
2710 // Add an entry to the whitelist that allows the specified URL regardless
2711 // of the setting of kAudioCapturedAllowed.
2712 request_url_ = GURL("http://www.example.com/foo");
2713 base::ListValue* list = new base::ListValue();
2715 list->AppendString(allow_rule);
2716 request_url_allowed_via_whitelist_ = true;
2718 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
2719 // We should ignore all wildcard entries in the whitelist, so even
2720 // though we've added an entry, it should be ignored and our expectation
2721 // is that the request has not been allowed via the whitelist.
2722 request_url_allowed_via_whitelist_ = false;
2724 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
2725 POLICY_SCOPE_USER, list, NULL);
2729 void Accept(const content::MediaStreamDevices& devices,
2730 scoped_ptr<content::MediaStreamUI> ui) {
2731 if (policy_value_ || request_url_allowed_via_whitelist_) {
2732 ASSERT_EQ(1U, devices.size());
2733 ASSERT_EQ("fake_dev", devices[0].id);
2735 ASSERT_EQ(0U, devices.size());
2739 void FinishAudioTest() {
2740 content::MediaStreamRequest request(0, 0, 0,
2741 request_url_.GetOrigin(),
2742 content::MEDIA_DEVICE_ACCESS,
2743 std::string(), std::string(),
2744 content::MEDIA_DEVICE_AUDIO_CAPTURE,
2745 content::MEDIA_NO_SERVICE);
2746 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2747 // and microphone permissions at the same time.
2748 MediaStreamDevicesController controller(
2749 browser()->tab_strip_model()->GetActiveWebContents(), request,
2750 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2751 controller.Accept(false);
2753 base::MessageLoop::current()->QuitWhenIdle();
2756 void FinishVideoTest() {
2757 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2758 // and microphone permissions at the same time.
2759 content::MediaStreamRequest request(0, 0, 0,
2760 request_url_.GetOrigin(),
2761 content::MEDIA_DEVICE_ACCESS,
2764 content::MEDIA_NO_SERVICE,
2765 content::MEDIA_DEVICE_VIDEO_CAPTURE);
2766 MediaStreamDevicesController controller(
2767 browser()->tab_strip_model()->GetActiveWebContents(), request,
2768 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2769 controller.Accept(false);
2771 base::MessageLoop::current()->QuitWhenIdle();
2775 bool request_url_allowed_via_whitelist_;
2777 static const char kExampleRequestPattern[];
2781 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
2782 "http://[*.]example.com/";
2784 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2785 AudioCaptureAllowed) {
2786 content::MediaStreamDevices audio_devices;
2787 content::MediaStreamDevice fake_audio_device(
2788 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2789 audio_devices.push_back(fake_audio_device);
2792 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
2793 UpdateProviderPolicy(policies);
2795 content::BrowserThread::PostTaskAndReply(
2796 content::BrowserThread::IO, FROM_HERE,
2797 base::Bind(&MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2798 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2800 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2803 base::MessageLoop::current()->Run();
2806 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2807 AudioCaptureAllowedUrls) {
2808 content::MediaStreamDevices audio_devices;
2809 content::MediaStreamDevice fake_audio_device(
2810 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2811 audio_devices.push_back(fake_audio_device);
2813 const char* allow_pattern[] = {
2814 kExampleRequestPattern,
2815 // This will set an allow-all policy whitelist. Since we do not allow
2816 // setting an allow-all entry in the whitelist, this entry should be ignored
2817 // and therefore the request should be denied.
2821 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2823 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
2824 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
2825 UpdateProviderPolicy(policies);
2827 content::BrowserThread::PostTaskAndReply(
2828 content::BrowserThread::IO, FROM_HERE,
2830 &MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2831 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2834 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2837 base::MessageLoop::current()->Run();
2841 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2842 VideoCaptureAllowed) {
2843 content::MediaStreamDevices video_devices;
2844 content::MediaStreamDevice fake_video_device(
2845 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2846 video_devices.push_back(fake_video_device);
2849 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
2850 UpdateProviderPolicy(policies);
2852 content::BrowserThread::PostTaskAndReply(
2853 content::BrowserThread::IO, FROM_HERE,
2854 base::Bind(&MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2855 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2857 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2860 base::MessageLoop::current()->Run();
2863 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2864 VideoCaptureAllowedUrls) {
2865 content::MediaStreamDevices video_devices;
2866 content::MediaStreamDevice fake_video_device(
2867 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2868 video_devices.push_back(fake_video_device);
2870 const char* allow_pattern[] = {
2871 kExampleRequestPattern,
2872 // This will set an allow-all policy whitelist. Since we do not allow
2873 // setting an allow-all entry in the whitelist, this entry should be ignored
2874 // and therefore the request should be denied.
2878 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2880 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
2881 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
2882 UpdateProviderPolicy(policies);
2884 content::BrowserThread::PostTaskAndReply(
2885 content::BrowserThread::IO, FROM_HERE,
2887 &MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2888 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2891 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2894 base::MessageLoop::current()->Run();
2898 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
2899 MediaStreamDevicesControllerBrowserTest,
2902 #if !defined(OS_CHROMEOS)
2903 // Similar to PolicyTest but sets the proper policy before the browser is
2905 class PolicyVariationsServiceTest : public PolicyTest {
2907 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2908 PolicyTest::SetUpInProcessBrowserTestFixture();
2911 key::kVariationsRestrictParameter,
2912 POLICY_LEVEL_MANDATORY,
2914 base::Value::CreateStringValue("restricted"),
2916 provider_.UpdateChromePolicy(policies);
2920 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
2921 const std::string default_variations_url =
2922 chrome_variations::VariationsService::
2923 GetDefaultVariationsServerURLForTesting();
2926 chrome_variations::VariationsService::GetVariationsServerURL(
2927 g_browser_process->local_state());
2928 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
2930 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
2931 EXPECT_EQ("restricted", value);
2934 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
2935 base::ListValue blacklist;
2936 blacklist.Append(base::Value::CreateStringValue("host.name"));
2938 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2939 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2940 UpdateProviderPolicy(policies);
2942 PrefService* prefs = browser()->profile()->GetPrefs();
2943 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2944 prefs, "host.name"));
2945 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2946 prefs, "other.host.name"));
2949 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
2950 base::ListValue blacklist;
2951 blacklist.Append(base::Value::CreateStringValue("*"));
2953 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2954 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2955 UpdateProviderPolicy(policies);
2957 PrefService* prefs = browser()->profile()->GetPrefs();
2958 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2959 prefs, "host.name"));
2960 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2961 prefs, "other.host.name"));
2964 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
2965 base::ListValue blacklist;
2966 blacklist.Append(base::Value::CreateStringValue("*"));
2967 base::ListValue whitelist;
2968 whitelist.Append(base::Value::CreateStringValue("host.name"));
2970 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2971 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2972 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
2973 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2974 UpdateProviderPolicy(policies);
2976 PrefService* prefs = browser()->profile()->GetPrefs();
2977 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2978 prefs, "host.name"));
2979 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2980 prefs, "other.host.name"));
2983 #endif // !defined(CHROME_OS)
2985 } // namespace policy