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_service.h"
39 #include "chrome/browser/extensions/unpacked_installer.h"
40 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
41 #include "chrome/browser/extensions/updater/extension_updater.h"
42 #include "chrome/browser/infobars/infobar_service.h"
43 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
44 #include "chrome/browser/media/media_stream_devices_controller.h"
45 #include "chrome/browser/metrics/variations/variations_service.h"
46 #include "chrome/browser/net/url_request_mock_util.h"
47 #include "chrome/browser/plugins/plugin_prefs.h"
48 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
49 #include "chrome/browser/policy/profile_policy_connector.h"
50 #include "chrome/browser/policy/profile_policy_connector_factory.h"
51 #include "chrome/browser/prefs/session_startup_pref.h"
52 #include "chrome/browser/profiles/profile.h"
53 #include "chrome/browser/search/instant_service.h"
54 #include "chrome/browser/search/instant_service_factory.h"
55 #include "chrome/browser/search/search.h"
56 #include "chrome/browser/search_engines/template_url.h"
57 #include "chrome/browser/search_engines/template_url_service.h"
58 #include "chrome/browser/search_engines/template_url_service_factory.h"
59 #include "chrome/browser/translate/chrome_translate_client.h"
60 #include "chrome/browser/translate/translate_browser_test_utils.h"
61 #include "chrome/browser/translate/translate_service.h"
62 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
63 #include "chrome/browser/ui/browser.h"
64 #include "chrome/browser/ui/browser_commands.h"
65 #include "chrome/browser/ui/browser_list.h"
66 #include "chrome/browser/ui/browser_tabstrip.h"
67 #include "chrome/browser/ui/browser_window.h"
68 #include "chrome/browser/ui/host_desktop.h"
69 #include "chrome/browser/ui/omnibox/location_bar.h"
70 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
71 #include "chrome/browser/ui/omnibox/omnibox_view.h"
72 #include "chrome/browser/ui/tabs/tab_strip_model.h"
73 #include "chrome/common/chrome_paths.h"
74 #include "chrome/common/chrome_switches.h"
75 #include "chrome/common/content_settings.h"
76 #include "chrome/common/content_settings_pattern.h"
77 #include "chrome/common/extensions/extension_constants.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/test/base/in_process_browser_test.h"
81 #include "chrome/test/base/test_switches.h"
82 #include "chrome/test/base/ui_test_utils.h"
83 #include "components/infobars/core/infobar.h"
84 #include "components/policy/core/browser/browser_policy_connector.h"
85 #include "components/policy/core/common/external_data_fetcher.h"
86 #include "components/policy/core/common/mock_configuration_policy_provider.h"
87 #include "components/policy/core/common/policy_map.h"
88 #include "components/policy/core/common/policy_pref_names.h"
89 #include "components/policy/core/common/policy_service.h"
90 #include "components/policy/core/common/policy_service_impl.h"
91 #include "components/translate/core/browser/language_state.h"
92 #include "components/translate/core/browser/translate_infobar_delegate.h"
93 #include "content/public/browser/browser_child_process_host_iterator.h"
94 #include "content/public/browser/browser_context.h"
95 #include "content/public/browser/browser_thread.h"
96 #include "content/public/browser/child_process_data.h"
97 #include "content/public/browser/download_item.h"
98 #include "content/public/browser/download_manager.h"
99 #include "content/public/browser/gpu_data_manager.h"
100 #include "content/public/browser/notification_details.h"
101 #include "content/public/browser/notification_observer.h"
102 #include "content/public/browser/notification_registrar.h"
103 #include "content/public/browser/notification_service.h"
104 #include "content/public/browser/notification_source.h"
105 #include "content/public/browser/notification_types.h"
106 #include "content/public/browser/plugin_service.h"
107 #include "content/public/browser/render_process_host.h"
108 #include "content/public/browser/render_view_host.h"
109 #include "content/public/browser/web_contents.h"
110 #include "content/public/common/content_constants.h"
111 #include "content/public/common/content_paths.h"
112 #include "content/public/common/page_transition_types.h"
113 #include "content/public/common/process_type.h"
114 #include "content/public/common/result_codes.h"
115 #include "content/public/common/url_constants.h"
116 #include "content/public/common/webplugininfo.h"
117 #include "content/public/test/browser_test_utils.h"
118 #include "content/public/test/download_test_observer.h"
119 #include "content/public/test/mock_notification_observer.h"
120 #include "content/public/test/test_navigation_observer.h"
121 #include "content/public/test/test_utils.h"
122 #include "content/test/net/url_request_failed_job.h"
123 #include "content/test/net/url_request_mock_http_job.h"
124 #include "extensions/browser/extension_host.h"
125 #include "extensions/browser/extension_system.h"
126 #include "extensions/browser/process_manager.h"
127 #include "extensions/common/constants.h"
128 #include "extensions/common/extension.h"
129 #include "extensions/common/extension_set.h"
130 #include "grit/generated_resources.h"
131 #include "net/base/net_errors.h"
132 #include "net/base/net_util.h"
133 #include "net/base/url_util.h"
134 #include "net/http/http_stream_factory.h"
135 #include "net/url_request/url_request.h"
136 #include "net/url_request/url_request_filter.h"
137 #include "policy/policy_constants.h"
138 #include "testing/gmock/include/gmock/gmock.h"
139 #include "testing/gtest/include/gtest/gtest.h"
140 #include "third_party/WebKit/public/web/WebInputEvent.h"
141 #include "ui/base/l10n/l10n_util.h"
142 #include "ui/base/resource/resource_bundle.h"
143 #include "url/gurl.h"
145 #if defined(OS_CHROMEOS)
146 #include "ash/accelerators/accelerator_controller.h"
147 #include "ash/accelerators/accelerator_table.h"
148 #include "ash/magnifier/magnifier_constants.h"
149 #include "ash/shell.h"
150 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
151 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
152 #include "chrome/browser/profiles/profile_manager.h"
153 #include "chrome/browser/ui/ash/screenshot_taker.h"
154 #include "chromeos/audio/cras_audio_handler.h"
155 #include "ui/keyboard/keyboard_util.h"
158 #if !defined(OS_MACOSX)
159 #include "apps/app_window.h"
160 #include "apps/app_window_registry.h"
161 #include "apps/ui/native_app_window.h"
162 #include "base/basictypes.h"
163 #include "base/compiler_specific.h"
164 #include "chrome/browser/ui/extensions/application_launch.h"
165 #include "ui/base/window_open_disposition.h"
168 using content::BrowserThread;
169 using content::URLRequestMockHTTPJob;
171 using testing::Return;
178 #if defined(OS_CHROMEOS)
179 const int kOneHourInMs = 60 * 60 * 1000;
180 const int kThreeHoursInMs = 180 * 60 * 1000;
183 const char kURL[] = "http://example.com";
184 const char kCookieValue[] = "converted=true";
185 // Assigned to Philip J. Fry to fix eventually.
186 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
188 const base::FilePath::CharType kTestExtensionsDir[] =
189 FILE_PATH_LITERAL("extensions");
190 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
191 const base::FilePath::CharType kAdBlockCrxName[] =
192 FILE_PATH_LITERAL("adblock.crx");
193 const base::FilePath::CharType kHostedAppCrxName[] =
194 FILE_PATH_LITERAL("hosted_app.crx");
196 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
197 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
198 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
200 const base::FilePath::CharType kGood2CrxManifestName[] =
201 FILE_PATH_LITERAL("good2_update_manifest.xml");
202 const base::FilePath::CharType kGoodV1CrxManifestName[] =
203 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
204 const base::FilePath::CharType kGoodUnpackedExt[] =
205 FILE_PATH_LITERAL("good_unpacked");
206 const base::FilePath::CharType kAppUnpackedExt[] =
207 FILE_PATH_LITERAL("app");
209 #if !defined(OS_MACOSX)
210 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
211 FILE_PATH_LITERAL("fullscreen_app");
212 #endif // !defined(OS_MACOSX)
214 // Filters requests to the hosts in |urls| and redirects them to the test data
215 // dir through URLRequestMockHTTPJobs.
216 void RedirectHostsToTestData(const char* const urls[], size_t size) {
217 // Map the given hosts to the test data dir.
218 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
219 base::FilePath base_path;
220 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
221 for (size_t i = 0; i < size; ++i) {
222 const GURL url(urls[i]);
223 EXPECT_TRUE(url.is_valid());
224 filter->AddUrlInterceptor(
225 url, URLRequestMockHTTPJob::CreateInterceptor(base_path));
229 // Remove filters for requests to the hosts in |urls|.
230 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
231 // Map the given hosts to the test data dir.
232 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
233 for (size_t i = 0; i < size; ++i) {
234 const GURL url(urls[i]);
235 EXPECT_TRUE(url.is_valid());
236 filter->RemoveUrlHandler(url);
240 // Fails requests using ERR_CONNECTION_RESET.
241 net::URLRequestJob* FailedJobFactory(
242 net::URLRequest* request,
243 net::NetworkDelegate* network_delegate,
244 const std::string& scheme) {
245 return new content::URLRequestFailedJob(
246 request, network_delegate, net::ERR_CONNECTION_RESET);
249 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
250 class MakeRequestFail {
252 // Sets up the filter on IO thread such that requests to |host| fail.
253 explicit MakeRequestFail(const std::string& host) : host_(host) {
254 BrowserThread::PostTaskAndReply(
255 BrowserThread::IO, FROM_HERE,
256 base::Bind(MakeRequestFailOnIO, host_),
257 base::MessageLoop::QuitClosure());
258 content::RunMessageLoop();
261 BrowserThread::PostTaskAndReply(
262 BrowserThread::IO, FROM_HERE,
263 base::Bind(UndoMakeRequestFailOnIO, host_),
264 base::MessageLoop::QuitClosure());
265 content::RunMessageLoop();
269 // Filters requests to the |host| such that they fail. Run on IO thread.
270 static void MakeRequestFailOnIO(const std::string& host) {
271 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
272 filter->AddHostnameHandler("http", host, &FailedJobFactory);
273 filter->AddHostnameHandler("https", host, &FailedJobFactory);
276 // Remove filters for requests to the |host|. Run on IO thread.
277 static void UndoMakeRequestFailOnIO(const std::string& host) {
278 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
279 filter->RemoveHostnameHandler("http", host);
280 filter->RemoveHostnameHandler("https", host);
283 const std::string host_;
286 // Verifies that the given url |spec| can be opened. This assumes that |spec|
287 // points at empty.html in the test data dir.
288 void CheckCanOpenURL(Browser* browser, const char* spec) {
290 ui_test_utils::NavigateToURL(browser, url);
291 content::WebContents* contents =
292 browser->tab_strip_model()->GetActiveWebContents();
293 EXPECT_EQ(url, contents->GetURL());
294 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
295 EXPECT_NE(title, contents->GetTitle());
298 // Verifies that access to the given url |spec| is blocked.
299 void CheckURLIsBlocked(Browser* browser, const char* spec) {
301 ui_test_utils::NavigateToURL(browser, url);
302 content::WebContents* contents =
303 browser->tab_strip_model()->GetActiveWebContents();
304 EXPECT_EQ(url, contents->GetURL());
305 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
306 EXPECT_EQ(title, contents->GetTitle());
308 // Verify that the expected error page is being displayed.
310 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
312 "var textContent = document.body.textContent;"
313 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
314 "domAutomationController.send(hasError);",
319 // Downloads a file named |file| and expects it to be saved to |dir|, which
321 void DownloadAndVerifyFile(
322 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
323 content::DownloadManager* download_manager =
324 content::BrowserContext::GetDownloadManager(browser->profile());
325 content::DownloadTestObserverTerminal observer(
327 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
328 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
329 base::FilePath downloaded = dir.Append(file);
330 EXPECT_FALSE(base::PathExists(downloaded));
331 ui_test_utils::NavigateToURLWithDisposition(
332 browser, url, CURRENT_TAB,
333 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
334 observer.WaitForFinished();
336 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
337 EXPECT_TRUE(base::PathExists(downloaded));
338 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
339 EXPECT_EQ(file, enumerator.Next().BaseName());
340 EXPECT_EQ(base::FilePath(), enumerator.Next());
343 #if defined(OS_CHROMEOS)
344 int CountScreenshots() {
345 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
346 ProfileManager::GetActiveUserProfile());
347 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
348 false, base::FileEnumerator::FILES,
351 while (!enumerator.Next().empty())
357 // Checks if WebGL is enabled in the given WebContents.
358 bool IsWebGLEnabled(content::WebContents* contents) {
360 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
362 "var canvas = document.createElement('canvas');"
363 "var context = canvas.getContext('webgl');"
364 "domAutomationController.send(context != null);",
369 bool IsJavascriptEnabled(content::WebContents* contents) {
370 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
371 contents->GetMainFrame(), "123");
373 if (!value->GetAsInteger(&result))
374 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
375 return result == 123;
378 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
379 const std::vector<content::WebPluginInfo>& in) {
381 base::MessageLoop::current()->QuitWhenIdle();
385 void CopyValueAndQuit(T* out, T in) {
387 base::MessageLoop::current()->QuitWhenIdle();
390 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
391 content::PluginService* service = content::PluginService::GetInstance();
392 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
393 content::RunMessageLoop();
396 const content::WebPluginInfo* GetFlashPlugin(
397 const std::vector<content::WebPluginInfo>& plugins) {
398 const content::WebPluginInfo* flash = NULL;
399 for (size_t i = 0; i < plugins.size(); ++i) {
400 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
405 #if defined(OFFICIAL_BUILD)
406 // Official builds bundle Flash.
410 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
415 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
416 const content::WebPluginInfo* plugin,
419 plugin_prefs->EnablePlugin(enabled, plugin->path,
420 base::Bind(CopyValueAndQuit<bool>, &ok));
421 content::RunMessageLoop();
425 int CountPluginsOnIOThread() {
427 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
428 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
429 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
438 BrowserThread::PostTaskAndReplyWithResult(
439 BrowserThread::IO, FROM_HERE,
440 base::Bind(CountPluginsOnIOThread),
441 base::Bind(CopyValueAndQuit<int>, &count));
442 content::RunMessageLoop();
447 void FlushBlacklistPolicy() {
448 // Updates of the URLBlacklist are done on IO, after building the blacklist
449 // on FILE, which is initiated from IO.
450 content::RunAllPendingInMessageLoop(BrowserThread::IO);
451 content::RunAllPendingInMessageLoop(BrowserThread::FILE);
452 content::RunAllPendingInMessageLoop(BrowserThread::IO);
455 bool ContainsVisibleElement(content::WebContents* contents,
456 const std::string& id) {
458 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
460 "var elem = document.getElementById('" + id + "');"
461 "domAutomationController.send(!!elem && !elem.hidden);",
466 #if defined(OS_CHROMEOS)
467 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
469 TestAudioObserver() : output_mute_changed_count_(0) {
472 int output_mute_changed_count() const {
473 return output_mute_changed_count_;
476 virtual ~TestAudioObserver() {}
479 // chromeos::CrasAudioHandler::AudioObserver overrides.
480 virtual void OnOutputMuteChanged() OVERRIDE {
481 ++output_mute_changed_count_;
485 int output_mute_changed_count_;
487 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
491 // This class waits until either a load stops or the WebContents is destroyed.
492 class WebContentsLoadedOrDestroyedWatcher
493 : public content::WebContentsObserver {
495 explicit WebContentsLoadedOrDestroyedWatcher(
496 content::WebContents* web_contents);
497 virtual ~WebContentsLoadedOrDestroyedWatcher();
499 // Waits until the WebContents's load is done or until it is destroyed.
502 // Overridden WebContentsObserver methods.
503 virtual void WebContentsDestroyed() 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 message_loop_runner_->Quit();
529 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
530 content::RenderViewHost* render_view_host) {
531 message_loop_runner_->Quit();
534 #if !defined(OS_MACOSX)
536 // Observer used to wait for the creation of a new app window.
537 class TestAddAppWindowObserver : public apps::AppWindowRegistry::Observer {
539 explicit TestAddAppWindowObserver(apps::AppWindowRegistry* registry);
540 virtual ~TestAddAppWindowObserver();
542 // apps::AppWindowRegistry::Observer:
543 virtual void OnAppWindowAdded(apps::AppWindow* app_window) OVERRIDE;
545 apps::AppWindow* WaitForAppWindow();
548 apps::AppWindowRegistry* registry_; // Not owned.
549 apps::AppWindow* window_; // Not owned.
550 base::RunLoop run_loop_;
552 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
555 TestAddAppWindowObserver::TestAddAppWindowObserver(
556 apps::AppWindowRegistry* registry)
557 : registry_(registry), window_(NULL) {
558 registry_->AddObserver(this);
561 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
562 registry_->RemoveObserver(this);
565 void TestAddAppWindowObserver::OnAppWindowAdded(apps::AppWindow* app_window) {
566 window_ = app_window;
570 apps::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
579 class PolicyTest : public InProcessBrowserTest {
582 virtual ~PolicyTest() {}
584 virtual void SetUp() OVERRIDE {
585 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
586 InProcessBrowserTest::SetUp();
589 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
590 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
591 EXPECT_CALL(provider_, IsInitializationComplete(_))
592 .WillRepeatedly(Return(true));
593 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
596 virtual void SetUpOnMainThread() OVERRIDE {
597 BrowserThread::PostTask(
598 BrowserThread::IO, FROM_HERE,
599 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
602 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
603 // instead of chrome::DIR_TEST_DATA.
604 void ServeContentTestData() {
605 base::FilePath root_http;
606 PathService::Get(content::DIR_TEST_DATA, &root_http);
607 BrowserThread::PostTaskAndReply(
608 BrowserThread::IO, FROM_HERE,
609 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http),
610 base::MessageLoop::current()->QuitWhenIdleClosure());
611 content::RunMessageLoop();
614 void SetScreenshotPolicy(bool enabled) {
616 policies.Set(key::kDisableScreenshots,
617 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
618 base::Value::CreateBooleanValue(!enabled), NULL);
619 UpdateProviderPolicy(policies);
622 #if defined(OS_CHROMEOS)
623 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
625 virtual void OnScreenshotCompleted(
626 ScreenshotTakerObserver::Result screenshot_result,
627 const base::FilePath& screenshot_path) OVERRIDE {
628 BrowserThread::PostTaskAndReply(BrowserThread::IO,
630 base::Bind(base::DoNothing),
631 base::MessageLoop::QuitClosure());
634 virtual ~QuitMessageLoopAfterScreenshot() {}
637 void TestScreenshotFile(bool enabled) {
638 // AddObserver is an ash-specific method, so just replace the screenshot
639 // taker with one we've created here.
640 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
641 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
642 // is tied to the test instead.
643 screenshot_taker->AddObserver(&observer_);
644 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
645 screenshot_taker.PassAs<ash::ScreenshotDelegate>());
647 SetScreenshotPolicy(enabled);
648 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
649 ash::TAKE_SCREENSHOT, ui::Accelerator());
651 content::RunMessageLoop();
655 ExtensionService* extension_service() {
656 extensions::ExtensionSystem* system =
657 extensions::ExtensionSystem::Get(browser()->profile());
658 return system->extension_service();
661 const extensions::Extension* InstallExtension(
662 const base::FilePath::StringType& name) {
663 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
664 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
665 scoped_refptr<extensions::CrxInstaller> installer =
666 extensions::CrxInstaller::CreateSilent(extension_service());
667 installer->set_allow_silent_install(true);
668 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
669 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
671 content::WindowedNotificationObserver observer(
672 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
673 content::NotificationService::AllSources());
674 installer->InstallCrx(extension_path);
676 content::Details<const extensions::Extension> details = observer.details();
677 return details.ptr();
680 const extensions::Extension* LoadUnpackedExtension(
681 const base::FilePath::StringType& name, bool expect_success) {
682 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
683 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
684 scoped_refptr<extensions::UnpackedInstaller> installer =
685 extensions::UnpackedInstaller::Create(extension_service());
686 content::WindowedNotificationObserver observer(
687 expect_success ? chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
688 : chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
689 content::NotificationService::AllSources());
690 installer->Load(extension_path);
693 const extensions::ExtensionSet* extensions =
694 extension_service()->extensions();
695 for (extensions::ExtensionSet::const_iterator it = extensions->begin();
696 it != extensions->end(); ++it) {
697 if ((*it)->path() == extension_path)
703 void UninstallExtension(const std::string& id, bool expect_success) {
704 content::WindowedNotificationObserver observer(
705 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
706 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
707 content::NotificationService::AllSources());
708 extension_service()->UninstallExtension(id, false, NULL);
712 void UpdateProviderPolicy(const PolicyMap& policy) {
713 provider_.UpdateChromePolicy(policy);
714 DCHECK(base::MessageLoop::current());
719 // Sends a mouse click at the given coordinates to the current renderer.
720 void PerformClick(int x, int y) {
721 content::WebContents* contents =
722 browser()->tab_strip_model()->GetActiveWebContents();
723 blink::WebMouseEvent click_event;
724 click_event.type = blink::WebInputEvent::MouseDown;
725 click_event.button = blink::WebMouseEvent::ButtonLeft;
726 click_event.clickCount = 1;
729 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
730 click_event.type = blink::WebInputEvent::MouseUp;
731 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
734 MockConfigurationPolicyProvider provider_;
735 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
736 #if defined(OS_CHROMEOS)
737 QuitMessageLoopAfterScreenshot observer_;
742 // This policy only exists on Windows.
744 // Sets the locale policy before the browser is started.
745 class LocalePolicyTest : public PolicyTest {
747 LocalePolicyTest() {}
748 virtual ~LocalePolicyTest() {}
750 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
751 PolicyTest::SetUpInProcessBrowserTestFixture();
754 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
755 base::Value::CreateStringValue("fr"), NULL);
756 provider_.UpdateChromePolicy(policies);
757 // The "en-US" ResourceBundle is always loaded before this step for tests,
758 // but in this test we want the browser to load the bundle as it
760 ResourceBundle::CleanupSharedInstance();
764 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
765 // Verifies that the default locale can be overridden with policy.
766 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
767 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
768 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
769 base::string16 title;
770 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
771 EXPECT_EQ(french_title, title);
773 // Make sure this is really French and differs from the English title.
775 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
776 EXPECT_EQ("en-US", loaded);
777 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
778 EXPECT_NE(french_title, english_title);
782 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
783 #if defined(OS_WIN) && defined(USE_ASH)
784 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
785 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
789 // Verifies that the bookmarks bar can be forced to always or never show up.
791 // Test starts in about:blank.
792 PrefService* prefs = browser()->profile()->GetPrefs();
793 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
794 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
795 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
798 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
799 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
800 UpdateProviderPolicy(policies);
801 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
802 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar));
803 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
805 // The NTP has special handling of the bookmark bar.
806 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
807 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
809 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
810 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
811 UpdateProviderPolicy(policies);
812 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
813 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
814 // The bookmark bar is hidden in the NTP when disabled by policy.
815 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
818 UpdateProviderPolicy(policies);
819 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
820 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
821 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
822 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
825 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
826 // Verifies that cookies are deleted on shutdown. This test is split in 3
827 // parts because it spans 2 browser restarts.
829 Profile* profile = browser()->profile();
831 // No cookies at startup.
832 EXPECT_TRUE(content::GetCookies(profile, url).empty());
834 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
835 EXPECT_TRUE(content::SetCookie(profile, url, value));
836 // Verify it was set.
837 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
840 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
841 // Verify that the cookie persists across restarts.
842 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
843 // Now set the policy and the cookie should be gone after another restart.
845 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY,
846 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4), NULL);
847 UpdateProviderPolicy(policies);
850 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
851 // Verify that the cookie is gone.
852 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
855 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
856 MakeRequestFail make_request_fail("search.example");
858 // Verifies that a default search is made using the provider configured via
859 // policy. Also checks that default search can be completely disabled.
860 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
861 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
862 const std::string kAlternateURL0(
863 "http://search.example/search#q={searchTerms}");
864 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
865 const std::string kSearchTermsReplacementKey("zekey");
866 const std::string kImageURL("http://test.com/searchbyimage/upload");
867 const std::string kImageURLPostParams(
868 "image_content=content,image_url=http://test.com/test.png");
869 const std::string kNewTabURL("http://search.example/newtab");
871 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
872 browser()->profile());
873 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
874 TemplateURL* default_search = service->GetDefaultSearchProvider();
875 ASSERT_TRUE(default_search);
876 EXPECT_NE(kKeyword, default_search->keyword());
877 EXPECT_NE(kSearchURL, default_search->url());
879 default_search->alternate_urls().size() == 2 &&
880 default_search->alternate_urls()[0] == kAlternateURL0 &&
881 default_search->alternate_urls()[1] == kAlternateURL1 &&
882 default_search->search_terms_replacement_key() ==
883 kSearchTermsReplacementKey &&
884 default_search->image_url() == kImageURL &&
885 default_search->image_url_post_params() == kImageURLPostParams &&
886 default_search->new_tab_url() == kNewTabURL);
888 // Override the default search provider using policies.
890 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
891 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
892 policies.Set(key::kDefaultSearchProviderKeyword,
893 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
894 base::Value::CreateStringValue(kKeyword), NULL);
895 policies.Set(key::kDefaultSearchProviderSearchURL,
896 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
897 base::Value::CreateStringValue(kSearchURL), NULL);
898 base::ListValue* alternate_urls = new base::ListValue();
899 alternate_urls->AppendString(kAlternateURL0);
900 alternate_urls->AppendString(kAlternateURL1);
901 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
902 POLICY_SCOPE_USER, alternate_urls, NULL);
903 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
904 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
905 base::Value::CreateStringValue(kSearchTermsReplacementKey),
907 policies.Set(key::kDefaultSearchProviderImageURL,
908 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
909 base::Value::CreateStringValue(kImageURL),
911 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
912 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
913 base::Value::CreateStringValue(kImageURLPostParams),
915 policies.Set(key::kDefaultSearchProviderNewTabURL,
916 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
917 base::Value::CreateStringValue(kNewTabURL),
919 UpdateProviderPolicy(policies);
920 default_search = service->GetDefaultSearchProvider();
921 ASSERT_TRUE(default_search);
922 EXPECT_EQ(kKeyword, default_search->keyword());
923 EXPECT_EQ(kSearchURL, default_search->url());
924 EXPECT_EQ(2U, default_search->alternate_urls().size());
925 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
926 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
927 EXPECT_EQ(kSearchTermsReplacementKey,
928 default_search->search_terms_replacement_key());
929 EXPECT_EQ(kImageURL, default_search->image_url());
930 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
931 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
933 // Verify that searching from the omnibox uses kSearchURL.
934 chrome::FocusLocationBar(browser());
935 LocationBar* location_bar = browser()->window()->GetLocationBar();
936 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
937 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
938 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
939 content::WebContents* web_contents =
940 browser()->tab_strip_model()->GetActiveWebContents();
941 GURL expected("http://search.example/search?q=stuff+to+search+for");
942 EXPECT_EQ(expected, web_contents->GetURL());
944 // Verify that searching from the omnibox can be disabled.
945 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
946 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
947 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
948 EXPECT_TRUE(service->GetDefaultSearchProvider());
949 UpdateProviderPolicy(policies);
950 EXPECT_FALSE(service->GetDefaultSearchProvider());
951 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
952 // This means that submitting won't trigger any action.
953 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
954 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
957 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
958 // Add an individual proxy policy value.
960 policies.Set(key::kProxyServerMode,
961 POLICY_LEVEL_MANDATORY,
963 base::Value::CreateIntegerValue(3),
965 UpdateProviderPolicy(policies);
967 // It should be removed and replaced with a dictionary.
969 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
970 expected_value->SetInteger(key::kProxyServerMode, 3);
971 expected.Set(key::kProxySettings,
972 POLICY_LEVEL_MANDATORY,
974 expected_value.release(),
977 // Check both the browser and the profile.
978 const PolicyMap& actual_from_browser =
979 g_browser_process->browser_policy_connector()
981 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
982 EXPECT_TRUE(expected.Equals(actual_from_browser));
983 const PolicyMap& actual_from_profile =
984 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
986 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
987 EXPECT_TRUE(expected.Equals(actual_from_profile));
990 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
991 // Makes the requests fail since all we want to check is that the redirection
993 MakeRequestFail make_request_fail("google.com");
995 // Verifies that requests to Google Search engine with the SafeSearch
996 // enabled set the safe=active&ssui=on parameters at the end of the query.
997 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
998 browser()->profile());
999 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1001 // First check that nothing happens.
1002 content::TestNavigationObserver no_safesearch_observer(
1003 browser()->tab_strip_model()->GetActiveWebContents());
1004 chrome::FocusLocationBar(browser());
1005 LocationBar* location_bar = browser()->window()->GetLocationBar();
1006 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1007 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1008 no_safesearch_observer.Wait();
1009 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1010 content::WebContents* web_contents =
1011 browser()->tab_strip_model()->GetActiveWebContents();
1012 GURL expected_without("http://google.com/");
1013 EXPECT_EQ(expected_without, web_contents->GetURL());
1015 PrefService* prefs = browser()->profile()->GetPrefs();
1016 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1017 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1019 // Override the default SafeSearch setting using policies.
1021 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
1022 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1023 UpdateProviderPolicy(policies);
1025 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1026 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1028 content::TestNavigationObserver safesearch_observer(
1029 browser()->tab_strip_model()->GetActiveWebContents());
1031 // Verify that searching from google.com works.
1032 chrome::FocusLocationBar(browser());
1033 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1034 safesearch_observer.Wait();
1035 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1036 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1037 std::string expected_url("http://google.com/?");
1038 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1039 chrome::kSafeSearchSsuiParameter;
1040 GURL expected_with_parameters(expected_url);
1041 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1044 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1045 MakeRequestFail make_request_fail("search.example");
1047 chrome::EnableQueryExtractionForTesting();
1049 // Verifies that a default search is made using the provider configured via
1050 // policy. Also checks that default search can be completely disabled.
1051 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1052 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1053 const std::string kInstantURL("http://does/not/exist");
1054 const std::string kAlternateURL0(
1055 "https://www.google.com/search#q={searchTerms}");
1056 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1057 const std::string kSearchTermsReplacementKey(
1058 "{google:instantExtendedEnabledKey}");
1060 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1061 browser()->profile());
1062 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1063 TemplateURL* default_search = service->GetDefaultSearchProvider();
1064 ASSERT_TRUE(default_search);
1065 EXPECT_NE(kKeyword, default_search->keyword());
1066 EXPECT_NE(kSearchURL, default_search->url());
1067 EXPECT_NE(kInstantURL, default_search->instant_url());
1069 default_search->alternate_urls().size() == 2 &&
1070 default_search->alternate_urls()[0] == kAlternateURL0 &&
1071 default_search->alternate_urls()[1] == kAlternateURL1);
1073 // Override the default search provider using policies.
1075 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1076 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1077 policies.Set(key::kDefaultSearchProviderKeyword,
1078 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1079 base::Value::CreateStringValue(kKeyword), NULL);
1080 policies.Set(key::kDefaultSearchProviderSearchURL,
1081 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1082 base::Value::CreateStringValue(kSearchURL), NULL);
1083 policies.Set(key::kDefaultSearchProviderInstantURL,
1084 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1085 base::Value::CreateStringValue(kInstantURL), NULL);
1086 base::ListValue* alternate_urls = new base::ListValue();
1087 alternate_urls->AppendString(kAlternateURL0);
1088 alternate_urls->AppendString(kAlternateURL1);
1089 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1090 POLICY_SCOPE_USER, alternate_urls, NULL);
1091 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1092 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1093 base::Value::CreateStringValue(kSearchTermsReplacementKey),
1095 UpdateProviderPolicy(policies);
1096 default_search = service->GetDefaultSearchProvider();
1097 ASSERT_TRUE(default_search);
1098 EXPECT_EQ(kKeyword, default_search->keyword());
1099 EXPECT_EQ(kSearchURL, default_search->url());
1100 EXPECT_EQ(kInstantURL, default_search->instant_url());
1101 EXPECT_EQ(2U, default_search->alternate_urls().size());
1102 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1103 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1105 // Query terms replacement requires that the renderer process be a recognized
1106 // Instant renderer. Fake it.
1107 InstantService* instant_service =
1108 InstantServiceFactory::GetForProfile(browser()->profile());
1109 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1110 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1112 // Verify that searching from the omnibox does search term replacement with
1113 // first URL pattern.
1114 chrome::FocusLocationBar(browser());
1115 LocationBar* location_bar = browser()->window()->GetLocationBar();
1116 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1117 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1118 "https://www.google.com/?espv=1#q=foobar");
1120 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1121 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1123 // Verify that not using espv=1 does not do search term replacement.
1124 chrome::FocusLocationBar(browser());
1125 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1126 "https://www.google.com/?q=foobar");
1128 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1129 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1130 omnibox_view->GetText());
1132 // Verify that searching from the omnibox does search term replacement with
1133 // second URL pattern.
1134 chrome::FocusLocationBar(browser());
1135 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1136 "https://www.google.com/search?espv=1#q=banana");
1138 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1139 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1141 // Verify that searching from the omnibox does search term replacement with
1142 // standard search URL pattern.
1143 chrome::FocusLocationBar(browser());
1144 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1145 "https://www.google.com/search?q=tractor+parts&espv=1");
1147 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1148 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1150 // Verify that searching from the omnibox prioritizes hash over query.
1151 chrome::FocusLocationBar(browser());
1152 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1153 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1155 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1156 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1159 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1160 // This test assumes Gpu access.
1161 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1164 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1165 // WebGL is enabled by default.
1166 content::WebContents* contents =
1167 browser()->tab_strip_model()->GetActiveWebContents();
1168 EXPECT_TRUE(IsWebGLEnabled(contents));
1169 // Disable with a policy.
1171 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1172 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1173 UpdateProviderPolicy(policies);
1174 // Crash and reload the tab to get a new renderer.
1175 content::CrashTab(contents);
1176 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1177 EXPECT_FALSE(IsWebGLEnabled(contents));
1178 // Enable with a policy.
1179 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1180 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1181 UpdateProviderPolicy(policies);
1182 content::CrashTab(contents);
1183 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1184 EXPECT_TRUE(IsWebGLEnabled(contents));
1187 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1188 // Verifies that SPDY can be disable by policy.
1189 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1191 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1192 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1193 UpdateProviderPolicy(policies);
1194 content::RunAllPendingInMessageLoop();
1195 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1196 // Verify that it can be force-enabled too.
1197 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1198 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1199 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1200 UpdateProviderPolicy(policies);
1201 content::RunAllPendingInMessageLoop();
1202 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1205 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1206 // Verifies that plugins can be forced to be disabled by policy.
1208 // Verify that the Flash plugin exists and that it can be enabled and disabled
1210 std::vector<content::WebPluginInfo> plugins;
1211 GetPluginList(&plugins);
1212 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1215 PluginPrefs* plugin_prefs =
1216 PluginPrefs::GetForProfile(browser()->profile()).get();
1217 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1218 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1219 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1220 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1221 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1223 // Now disable it with a policy.
1224 base::ListValue disabled_plugins;
1225 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
1227 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1228 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1229 UpdateProviderPolicy(policies);
1230 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1231 // The user shouldn't be able to enable it.
1232 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1233 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1236 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1237 // Verifies that plugins with an exception in the blacklist can be enabled.
1239 // Verify that the Flash plugin exists and that it can be enabled and disabled
1241 std::vector<content::WebPluginInfo> plugins;
1242 GetPluginList(&plugins);
1243 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1246 PluginPrefs* plugin_prefs =
1247 PluginPrefs::GetForProfile(browser()->profile()).get();
1248 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1250 // Disable all plugins.
1251 base::ListValue disabled_plugins;
1252 disabled_plugins.Append(base::Value::CreateStringValue("*"));
1254 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1255 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1256 UpdateProviderPolicy(policies);
1257 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1258 // The user shouldn't be able to enable it.
1259 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1260 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1262 // Now open an exception for flash.
1263 base::ListValue disabled_plugins_exceptions;
1264 disabled_plugins_exceptions.Append(
1265 base::Value::CreateStringValue("*Flash*"));
1266 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1267 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1268 UpdateProviderPolicy(policies);
1269 // It should revert to the user's preference automatically.
1270 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1271 // And the user should be able to disable and enable again.
1272 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1273 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1274 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1275 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1278 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1279 // Verifies that a plugin can be force-installed with a policy.
1280 std::vector<content::WebPluginInfo> plugins;
1281 GetPluginList(&plugins);
1282 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1285 PluginPrefs* plugin_prefs =
1286 PluginPrefs::GetForProfile(browser()->profile()).get();
1287 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1289 // The user disables it and then a policy forces it to be enabled.
1290 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1291 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1292 base::ListValue plugin_list;
1293 plugin_list.Append(base::Value::CreateStringValue(content::kFlashPluginName));
1295 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1296 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1297 UpdateProviderPolicy(policies);
1298 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1299 // The user can't disable it anymore.
1300 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1301 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1303 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1304 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1305 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1306 UpdateProviderPolicy(policies);
1307 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1310 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1311 // Verifies that dangerous plugins can be always authorized to run with
1314 // Verify that the test page exists. It is only present in checkouts with
1316 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1317 base::FilePath(FILE_PATH_LITERAL("plugin")),
1318 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1320 "Test skipped because plugin/quicktime.html test file wasn't found.";
1324 ServeContentTestData();
1325 // No plugins at startup.
1326 EXPECT_EQ(0, CountPlugins());
1328 content::WebContents* contents =
1329 browser()->tab_strip_model()->GetActiveWebContents();
1330 ASSERT_TRUE(contents);
1331 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1332 ASSERT_TRUE(infobar_service);
1333 EXPECT_EQ(0u, infobar_service->infobar_count());
1335 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1336 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1337 ui_test_utils::NavigateToURL(browser(), url);
1338 // This should have triggered the dangerous plugin infobar.
1339 ASSERT_EQ(1u, infobar_service->infobar_count());
1341 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1342 // And the plugin isn't running.
1343 EXPECT_EQ(0, CountPlugins());
1345 // Now set a policy to always authorize this.
1347 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1348 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1349 UpdateProviderPolicy(policies);
1350 // Reloading the page shouldn't trigger the infobar this time.
1351 ui_test_utils::NavigateToURL(browser(), url);
1352 EXPECT_EQ(0u, infobar_service->infobar_count());
1353 // And the plugin started automatically.
1354 EXPECT_EQ(1, CountPlugins());
1357 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1358 // Verifies that access to the developer tools can be disabled.
1361 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1362 content::WebContents* contents =
1363 browser()->tab_strip_model()->GetActiveWebContents();
1364 DevToolsWindow *devtools_window =
1365 DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1366 contents->GetRenderViewHost());
1367 EXPECT_TRUE(devtools_window);
1369 // Disable devtools via policy.
1371 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1372 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1373 content::WindowedNotificationObserver close_observer(
1374 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1375 content::Source<content::WebContents>(
1376 devtools_window->web_contents_for_test()));
1377 UpdateProviderPolicy(policies);
1378 // wait for devtools close
1379 close_observer.Wait();
1380 // The existing devtools window should have closed.
1381 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1382 contents->GetRenderViewHost()));
1383 // And it's not possible to open it again.
1384 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1385 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1386 contents->GetRenderViewHost()));
1389 // TODO(samarth): remove along with rest of NTP4 code.
1390 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1391 #if defined(OS_WIN) && defined(USE_ASH)
1392 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1393 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1397 // Verifies that the web store icons can be hidden from the new tab page.
1399 // Open new tab page and look for the web store icons.
1400 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1401 content::WebContents* contents =
1402 browser()->tab_strip_model()->GetActiveWebContents();
1404 #if !defined(OS_CHROMEOS)
1405 // Look for web store's app ID in the apps page.
1406 EXPECT_TRUE(ContainsVisibleElement(contents,
1407 "ahfgeienlihckogmohjhadlkjgocpleb"));
1410 // The next NTP has no footer.
1411 if (ContainsVisibleElement(contents, "footer"))
1412 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1414 // Turn off the web store icons.
1416 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
1417 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1418 UpdateProviderPolicy(policies);
1420 // The web store icons should now be hidden.
1421 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1422 EXPECT_FALSE(ContainsVisibleElement(contents,
1423 "ahfgeienlihckogmohjhadlkjgocpleb"));
1424 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1427 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1428 // Verifies that the download directory can be forced by policy.
1430 // Set the initial download directory.
1431 base::ScopedTempDir initial_dir;
1432 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1433 browser()->profile()->GetPrefs()->SetFilePath(
1434 prefs::kDownloadDefaultDirectory, initial_dir.path());
1435 // Don't prompt for the download location during this test.
1436 browser()->profile()->GetPrefs()->SetBoolean(
1437 prefs::kPromptForDownload, false);
1439 // Verify that downloads end up on the default directory.
1440 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1441 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1442 base::DieFileDie(initial_dir.path().Append(file), false);
1444 // Override the download directory with the policy and verify a download.
1445 base::ScopedTempDir forced_dir;
1446 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1448 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1450 base::Value::CreateStringValue(forced_dir.path().value()), NULL);
1451 UpdateProviderPolicy(policies);
1452 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1453 // Verify that the first download location wasn't affected.
1454 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1457 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1458 // Verifies that blacklisted extensions can't be installed.
1459 ExtensionService* service = extension_service();
1460 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1461 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1462 base::ListValue blacklist;
1463 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1465 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1466 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1467 UpdateProviderPolicy(policies);
1469 // "good.crx" is blacklisted.
1470 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1471 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1473 // "adblock.crx" is not.
1474 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1475 ASSERT_TRUE(adblock);
1476 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1478 service->GetExtensionById(kAdBlockCrxId, true));
1481 // Flaky on windows; http://crbug.com/307994.
1483 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1485 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1487 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1488 // Verify that a wildcard blacklist takes effect.
1489 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1490 ExtensionService* service = extension_service();
1491 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1492 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1493 base::ListValue blacklist;
1494 blacklist.Append(base::Value::CreateStringValue("*"));
1496 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1497 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1498 UpdateProviderPolicy(policies);
1500 // AdBlock was automatically removed.
1501 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1503 // And can't be installed again, nor can good.crx.
1504 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1505 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1506 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1507 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1510 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1511 // Verifies that the whitelist can open exceptions to the blacklist.
1512 ExtensionService* service = extension_service();
1513 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1514 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1515 base::ListValue blacklist;
1516 blacklist.Append(base::Value::CreateStringValue("*"));
1517 base::ListValue whitelist;
1518 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1520 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1521 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1522 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1523 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1524 UpdateProviderPolicy(policies);
1525 // "adblock.crx" is blacklisted.
1526 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1527 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1528 // "good.crx" has a whitelist exception.
1529 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1531 EXPECT_EQ(kGoodCrxId, good->id());
1532 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1533 // The user can also remove this extension.
1534 UninstallExtension(kGoodCrxId, true);
1537 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1538 // Verifies that extensions that are force-installed by policies are
1539 // installed and can't be uninstalled.
1540 ExtensionService* service = extension_service();
1541 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1543 // Extensions that are force-installed come from an update URL, which defaults
1544 // to the webstore. Use a mock URL for this test with an update manifest
1545 // that includes "good_v1.crx".
1546 base::FilePath path =
1547 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1548 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1550 // Setting the forcelist extension should install "good_v1.crx".
1551 base::ListValue forcelist;
1552 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf(
1553 "%s;%s", kGoodCrxId, url.spec().c_str())));
1555 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1556 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1557 content::WindowedNotificationObserver observer(
1558 chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED,
1559 content::NotificationService::AllSources());
1560 UpdateProviderPolicy(policies);
1562 // Note: Cannot check that the notification details match the expected
1563 // exception, since the details object has already been freed prior to
1564 // the completion of observer.Wait().
1566 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1568 // The user is not allowed to uninstall force-installed extensions.
1569 UninstallExtension(kGoodCrxId, false);
1571 // The user is not allowed to load an unpacked extension with the
1572 // same ID as a force-installed extension.
1573 LoadUnpackedExtension(kGoodUnpackedExt, false);
1575 // Loading other unpacked extensions are not blocked.
1576 LoadUnpackedExtension(kAppUnpackedExt, true);
1578 const std::string old_version_number =
1579 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1581 base::FilePath test_path;
1582 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1584 TestRequestInterceptor interceptor(
1586 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1587 interceptor.PushJobCallback(
1588 TestRequestInterceptor::FileJob(
1589 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1591 // Updating the force-installed extension.
1592 extensions::ExtensionUpdater* updater = service->updater();
1593 extensions::ExtensionUpdater::CheckParams params;
1594 params.install_immediately = true;
1595 content::WindowedNotificationObserver update_observer(
1596 chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED,
1597 content::NotificationService::AllSources());
1598 updater->CheckNow(params);
1599 update_observer.Wait();
1601 const base::Version* new_version =
1602 service->GetExtensionById(kGoodCrxId, true)->version();
1603 ASSERT_TRUE(new_version->IsValid());
1604 base::Version old_version(old_version_number);
1605 ASSERT_TRUE(old_version.IsValid());
1607 EXPECT_EQ(1, new_version->CompareTo(old_version));
1609 EXPECT_EQ(0u, interceptor.GetPendingSize());
1611 // Wait until any background pages belonging to force-installed extensions
1612 // have been loaded.
1613 extensions::ProcessManager* manager =
1614 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1615 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1616 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1618 iter != all_views.end();) {
1619 if (!(*iter)->IsLoading()) {
1622 content::WebContents* web_contents =
1623 content::WebContents::FromRenderViewHost(*iter);
1624 ASSERT_TRUE(web_contents);
1625 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1627 // Test activity may have modified the set of extension processes during
1628 // message processing, so re-start the iteration to catch added/removed
1630 all_views = manager->GetAllViews();
1631 iter = all_views.begin();
1635 // Test policy-installed extensions are reloaded when killed.
1636 BackgroundContentsService::
1637 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1638 content::WindowedNotificationObserver extension_crashed_observer(
1639 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1640 content::NotificationService::AllSources());
1641 content::WindowedNotificationObserver extension_loaded_observer(
1642 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1643 content::NotificationService::AllSources());
1644 extensions::ExtensionHost* extension_host =
1645 extensions::ExtensionSystem::Get(browser()->profile())->
1646 process_manager()->GetBackgroundHostForExtension(kGoodCrxId);
1647 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1648 content::RESULT_CODE_KILLED, false);
1649 extension_crashed_observer.Wait();
1650 extension_loaded_observer.Wait();
1653 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1654 // Verifies that extensions are blocked if policy specifies an allowed types
1655 // list and the extension's type is not on that list.
1656 ExtensionService* service = extension_service();
1657 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1658 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1660 base::ListValue allowed_types;
1661 allowed_types.AppendString("hosted_app");
1663 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1664 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1665 UpdateProviderPolicy(policies);
1667 // "good.crx" is blocked.
1668 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1669 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1671 // "hosted_app.crx" is of a whitelisted type.
1672 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1673 ASSERT_TRUE(hosted_app);
1674 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1675 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1677 // The user can remove the extension.
1678 UninstallExtension(kHostedAppCrxId, true);
1681 // Checks that a click on an extension CRX download triggers the extension
1682 // installation prompt without further user interaction when the source is
1683 // whitelisted by policy.
1684 // Flaky on windows; http://crbug.com/295729 .
1686 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1688 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1690 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1691 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1692 switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
1694 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1695 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1696 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1697 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1699 base::ScopedTempDir download_directory;
1700 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1701 DownloadPrefs* download_prefs =
1702 DownloadPrefs::FromBrowserContext(browser()->profile());
1703 download_prefs->SetDownloadPath(download_directory.path());
1705 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1706 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1707 ui_test_utils::NavigateToURL(browser(), download_page_url);
1709 // As long as the policy is not present, extensions are considered dangerous.
1710 content::DownloadTestObserverTerminal download_observer(
1711 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1712 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1714 download_observer.WaitForFinished();
1716 // Install the policy and trigger another download.
1717 base::ListValue install_sources;
1718 install_sources.AppendString(install_source_url.spec());
1719 install_sources.AppendString(referrer_url.spec());
1721 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1722 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1723 UpdateProviderPolicy(policies);
1725 content::WindowedNotificationObserver observer(
1726 chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED,
1727 content::NotificationService::AllSources());
1730 // Note: Cannot check that the notification details match the expected
1731 // exception, since the details object has already been freed prior to
1732 // the completion of observer.Wait().
1734 // The first extension shouldn't be present, the second should be there.
1735 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1736 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1739 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1740 #if defined(OS_WIN) && defined(USE_ASH)
1741 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1742 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1746 // Verifies that the homepage can be configured with policies.
1747 // Set a default, and check that the home button navigates there.
1748 browser()->profile()->GetPrefs()->SetString(
1749 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1750 browser()->profile()->GetPrefs()->SetBoolean(
1751 prefs::kHomePageIsNewTabPage, false);
1752 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1753 browser()->profile()->GetHomePage());
1754 content::WebContents* contents =
1755 browser()->tab_strip_model()->GetActiveWebContents();
1756 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
1757 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1758 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1760 // Now override with policy.
1762 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1764 base::Value::CreateStringValue(chrome::kChromeUICreditsURL),
1766 UpdateProviderPolicy(policies);
1767 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1768 content::WaitForLoadStop(contents);
1769 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1771 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1772 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1773 UpdateProviderPolicy(policies);
1774 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1775 content::WaitForLoadStop(contents);
1776 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1779 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1780 // Verifies that incognito windows can't be opened when disabled by policy.
1782 const BrowserList* active_browser_list =
1783 BrowserList::GetInstance(chrome::GetActiveDesktop());
1785 // Disable incognito via policy and verify that incognito windows can't be
1787 EXPECT_EQ(1u, active_browser_list->size());
1788 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1790 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1791 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1792 UpdateProviderPolicy(policies);
1793 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1794 EXPECT_EQ(1u, active_browser_list->size());
1795 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1797 // Enable via policy and verify that incognito windows can be opened.
1798 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1799 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1800 UpdateProviderPolicy(policies);
1801 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1802 EXPECT_EQ(2u, active_browser_list->size());
1803 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1806 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1807 // Verifies that Javascript can be disabled.
1808 content::WebContents* contents =
1809 browser()->tab_strip_model()->GetActiveWebContents();
1810 EXPECT_TRUE(IsJavascriptEnabled(contents));
1811 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1812 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1813 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1815 // Disable Javascript via policy.
1817 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1818 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1819 UpdateProviderPolicy(policies);
1821 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1822 EXPECT_FALSE(IsJavascriptEnabled(contents));
1823 // Developer tools still work when javascript is disabled.
1824 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1825 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1826 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1827 // Javascript is always enabled for the internal pages.
1828 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1829 EXPECT_TRUE(IsJavascriptEnabled(contents));
1831 // The javascript content setting policy overrides the javascript policy.
1832 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1833 EXPECT_FALSE(IsJavascriptEnabled(contents));
1834 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1836 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL);
1837 UpdateProviderPolicy(policies);
1838 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1839 EXPECT_TRUE(IsJavascriptEnabled(contents));
1842 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1843 // Verifies that browsing history is not saved.
1845 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1846 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1847 UpdateProviderPolicy(policies);
1848 GURL url = ui_test_utils::GetTestUrl(
1849 base::FilePath(base::FilePath::kCurrentDirectory),
1850 base::FilePath(FILE_PATH_LITERAL("empty.html")));
1851 ui_test_utils::NavigateToURL(browser(), url);
1852 // Verify that the navigation wasn't saved in the history.
1853 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1854 EXPECT_EQ(0u, enumerator1.urls().size());
1856 // Now flip the policy and try again.
1857 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1858 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1859 UpdateProviderPolicy(policies);
1860 ui_test_utils::NavigateToURL(browser(), url);
1861 // Verify that the navigation was saved in the history.
1862 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1863 ASSERT_EQ(1u, enumerator2.urls().size());
1864 EXPECT_EQ(url, enumerator2.urls()[0]);
1867 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
1868 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
1869 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
1870 if (TranslateService::IsTranslateBubbleEnabled())
1873 test::ScopedCLDDynamicDataHarness dynamic_data_scope;
1874 ASSERT_NO_FATAL_FAILURE(dynamic_data_scope.Init());
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 ChromeTranslateClient* chrome_translate_client =
1907 ChromeTranslateClient::FromWebContents(contents);
1908 ASSERT_TRUE(chrome_translate_client);
1909 LanguageState& language_state = chrome_translate_client->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 infobars::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(translate::TRANSLATE_STEP_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, AccessibilityVirtualKeyboardEnabled) {
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());
2445 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2446 // Verify keyboard disabled by default.
2447 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2448 // Verify keyboard can be toggled by default.
2449 keyboard::SetTouchKeyboardEnabled(true);
2450 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2451 keyboard::SetTouchKeyboardEnabled(false);
2452 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2454 // Verify enabling the policy takes effect immediately and that that user
2455 // cannot disable the keyboard..
2457 policies.Set(key::kTouchVirtualKeyboardEnabled,
2458 POLICY_LEVEL_MANDATORY,
2460 base::Value::CreateBooleanValue(true),
2462 UpdateProviderPolicy(policies);
2463 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2464 keyboard::SetTouchKeyboardEnabled(false);
2465 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2467 // Verify that disabling the policy takes effect immediately and that the user
2468 // cannot enable the keyboard.
2469 policies.Set(key::kTouchVirtualKeyboardEnabled,
2470 POLICY_LEVEL_MANDATORY,
2472 base::Value::CreateBooleanValue(false),
2474 UpdateProviderPolicy(policies);
2475 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2476 keyboard::SetTouchKeyboardEnabled(true);
2477 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2484 static const char* kRestoredURLs[] = {
2485 "http://aaa.com/empty.html",
2486 "http://bbb.com/empty.html",
2489 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2490 return s.empty() || s[0] != '-';
2495 // Similar to PolicyTest but allows setting policies before the browser is
2496 // created. Each test parameter is a method that sets up the early policies
2497 // and stores the expected startup URLs in |expected_urls_|.
2498 class RestoreOnStartupPolicyTest
2499 : public PolicyTest,
2500 public testing::WithParamInterface<
2501 void (RestoreOnStartupPolicyTest::*)(void)> {
2503 RestoreOnStartupPolicyTest() {}
2504 virtual ~RestoreOnStartupPolicyTest() {}
2506 #if defined(OS_CHROMEOS)
2507 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2508 // TODO(nkostylev): Investigate if we can remove this switch.
2509 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2510 PolicyTest::SetUpCommandLine(command_line);
2514 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2515 PolicyTest::SetUpInProcessBrowserTestFixture();
2516 // Set early policies now, before the browser is created.
2517 (this->*(GetParam()))();
2519 // Remove the non-switch arguments, so that session restore kicks in for
2521 CommandLine* command_line = CommandLine::ForCurrentProcess();
2522 CommandLine::StringVector argv = command_line->argv();
2523 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2525 command_line->InitFromArgv(argv);
2526 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2527 command_line->argv().begin()));
2529 // Redirect the test URLs to the test data directory.
2530 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs));
2533 void HomepageIsNotNTP() {
2534 // Verifies that policy can set the startup pages to the homepage, when
2535 // the homepage is not the NTP.
2538 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2539 base::Value::CreateIntegerValue(
2540 SessionStartupPref::kPrefValueHomePage),
2543 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2544 base::Value::CreateBooleanValue(false), NULL);
2546 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2547 base::Value::CreateStringValue(kRestoredURLs[1]), NULL);
2548 provider_.UpdateChromePolicy(policies);
2550 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2553 void HomepageIsNTP() {
2554 // Verifies that policy can set the startup pages to the homepage, when
2555 // the homepage is the NTP.
2558 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2559 base::Value::CreateIntegerValue(
2560 SessionStartupPref::kPrefValueHomePage),
2563 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2564 base::Value::CreateBooleanValue(true), NULL);
2565 provider_.UpdateChromePolicy(policies);
2567 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2571 // Verifies that policy can set the startup pages to a list of URLs.
2572 base::ListValue urls;
2573 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2574 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i]));
2575 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2579 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2580 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs),
2583 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2584 urls.DeepCopy(), NULL);
2585 provider_.UpdateChromePolicy(policies);
2589 // Verifies that policy can set the startup page to the NTP.
2592 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2593 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab),
2595 provider_.UpdateChromePolicy(policies);
2596 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2600 // Verifies that policy can set the startup pages to the last session.
2603 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2604 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast),
2606 provider_.UpdateChromePolicy(policies);
2607 // This should restore the tabs opened at PRE_RunTest below.
2608 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2609 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2612 std::vector<GURL> expected_urls_;
2615 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2616 // Open some tabs to verify if they are restored after the browser restarts.
2617 // Most policy settings override this, except kPrefValueLast which enforces
2619 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2620 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2621 content::WindowedNotificationObserver observer(
2622 content::NOTIFICATION_LOAD_STOP,
2623 content::NotificationService::AllSources());
2624 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2625 content::PAGE_TRANSITION_LINK);
2630 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2631 #if defined(OS_WIN) && defined(USE_ASH)
2632 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2633 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2637 TabStripModel* model = browser()->tab_strip_model();
2638 int size = static_cast<int>(expected_urls_.size());
2639 EXPECT_EQ(size, model->count());
2640 for (int i = 0; i < size && i < model->count(); ++i) {
2641 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2645 INSTANTIATE_TEST_CASE_P(
2646 RestoreOnStartupPolicyTestInstance,
2647 RestoreOnStartupPolicyTest,
2648 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2649 &RestoreOnStartupPolicyTest::HomepageIsNTP,
2650 &RestoreOnStartupPolicyTest::ListOfURLs,
2651 &RestoreOnStartupPolicyTest::NTP,
2652 &RestoreOnStartupPolicyTest::Last));
2654 // Similar to PolicyTest but sets a couple of policies before the browser is
2656 class PolicyStatisticsCollectorTest : public PolicyTest {
2658 PolicyStatisticsCollectorTest() {}
2659 virtual ~PolicyStatisticsCollectorTest() {}
2661 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2662 PolicyTest::SetUpInProcessBrowserTestFixture();
2665 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2666 base::Value::CreateBooleanValue(true), NULL);
2668 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2669 base::Value::CreateBooleanValue(false), NULL);
2671 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2672 base::Value::CreateStringValue("http://chromium.org"), NULL);
2673 provider_.UpdateChromePolicy(policies);
2677 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2678 // Verifies that policy usage histograms are collected at startup.
2680 // BrowserPolicyConnector::Init() has already been called. Make sure the
2681 // CompleteInitialization() task has executed as well.
2682 content::RunAllPendingInMessageLoop();
2684 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
2685 std::string(url::kStandardSchemeSeparator) +
2686 std::string(content::kChromeUIHistogramHost));
2687 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
2688 content::WebContents* contents =
2689 browser()->tab_strip_model()->GetActiveWebContents();
2691 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2693 "var nodes = document.querySelectorAll('body > pre');"
2695 "for (var i = 0; i < nodes.length; ++i) {"
2696 " var text = nodes[i].innerHTML;"
2697 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
2702 "domAutomationController.send(result);",
2704 ASSERT_FALSE(text.empty());
2705 const std::string kExpectedLabel =
2706 "Histogram: Enterprise.Policies recorded 3 samples";
2707 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
2708 // HomepageLocation has policy ID 1.
2709 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
2710 // ShowHomeButton has policy ID 35.
2711 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
2712 // BookmarkBarEnabled has policy ID 82.
2713 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
2716 class MediaStreamDevicesControllerBrowserTest
2717 : public PolicyTest,
2718 public testing::WithParamInterface<bool> {
2720 MediaStreamDevicesControllerBrowserTest()
2721 : request_url_allowed_via_whitelist_(false) {
2722 policy_value_ = GetParam();
2724 virtual ~MediaStreamDevicesControllerBrowserTest() {}
2726 // Configure a given policy map.
2727 // The |policy_name| is the name of either the audio or video capture allow
2728 // policy and must never be NULL.
2729 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
2730 // policy is set. If non-NULL, the request_url_ will be set to be non empty
2731 // and the whitelist policy is set to contain either the |allow_rule| (if
2732 // non-NULL) or an "allow all" wildcard.
2733 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
2734 const char* whitelist_policy,
2735 const char* allow_rule) {
2736 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2737 base::Value::CreateBooleanValue(policy_value_), NULL);
2739 if (whitelist_policy) {
2740 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
2741 // in the media exceptions UI.
2742 // See discussion here: https://codereview.chromium.org/15738004/
2743 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
2745 // Add an entry to the whitelist that allows the specified URL regardless
2746 // of the setting of kAudioCapturedAllowed.
2747 request_url_ = GURL("http://www.example.com/foo");
2748 base::ListValue* list = new base::ListValue();
2750 list->AppendString(allow_rule);
2751 request_url_allowed_via_whitelist_ = true;
2753 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
2754 // We should ignore all wildcard entries in the whitelist, so even
2755 // though we've added an entry, it should be ignored and our expectation
2756 // is that the request has not been allowed via the whitelist.
2757 request_url_allowed_via_whitelist_ = false;
2759 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
2760 POLICY_SCOPE_USER, list, NULL);
2764 void Accept(const content::MediaStreamDevices& devices,
2765 content::MediaStreamRequestResult result,
2766 scoped_ptr<content::MediaStreamUI> ui) {
2767 if (policy_value_ || request_url_allowed_via_whitelist_) {
2768 ASSERT_EQ(1U, devices.size());
2769 ASSERT_EQ("fake_dev", devices[0].id);
2771 ASSERT_EQ(0U, devices.size());
2775 void FinishAudioTest() {
2776 content::MediaStreamRequest request(0, 0, 0,
2777 request_url_.GetOrigin(), false,
2778 content::MEDIA_DEVICE_ACCESS,
2779 std::string(), std::string(),
2780 content::MEDIA_DEVICE_AUDIO_CAPTURE,
2781 content::MEDIA_NO_SERVICE);
2782 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2783 // and microphone permissions at the same time.
2784 MediaStreamDevicesController controller(
2785 browser()->tab_strip_model()->GetActiveWebContents(), request,
2786 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2787 controller.Accept(false);
2789 base::MessageLoop::current()->QuitWhenIdle();
2792 void FinishVideoTest() {
2793 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2794 // and microphone permissions at the same time.
2795 content::MediaStreamRequest request(0, 0, 0,
2796 request_url_.GetOrigin(), false,
2797 content::MEDIA_DEVICE_ACCESS,
2800 content::MEDIA_NO_SERVICE,
2801 content::MEDIA_DEVICE_VIDEO_CAPTURE);
2802 MediaStreamDevicesController controller(
2803 browser()->tab_strip_model()->GetActiveWebContents(), request,
2804 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2805 controller.Accept(false);
2807 base::MessageLoop::current()->QuitWhenIdle();
2811 bool request_url_allowed_via_whitelist_;
2813 static const char kExampleRequestPattern[];
2817 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
2818 "http://[*.]example.com/";
2820 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2821 AudioCaptureAllowed) {
2822 content::MediaStreamDevices audio_devices;
2823 content::MediaStreamDevice fake_audio_device(
2824 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2825 audio_devices.push_back(fake_audio_device);
2828 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
2829 UpdateProviderPolicy(policies);
2831 content::BrowserThread::PostTaskAndReply(
2832 content::BrowserThread::IO, FROM_HERE,
2833 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
2834 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2836 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2839 base::MessageLoop::current()->Run();
2842 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2843 AudioCaptureAllowedUrls) {
2844 content::MediaStreamDevices audio_devices;
2845 content::MediaStreamDevice fake_audio_device(
2846 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2847 audio_devices.push_back(fake_audio_device);
2849 const char* allow_pattern[] = {
2850 kExampleRequestPattern,
2851 // This will set an allow-all policy whitelist. Since we do not allow
2852 // setting an allow-all entry in the whitelist, this entry should be ignored
2853 // and therefore the request should be denied.
2857 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2859 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
2860 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
2861 UpdateProviderPolicy(policies);
2863 content::BrowserThread::PostTaskAndReply(
2864 content::BrowserThread::IO, FROM_HERE,
2866 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
2867 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2870 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2873 base::MessageLoop::current()->Run();
2877 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2878 VideoCaptureAllowed) {
2879 content::MediaStreamDevices video_devices;
2880 content::MediaStreamDevice fake_video_device(
2881 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2882 video_devices.push_back(fake_video_device);
2885 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
2886 UpdateProviderPolicy(policies);
2888 content::BrowserThread::PostTaskAndReply(
2889 content::BrowserThread::IO, FROM_HERE,
2890 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
2891 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2893 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2896 base::MessageLoop::current()->Run();
2899 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2900 VideoCaptureAllowedUrls) {
2901 content::MediaStreamDevices video_devices;
2902 content::MediaStreamDevice fake_video_device(
2903 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2904 video_devices.push_back(fake_video_device);
2906 const char* allow_pattern[] = {
2907 kExampleRequestPattern,
2908 // This will set an allow-all policy whitelist. Since we do not allow
2909 // setting an allow-all entry in the whitelist, this entry should be ignored
2910 // and therefore the request should be denied.
2914 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2916 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
2917 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
2918 UpdateProviderPolicy(policies);
2920 content::BrowserThread::PostTaskAndReply(
2921 content::BrowserThread::IO, FROM_HERE,
2922 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
2923 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2926 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2929 base::MessageLoop::current()->Run();
2933 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
2934 MediaStreamDevicesControllerBrowserTest,
2937 #if !defined(OS_CHROMEOS)
2938 // Similar to PolicyTest but sets the proper policy before the browser is
2940 class PolicyVariationsServiceTest : public PolicyTest {
2942 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2943 PolicyTest::SetUpInProcessBrowserTestFixture();
2946 key::kVariationsRestrictParameter,
2947 POLICY_LEVEL_MANDATORY,
2949 base::Value::CreateStringValue("restricted"),
2951 provider_.UpdateChromePolicy(policies);
2955 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
2956 const std::string default_variations_url =
2957 chrome_variations::VariationsService::
2958 GetDefaultVariationsServerURLForTesting();
2961 chrome_variations::VariationsService::GetVariationsServerURL(
2962 g_browser_process->local_state());
2963 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
2965 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
2966 EXPECT_EQ("restricted", value);
2969 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
2970 base::ListValue blacklist;
2971 blacklist.Append(base::Value::CreateStringValue("host.name"));
2973 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2974 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2975 UpdateProviderPolicy(policies);
2977 PrefService* prefs = browser()->profile()->GetPrefs();
2978 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2979 prefs, "host.name"));
2980 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2981 prefs, "other.host.name"));
2984 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
2985 base::ListValue blacklist;
2986 blacklist.Append(base::Value::CreateStringValue("*"));
2988 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2989 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2990 UpdateProviderPolicy(policies);
2992 PrefService* prefs = browser()->profile()->GetPrefs();
2993 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2994 prefs, "host.name"));
2995 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2996 prefs, "other.host.name"));
2999 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3000 base::ListValue blacklist;
3001 blacklist.Append(base::Value::CreateStringValue("*"));
3002 base::ListValue whitelist;
3003 whitelist.Append(base::Value::CreateStringValue("host.name"));
3005 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3006 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3007 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3008 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3009 UpdateProviderPolicy(policies);
3011 PrefService* prefs = browser()->profile()->GetPrefs();
3012 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
3013 prefs, "host.name"));
3014 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
3015 prefs, "other.host.name"));
3018 IN_PROC_BROWSER_TEST_F(PolicyTest,
3019 EnableDeprecatedWebPlatformFeatures_ShowModalDialog) {
3020 base::ListValue enabled_features;
3021 enabled_features.Append(new base::StringValue(
3022 "ShowModalDialog_EffectiveUntil20150430"));
3024 policies.Set(key::kEnableDeprecatedWebPlatformFeatures,
3025 POLICY_LEVEL_MANDATORY,
3027 enabled_features.DeepCopy(),
3029 UpdateProviderPolicy(policies);
3031 // Policy only takes effect on new browsers, not existing browsers, so create
3033 Browser* browser2 = CreateBrowser(browser()->profile());
3034 ui_test_utils::NavigateToURL(browser2, GURL(url::kAboutBlankURL));
3035 bool result = false;
3036 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3037 browser2->tab_strip_model()->GetActiveWebContents(),
3038 "domAutomationController.send(window.showModalDialog !== undefined);",
3040 EXPECT_TRUE(result);
3043 #endif // !defined(CHROME_OS)
3045 } // namespace policy