Fix cpplint warnings in **/policy/
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blob6f61f15977a0802cf4320eac5537e021e334aa67
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <algorithm>
6 #include <string>
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.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/threading/sequenced_worker_pool.h"
27 #include "base/time/time.h"
28 #include "base/values.h"
29 #include "chrome/app/chrome_command_ids.h"
30 #include "chrome/browser/autocomplete/autocomplete_controller.h"
31 #include "chrome/browser/background/background_contents_service.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
35 #include "chrome/browser/devtools/devtools_window_testing.h"
36 #include "chrome/browser/download/download_prefs.h"
37 #include "chrome/browser/extensions/api/messaging/message_service.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/extension_management_constants.h"
40 #include "chrome/browser/extensions/extension_service.h"
41 #include "chrome/browser/extensions/shared_module_service.h"
42 #include "chrome/browser/extensions/unpacked_installer.h"
43 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
44 #include "chrome/browser/extensions/updater/extension_updater.h"
45 #include "chrome/browser/infobars/infobar_service.h"
46 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
47 #include "chrome/browser/media/media_stream_devices_controller.h"
48 #include "chrome/browser/metrics/variations/variations_service.h"
49 #include "chrome/browser/net/prediction_options.h"
50 #include "chrome/browser/net/ssl_config_service_manager.h"
51 #include "chrome/browser/net/url_request_mock_util.h"
52 #include "chrome/browser/plugins/plugin_prefs.h"
53 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
54 #include "chrome/browser/policy/profile_policy_connector.h"
55 #include "chrome/browser/policy/profile_policy_connector_factory.h"
56 #include "chrome/browser/prefs/session_startup_pref.h"
57 #include "chrome/browser/profiles/profile.h"
58 #include "chrome/browser/search/instant_service.h"
59 #include "chrome/browser/search/instant_service_factory.h"
60 #include "chrome/browser/search/search.h"
61 #include "chrome/browser/search_engines/template_url_service_factory.h"
62 #include "chrome/browser/translate/chrome_translate_client.h"
63 #include "chrome/browser/translate/cld_data_harness.h"
64 #include "chrome/browser/translate/cld_data_harness_factory.h"
65 #include "chrome/browser/translate/translate_service.h"
66 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
67 #include "chrome/browser/ui/browser.h"
68 #include "chrome/browser/ui/browser_commands.h"
69 #include "chrome/browser/ui/browser_list.h"
70 #include "chrome/browser/ui/browser_tabstrip.h"
71 #include "chrome/browser/ui/browser_window.h"
72 #include "chrome/browser/ui/host_desktop.h"
73 #include "chrome/browser/ui/location_bar/location_bar.h"
74 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
75 #include "chrome/browser/ui/omnibox/omnibox_view.h"
76 #include "chrome/browser/ui/tabs/tab_strip_model.h"
77 #include "chrome/common/chrome_paths.h"
78 #include "chrome/common/chrome_switches.h"
79 #include "chrome/common/extensions/extension_constants.h"
80 #include "chrome/common/extensions/features/feature_channel.h"
81 #include "chrome/common/pref_names.h"
82 #include "chrome/common/url_constants.h"
83 #include "chrome/grit/generated_resources.h"
84 #include "chrome/test/base/in_process_browser_test.h"
85 #include "chrome/test/base/test_switches.h"
86 #include "chrome/test/base/ui_test_utils.h"
87 #include "components/content_settings/core/common/content_settings.h"
88 #include "components/content_settings/core/common/content_settings_pattern.h"
89 #include "components/infobars/core/infobar.h"
90 #include "components/policy/core/browser/browser_policy_connector.h"
91 #include "components/policy/core/common/external_data_fetcher.h"
92 #include "components/policy/core/common/mock_configuration_policy_provider.h"
93 #include "components/policy/core/common/policy_map.h"
94 #include "components/policy/core/common/policy_pref_names.h"
95 #include "components/policy/core/common/policy_service.h"
96 #include "components/policy/core/common/policy_service_impl.h"
97 #include "components/search_engines/template_url.h"
98 #include "components/search_engines/template_url_service.h"
99 #include "components/translate/core/browser/language_state.h"
100 #include "components/translate/core/browser/translate_infobar_delegate.h"
101 #include "content/public/browser/browser_child_process_host_iterator.h"
102 #include "content/public/browser/browser_context.h"
103 #include "content/public/browser/browser_thread.h"
104 #include "content/public/browser/child_process_data.h"
105 #include "content/public/browser/download_item.h"
106 #include "content/public/browser/download_manager.h"
107 #include "content/public/browser/gpu_data_manager.h"
108 #include "content/public/browser/notification_details.h"
109 #include "content/public/browser/notification_observer.h"
110 #include "content/public/browser/notification_registrar.h"
111 #include "content/public/browser/notification_service.h"
112 #include "content/public/browser/notification_source.h"
113 #include "content/public/browser/notification_types.h"
114 #include "content/public/browser/plugin_service.h"
115 #include "content/public/browser/render_process_host.h"
116 #include "content/public/browser/render_view_host.h"
117 #include "content/public/browser/web_contents.h"
118 #include "content/public/common/content_constants.h"
119 #include "content/public/common/content_paths.h"
120 #include "content/public/common/process_type.h"
121 #include "content/public/common/result_codes.h"
122 #include "content/public/common/url_constants.h"
123 #include "content/public/common/webplugininfo.h"
124 #include "content/public/test/browser_test_utils.h"
125 #include "content/public/test/download_test_observer.h"
126 #include "content/public/test/mock_notification_observer.h"
127 #include "content/public/test/test_navigation_observer.h"
128 #include "content/public/test/test_utils.h"
129 #include "extensions/browser/extension_host.h"
130 #include "extensions/browser/extension_registry.h"
131 #include "extensions/browser/extension_system.h"
132 #include "extensions/browser/process_manager.h"
133 #include "extensions/browser/test_extension_registry_observer.h"
134 #include "extensions/browser/uninstall_reason.h"
135 #include "extensions/common/constants.h"
136 #include "extensions/common/extension.h"
137 #include "extensions/common/extension_set.h"
138 #include "extensions/common/manifest_handlers/shared_module_info.h"
139 #include "net/base/net_errors.h"
140 #include "net/base/net_util.h"
141 #include "net/base/url_util.h"
142 #include "net/http/http_stream_factory.h"
143 #include "net/ssl/ssl_config.h"
144 #include "net/ssl/ssl_config_service.h"
145 #include "net/test/url_request/url_request_failed_job.h"
146 #include "net/test/url_request/url_request_mock_http_job.h"
147 #include "net/url_request/url_request.h"
148 #include "net/url_request/url_request_filter.h"
149 #include "policy/policy_constants.h"
150 #include "testing/gmock/include/gmock/gmock.h"
151 #include "testing/gtest/include/gtest/gtest.h"
152 #include "third_party/WebKit/public/web/WebInputEvent.h"
153 #include "ui/base/l10n/l10n_util.h"
154 #include "ui/base/page_transition_types.h"
155 #include "ui/base/resource/resource_bundle.h"
156 #include "url/gurl.h"
158 #if defined(OS_CHROMEOS)
159 #include "ash/accelerators/accelerator_controller.h"
160 #include "ash/accelerators/accelerator_table.h"
161 #include "ash/shell.h"
162 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
163 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
164 #include "chrome/browser/profiles/profile_manager.h"
165 #include "chrome/browser/ui/ash/screenshot_taker.h"
166 #include "chromeos/audio/cras_audio_handler.h"
167 #include "ui/chromeos/accessibility_types.h"
168 #include "ui/keyboard/keyboard_util.h"
169 #endif
171 #if !defined(OS_MACOSX)
172 #include "base/basictypes.h"
173 #include "base/compiler_specific.h"
174 #include "chrome/browser/ui/extensions/application_launch.h"
175 #include "extensions/browser/app_window/app_window.h"
176 #include "extensions/browser/app_window/app_window_registry.h"
177 #include "extensions/browser/app_window/native_app_window.h"
178 #include "ui/base/window_open_disposition.h"
179 #endif
181 using content::BrowserThread;
182 using net::URLRequestMockHTTPJob;
183 using testing::Mock;
184 using testing::Return;
185 using testing::_;
187 namespace policy {
189 namespace {
191 #if defined(OS_CHROMEOS)
192 const int kOneHourInMs = 60 * 60 * 1000;
193 const int kThreeHoursInMs = 180 * 60 * 1000;
194 #endif
196 const char kURL[] = "http://example.com";
197 const char kCookieValue[] = "converted=true";
198 // Assigned to Philip J. Fry to fix eventually.
199 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
201 const base::FilePath::CharType kTestExtensionsDir[] =
202 FILE_PATH_LITERAL("extensions");
203 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
204 const base::FilePath::CharType kAdBlockCrxName[] =
205 FILE_PATH_LITERAL("adblock.crx");
206 const base::FilePath::CharType kHostedAppCrxName[] =
207 FILE_PATH_LITERAL("hosted_app.crx");
209 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
210 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
211 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
213 const base::FilePath::CharType kGood2CrxManifestName[] =
214 FILE_PATH_LITERAL("good2_update_manifest.xml");
215 const base::FilePath::CharType kGoodV1CrxManifestName[] =
216 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
217 const base::FilePath::CharType kGoodUnpackedExt[] =
218 FILE_PATH_LITERAL("good_unpacked");
219 const base::FilePath::CharType kAppUnpackedExt[] =
220 FILE_PATH_LITERAL("app");
222 #if !defined(OS_MACOSX)
223 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
224 FILE_PATH_LITERAL("fullscreen_app");
225 #endif // !defined(OS_MACOSX)
227 // Filters requests to the hosts in |urls| and redirects them to the test data
228 // dir through URLRequestMockHTTPJobs.
229 void RedirectHostsToTestData(const char* const urls[], size_t size) {
230 // Map the given hosts to the test data dir.
231 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
232 base::FilePath base_path;
233 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
234 for (size_t i = 0; i < size; ++i) {
235 const GURL url(urls[i]);
236 EXPECT_TRUE(url.is_valid());
237 filter->AddUrlInterceptor(url,
238 URLRequestMockHTTPJob::CreateInterceptor(
239 base_path, BrowserThread::GetBlockingPool()));
243 // Remove filters for requests to the hosts in |urls|.
244 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
245 // Map the given hosts to the test data dir.
246 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
247 for (size_t i = 0; i < size; ++i) {
248 const GURL url(urls[i]);
249 EXPECT_TRUE(url.is_valid());
250 filter->RemoveUrlHandler(url);
254 // Fails requests using ERR_CONNECTION_RESET.
255 net::URLRequestJob* FailedJobFactory(
256 net::URLRequest* request,
257 net::NetworkDelegate* network_delegate,
258 const std::string& scheme) {
259 return new net::URLRequestFailedJob(
260 request, network_delegate, net::ERR_CONNECTION_RESET);
263 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
264 class MakeRequestFail {
265 public:
266 // Sets up the filter on IO thread such that requests to |host| fail.
267 explicit MakeRequestFail(const std::string& host) : host_(host) {
268 BrowserThread::PostTaskAndReply(
269 BrowserThread::IO, FROM_HERE,
270 base::Bind(MakeRequestFailOnIO, host_),
271 base::MessageLoop::QuitClosure());
272 content::RunMessageLoop();
274 ~MakeRequestFail() {
275 BrowserThread::PostTaskAndReply(
276 BrowserThread::IO, FROM_HERE,
277 base::Bind(UndoMakeRequestFailOnIO, host_),
278 base::MessageLoop::QuitClosure());
279 content::RunMessageLoop();
282 private:
283 // Filters requests to the |host| such that they fail. Run on IO thread.
284 static void MakeRequestFailOnIO(const std::string& host) {
285 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
286 filter->AddHostnameHandler("http", host, &FailedJobFactory);
287 filter->AddHostnameHandler("https", host, &FailedJobFactory);
290 // Remove filters for requests to the |host|. Run on IO thread.
291 static void UndoMakeRequestFailOnIO(const std::string& host) {
292 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
293 filter->RemoveHostnameHandler("http", host);
294 filter->RemoveHostnameHandler("https", host);
297 const std::string host_;
300 // Verifies that the given url |spec| can be opened. This assumes that |spec|
301 // points at empty.html in the test data dir.
302 void CheckCanOpenURL(Browser* browser, const char* spec) {
303 GURL url(spec);
304 ui_test_utils::NavigateToURL(browser, url);
305 content::WebContents* contents =
306 browser->tab_strip_model()->GetActiveWebContents();
307 EXPECT_EQ(url, contents->GetURL());
308 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
309 base::string16 title =
310 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
311 EXPECT_NE(title, contents->GetTitle());
314 // Verifies that access to the given url |spec| is blocked.
315 void CheckURLIsBlocked(Browser* browser, const char* spec) {
316 GURL url(spec);
317 ui_test_utils::NavigateToURL(browser, url);
318 content::WebContents* contents =
319 browser->tab_strip_model()->GetActiveWebContents();
320 EXPECT_EQ(url, contents->GetURL());
321 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
322 base::string16 title =
323 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
324 EXPECT_EQ(title, contents->GetTitle());
326 // Verify that the expected error page is being displayed.
327 bool result = false;
328 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
329 contents,
330 "var textContent = document.body.textContent;"
331 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
332 "domAutomationController.send(hasError);",
333 &result));
334 EXPECT_TRUE(result);
337 // Downloads a file named |file| and expects it to be saved to |dir|, which
338 // must be empty.
339 void DownloadAndVerifyFile(
340 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
341 content::DownloadManager* download_manager =
342 content::BrowserContext::GetDownloadManager(browser->profile());
343 content::DownloadTestObserverTerminal observer(
344 download_manager, 1,
345 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
346 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
347 base::FilePath downloaded = dir.Append(file);
348 EXPECT_FALSE(base::PathExists(downloaded));
349 ui_test_utils::NavigateToURLWithDisposition(
350 browser, url, CURRENT_TAB,
351 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
352 observer.WaitForFinished();
353 EXPECT_EQ(
354 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
355 EXPECT_TRUE(base::PathExists(downloaded));
356 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
357 EXPECT_EQ(file, enumerator.Next().BaseName());
358 EXPECT_EQ(base::FilePath(), enumerator.Next());
361 #if defined(OS_CHROMEOS)
362 int CountScreenshots() {
363 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
364 ProfileManager::GetActiveUserProfile());
365 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
366 false, base::FileEnumerator::FILES,
367 "Screenshot*");
368 int count = 0;
369 while (!enumerator.Next().empty())
370 count++;
371 return count;
373 #endif
375 // Checks if WebGL is enabled in the given WebContents.
376 bool IsWebGLEnabled(content::WebContents* contents) {
377 bool result = false;
378 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
379 contents,
380 "var canvas = document.createElement('canvas');"
381 "var context = canvas.getContext('webgl');"
382 "domAutomationController.send(context != null);",
383 &result));
384 return result;
387 bool IsJavascriptEnabled(content::WebContents* contents) {
388 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
389 contents->GetMainFrame(), "123");
390 int result = 0;
391 if (!value->GetAsInteger(&result))
392 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
393 return result == 123;
396 bool IsNetworkPredictionEnabled(PrefService* prefs) {
397 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs);
400 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
401 const std::vector<content::WebPluginInfo>& in) {
402 *out = in;
403 base::MessageLoop::current()->QuitWhenIdle();
406 template<typename T>
407 void CopyValueAndQuit(T* out, T in) {
408 *out = in;
409 base::MessageLoop::current()->QuitWhenIdle();
412 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
413 content::PluginService* service = content::PluginService::GetInstance();
414 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
415 content::RunMessageLoop();
418 const content::WebPluginInfo* GetFlashPlugin(
419 const std::vector<content::WebPluginInfo>& plugins) {
420 const content::WebPluginInfo* flash = NULL;
421 for (size_t i = 0; i < plugins.size(); ++i) {
422 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
423 flash = &plugins[i];
424 break;
427 #if defined(OFFICIAL_BUILD)
428 // Official builds bundle Flash.
429 EXPECT_TRUE(flash);
430 #else
431 if (!flash)
432 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
433 #endif
434 return flash;
437 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
438 const content::WebPluginInfo* plugin,
439 bool enabled) {
440 bool ok = false;
441 plugin_prefs->EnablePlugin(enabled, plugin->path,
442 base::Bind(CopyValueAndQuit<bool>, &ok));
443 content::RunMessageLoop();
444 return ok;
447 int CountPluginsOnIOThread() {
448 int count = 0;
449 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
450 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
451 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
452 count++;
455 return count;
458 int CountPlugins() {
459 int count = -1;
460 BrowserThread::PostTaskAndReplyWithResult(
461 BrowserThread::IO, FROM_HERE,
462 base::Bind(CountPluginsOnIOThread),
463 base::Bind(CopyValueAndQuit<int>, &count));
464 content::RunMessageLoop();
465 EXPECT_GE(count, 0);
466 return count;
469 void FlushBlacklistPolicy() {
470 // Updates of the URLBlacklist are done on IO, after building the blacklist
471 // on the blocking pool, which is initiated from IO.
472 content::RunAllPendingInMessageLoop(BrowserThread::IO);
473 BrowserThread::GetBlockingPool()->FlushForTesting();
474 content::RunAllPendingInMessageLoop(BrowserThread::IO);
477 bool ContainsVisibleElement(content::WebContents* contents,
478 const std::string& id) {
479 bool result;
480 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
481 contents,
482 "var elem = document.getElementById('" + id + "');"
483 "domAutomationController.send(!!elem && !elem.hidden);",
484 &result));
485 return result;
488 #if defined(OS_CHROMEOS)
489 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
490 public:
491 TestAudioObserver() : output_mute_changed_count_(0) {
494 int output_mute_changed_count() const {
495 return output_mute_changed_count_;
498 virtual ~TestAudioObserver() {}
500 protected:
501 // chromeos::CrasAudioHandler::AudioObserver overrides.
502 virtual void OnOutputMuteChanged() override {
503 ++output_mute_changed_count_;
506 private:
507 int output_mute_changed_count_;
509 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
511 #endif
513 // This class waits until either a load stops or the WebContents is destroyed.
514 class WebContentsLoadedOrDestroyedWatcher
515 : public content::WebContentsObserver {
516 public:
517 explicit WebContentsLoadedOrDestroyedWatcher(
518 content::WebContents* web_contents);
519 ~WebContentsLoadedOrDestroyedWatcher() override;
521 // Waits until the WebContents's load is done or until it is destroyed.
522 void Wait();
524 // Overridden WebContentsObserver methods.
525 void WebContentsDestroyed() override;
526 void DidStopLoading(content::RenderViewHost* render_view_host) override;
528 private:
529 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
531 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
534 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
535 content::WebContents* web_contents)
536 : content::WebContentsObserver(web_contents),
537 message_loop_runner_(new content::MessageLoopRunner) {
540 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
542 void WebContentsLoadedOrDestroyedWatcher::Wait() {
543 message_loop_runner_->Run();
546 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
547 message_loop_runner_->Quit();
550 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
551 content::RenderViewHost* render_view_host) {
552 message_loop_runner_->Quit();
555 #if !defined(OS_MACOSX)
557 // Observer used to wait for the creation of a new app window.
558 class TestAddAppWindowObserver
559 : public extensions::AppWindowRegistry::Observer {
560 public:
561 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
562 ~TestAddAppWindowObserver() override;
564 // extensions::AppWindowRegistry::Observer:
565 void OnAppWindowAdded(extensions::AppWindow* app_window) override;
567 extensions::AppWindow* WaitForAppWindow();
569 private:
570 extensions::AppWindowRegistry* registry_; // Not owned.
571 extensions::AppWindow* window_; // Not owned.
572 base::RunLoop run_loop_;
574 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
577 TestAddAppWindowObserver::TestAddAppWindowObserver(
578 extensions::AppWindowRegistry* registry)
579 : registry_(registry), window_(NULL) {
580 registry_->AddObserver(this);
583 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
584 registry_->RemoveObserver(this);
587 void TestAddAppWindowObserver::OnAppWindowAdded(
588 extensions::AppWindow* app_window) {
589 window_ = app_window;
590 run_loop_.Quit();
593 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
594 run_loop_.Run();
595 return window_;
598 #endif
600 } // namespace
602 class PolicyTest : public InProcessBrowserTest {
603 protected:
604 PolicyTest() {}
605 ~PolicyTest() override {}
607 void SetUp() override {
608 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
609 InProcessBrowserTest::SetUp();
612 void SetUpInProcessBrowserTestFixture() override {
613 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
614 EXPECT_CALL(provider_, IsInitializationComplete(_))
615 .WillRepeatedly(Return(true));
616 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
619 void SetUpOnMainThread() override {
620 BrowserThread::PostTask(
621 BrowserThread::IO, FROM_HERE,
622 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
623 if (extension_service()->updater()) {
624 extension_service()->updater()->SetExtensionCacheForTesting(
625 test_extension_cache_.get());
629 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
630 // instead of chrome::DIR_TEST_DATA.
631 void ServeContentTestData() {
632 base::FilePath root_http;
633 PathService::Get(content::DIR_TEST_DATA, &root_http);
634 BrowserThread::PostTaskAndReply(
635 BrowserThread::IO,
636 FROM_HERE,
637 base::Bind(URLRequestMockHTTPJob::AddUrlHandler,
638 root_http,
639 make_scoped_refptr(BrowserThread::GetBlockingPool())),
640 base::MessageLoop::current()->QuitWhenIdleClosure());
641 content::RunMessageLoop();
644 void SetScreenshotPolicy(bool enabled) {
645 PolicyMap policies;
646 policies.Set(key::kDisableScreenshots,
647 POLICY_LEVEL_MANDATORY,
648 POLICY_SCOPE_USER,
649 new base::FundamentalValue(!enabled),
650 NULL);
651 UpdateProviderPolicy(policies);
654 #if defined(OS_CHROMEOS)
655 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
656 public:
657 virtual void OnScreenshotCompleted(
658 ScreenshotTakerObserver::Result screenshot_result,
659 const base::FilePath& screenshot_path) override {
660 BrowserThread::PostTaskAndReply(BrowserThread::IO,
661 FROM_HERE,
662 base::Bind(base::DoNothing),
663 base::MessageLoop::QuitClosure());
666 virtual ~QuitMessageLoopAfterScreenshot() {}
669 void TestScreenshotFile(bool enabled) {
670 // AddObserver is an ash-specific method, so just replace the screenshot
671 // taker with one we've created here.
672 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
673 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
674 // is tied to the test instead.
675 screenshot_taker->AddObserver(&observer_);
676 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
677 screenshot_taker.Pass());
679 SetScreenshotPolicy(enabled);
680 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
681 ash::TAKE_SCREENSHOT);
683 content::RunMessageLoop();
685 #endif
687 ExtensionService* extension_service() {
688 extensions::ExtensionSystem* system =
689 extensions::ExtensionSystem::Get(browser()->profile());
690 return system->extension_service();
693 const extensions::Extension* InstallExtension(
694 const base::FilePath::StringType& name) {
695 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
696 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
697 scoped_refptr<extensions::CrxInstaller> installer =
698 extensions::CrxInstaller::CreateSilent(extension_service());
699 installer->set_allow_silent_install(true);
700 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
701 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
703 content::WindowedNotificationObserver observer(
704 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
705 content::NotificationService::AllSources());
706 installer->InstallCrx(extension_path);
707 observer.Wait();
708 content::Details<const extensions::Extension> details = observer.details();
709 return details.ptr();
712 const extensions::Extension* LoadUnpackedExtension(
713 const base::FilePath::StringType& name, bool expect_success) {
714 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
715 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
716 scoped_refptr<extensions::UnpackedInstaller> installer =
717 extensions::UnpackedInstaller::Create(extension_service());
718 content::WindowedNotificationObserver observer(
719 expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
720 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
721 content::NotificationService::AllSources());
722 installer->Load(extension_path);
723 observer.Wait();
725 extensions::ExtensionRegistry* registry =
726 extensions::ExtensionRegistry::Get(browser()->profile());
727 for (const scoped_refptr<const extensions::Extension>& extension :
728 registry->enabled_extensions()) {
729 if (extension->path() == extension_path)
730 return extension.get();
732 return NULL;
735 void UninstallExtension(const std::string& id, bool expect_success) {
736 content::WindowedNotificationObserver observer(
737 expect_success
738 ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
739 : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
740 content::NotificationService::AllSources());
741 extension_service()->UninstallExtension(
743 extensions::UNINSTALL_REASON_FOR_TESTING,
744 base::Bind(&base::DoNothing),
745 NULL);
746 observer.Wait();
749 void DisableExtension(const std::string& id) {
750 content::WindowedNotificationObserver observer(
751 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
752 content::NotificationService::AllSources());
753 extension_service()->DisableExtension(id,
754 extensions::Extension::DISABLE_NONE);
755 observer.Wait();
758 void UpdateProviderPolicy(const PolicyMap& policy) {
759 provider_.UpdateChromePolicy(policy);
760 DCHECK(base::MessageLoop::current());
761 base::RunLoop loop;
762 loop.RunUntilIdle();
765 // Sends a mouse click at the given coordinates to the current renderer.
766 void PerformClick(int x, int y) {
767 content::WebContents* contents =
768 browser()->tab_strip_model()->GetActiveWebContents();
769 blink::WebMouseEvent click_event;
770 click_event.type = blink::WebInputEvent::MouseDown;
771 click_event.button = blink::WebMouseEvent::ButtonLeft;
772 click_event.clickCount = 1;
773 click_event.x = x;
774 click_event.y = y;
775 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
776 click_event.type = blink::WebInputEvent::MouseUp;
777 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
780 MockConfigurationPolicyProvider provider_;
781 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
782 #if defined(OS_CHROMEOS)
783 QuitMessageLoopAfterScreenshot observer_;
784 #endif
787 #if defined(OS_WIN)
788 // This policy only exists on Windows.
790 // Sets the locale policy before the browser is started.
791 class LocalePolicyTest : public PolicyTest {
792 public:
793 LocalePolicyTest() {}
794 virtual ~LocalePolicyTest() {}
796 virtual void SetUpInProcessBrowserTestFixture() override {
797 PolicyTest::SetUpInProcessBrowserTestFixture();
798 PolicyMap policies;
799 policies.Set(key::kApplicationLocaleValue,
800 POLICY_LEVEL_MANDATORY,
801 POLICY_SCOPE_USER,
802 new base::StringValue("fr"),
803 NULL);
804 provider_.UpdateChromePolicy(policies);
805 // The "en-US" ResourceBundle is always loaded before this step for tests,
806 // but in this test we want the browser to load the bundle as it
807 // normally would.
808 ResourceBundle::CleanupSharedInstance();
812 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
813 // Verifies that the default locale can be overridden with policy.
814 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
815 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
816 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
817 base::string16 title;
818 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
819 EXPECT_EQ(french_title, title);
821 // Make sure this is really French and differs from the English title.
822 std::string loaded =
823 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
824 EXPECT_EQ("en-US", loaded);
825 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
826 EXPECT_NE(french_title, english_title);
828 #endif
830 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
831 #if defined(OS_WIN) && defined(USE_ASH)
832 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
833 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
834 return;
835 #endif
837 // Verifies that the bookmarks bar can be forced to always or never show up.
839 // Test starts in about:blank.
840 PrefService* prefs = browser()->profile()->GetPrefs();
841 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
842 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
843 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
845 PolicyMap policies;
846 policies.Set(key::kBookmarkBarEnabled,
847 POLICY_LEVEL_MANDATORY,
848 POLICY_SCOPE_USER,
849 new base::FundamentalValue(true),
850 NULL);
851 UpdateProviderPolicy(policies);
852 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
853 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
854 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
856 // The NTP has special handling of the bookmark bar.
857 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
858 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
860 policies.Set(key::kBookmarkBarEnabled,
861 POLICY_LEVEL_MANDATORY,
862 POLICY_SCOPE_USER,
863 new base::FundamentalValue(false),
864 NULL);
865 UpdateProviderPolicy(policies);
866 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
867 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
868 // The bookmark bar is hidden in the NTP when disabled by policy.
869 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
871 policies.Clear();
872 UpdateProviderPolicy(policies);
873 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
874 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
875 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
876 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
879 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
880 // Verifies that cookies are deleted on shutdown. This test is split in 3
881 // parts because it spans 2 browser restarts.
883 Profile* profile = browser()->profile();
884 GURL url(kURL);
885 // No cookies at startup.
886 EXPECT_TRUE(content::GetCookies(profile, url).empty());
887 // Set a cookie now.
888 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
889 EXPECT_TRUE(content::SetCookie(profile, url, value));
890 // Verify it was set.
891 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
894 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
895 // Verify that the cookie persists across restarts.
896 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
897 // Now set the policy and the cookie should be gone after another restart.
898 PolicyMap policies;
899 policies.Set(key::kDefaultCookiesSetting,
900 POLICY_LEVEL_MANDATORY,
901 POLICY_SCOPE_USER,
902 new base::FundamentalValue(4),
903 NULL);
904 UpdateProviderPolicy(policies);
907 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
908 // Verify that the cookie is gone.
909 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
912 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
913 MakeRequestFail make_request_fail("search.example");
915 // Verifies that a default search is made using the provider configured via
916 // policy. Also checks that default search can be completely disabled.
917 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
918 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
919 const std::string kAlternateURL0(
920 "http://search.example/search#q={searchTerms}");
921 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
922 const std::string kSearchTermsReplacementKey("zekey");
923 const std::string kImageURL("http://test.com/searchbyimage/upload");
924 const std::string kImageURLPostParams(
925 "image_content=content,image_url=http://test.com/test.png");
926 const std::string kNewTabURL("http://search.example/newtab");
928 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
929 browser()->profile());
930 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
931 TemplateURL* default_search = service->GetDefaultSearchProvider();
932 ASSERT_TRUE(default_search);
933 EXPECT_NE(kKeyword, default_search->keyword());
934 EXPECT_NE(kSearchURL, default_search->url());
935 EXPECT_FALSE(
936 default_search->alternate_urls().size() == 2 &&
937 default_search->alternate_urls()[0] == kAlternateURL0 &&
938 default_search->alternate_urls()[1] == kAlternateURL1 &&
939 default_search->search_terms_replacement_key() ==
940 kSearchTermsReplacementKey &&
941 default_search->image_url() == kImageURL &&
942 default_search->image_url_post_params() == kImageURLPostParams &&
943 default_search->new_tab_url() == kNewTabURL);
945 // Override the default search provider using policies.
946 PolicyMap policies;
947 policies.Set(key::kDefaultSearchProviderEnabled,
948 POLICY_LEVEL_MANDATORY,
949 POLICY_SCOPE_USER,
950 new base::FundamentalValue(true),
951 NULL);
952 policies.Set(key::kDefaultSearchProviderKeyword,
953 POLICY_LEVEL_MANDATORY,
954 POLICY_SCOPE_USER,
955 new base::StringValue(kKeyword),
956 NULL);
957 policies.Set(key::kDefaultSearchProviderSearchURL,
958 POLICY_LEVEL_MANDATORY,
959 POLICY_SCOPE_USER,
960 new base::StringValue(kSearchURL),
961 NULL);
962 base::ListValue* alternate_urls = new base::ListValue();
963 alternate_urls->AppendString(kAlternateURL0);
964 alternate_urls->AppendString(kAlternateURL1);
965 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
966 POLICY_SCOPE_USER, alternate_urls, NULL);
967 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
968 POLICY_LEVEL_MANDATORY,
969 POLICY_SCOPE_USER,
970 new base::StringValue(kSearchTermsReplacementKey),
971 NULL);
972 policies.Set(key::kDefaultSearchProviderImageURL,
973 POLICY_LEVEL_MANDATORY,
974 POLICY_SCOPE_USER,
975 new base::StringValue(kImageURL),
976 NULL);
977 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
978 POLICY_LEVEL_MANDATORY,
979 POLICY_SCOPE_USER,
980 new base::StringValue(kImageURLPostParams),
981 NULL);
982 policies.Set(key::kDefaultSearchProviderNewTabURL,
983 POLICY_LEVEL_MANDATORY,
984 POLICY_SCOPE_USER,
985 new base::StringValue(kNewTabURL),
986 NULL);
987 UpdateProviderPolicy(policies);
988 default_search = service->GetDefaultSearchProvider();
989 ASSERT_TRUE(default_search);
990 EXPECT_EQ(kKeyword, default_search->keyword());
991 EXPECT_EQ(kSearchURL, default_search->url());
992 EXPECT_EQ(2U, default_search->alternate_urls().size());
993 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
994 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
995 EXPECT_EQ(kSearchTermsReplacementKey,
996 default_search->search_terms_replacement_key());
997 EXPECT_EQ(kImageURL, default_search->image_url());
998 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
999 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
1001 // Verify that searching from the omnibox uses kSearchURL.
1002 chrome::FocusLocationBar(browser());
1003 LocationBar* location_bar = browser()->window()->GetLocationBar();
1004 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1005 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1006 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1007 content::WebContents* web_contents =
1008 browser()->tab_strip_model()->GetActiveWebContents();
1009 GURL expected("http://search.example/search?q=stuff+to+search+for");
1010 EXPECT_EQ(expected, web_contents->GetURL());
1012 // Verify that searching from the omnibox can be disabled.
1013 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1014 policies.Set(key::kDefaultSearchProviderEnabled,
1015 POLICY_LEVEL_MANDATORY,
1016 POLICY_SCOPE_USER,
1017 new base::FundamentalValue(false),
1018 NULL);
1019 EXPECT_TRUE(service->GetDefaultSearchProvider());
1020 UpdateProviderPolicy(policies);
1021 EXPECT_FALSE(service->GetDefaultSearchProvider());
1022 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1023 // This means that submitting won't trigger any action.
1024 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1025 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1028 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1029 // Add an individual proxy policy value.
1030 PolicyMap policies;
1031 policies.Set(key::kProxyServerMode,
1032 POLICY_LEVEL_MANDATORY,
1033 POLICY_SCOPE_USER,
1034 new base::FundamentalValue(3),
1035 NULL);
1036 UpdateProviderPolicy(policies);
1038 // It should be removed and replaced with a dictionary.
1039 PolicyMap expected;
1040 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1041 expected_value->SetInteger(key::kProxyServerMode, 3);
1042 expected.Set(key::kProxySettings,
1043 POLICY_LEVEL_MANDATORY,
1044 POLICY_SCOPE_USER,
1045 expected_value.release(),
1046 NULL);
1048 // Check both the browser and the profile.
1049 const PolicyMap& actual_from_browser =
1050 g_browser_process->browser_policy_connector()
1051 ->GetPolicyService()
1052 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1053 EXPECT_TRUE(expected.Equals(actual_from_browser));
1054 const PolicyMap& actual_from_profile =
1055 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
1056 ->policy_service()
1057 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1058 EXPECT_TRUE(expected.Equals(actual_from_profile));
1061 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1062 // Makes the requests fail since all we want to check is that the redirection
1063 // is done properly.
1064 MakeRequestFail make_request_fail("google.com");
1066 // Verifies that requests to Google Search engine with the SafeSearch
1067 // enabled set the safe=active&ssui=on parameters at the end of the query.
1068 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1069 browser()->profile());
1070 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1072 // First check that nothing happens.
1073 content::TestNavigationObserver no_safesearch_observer(
1074 browser()->tab_strip_model()->GetActiveWebContents());
1075 chrome::FocusLocationBar(browser());
1076 LocationBar* location_bar = browser()->window()->GetLocationBar();
1077 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1078 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1079 no_safesearch_observer.Wait();
1080 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1081 content::WebContents* web_contents =
1082 browser()->tab_strip_model()->GetActiveWebContents();
1083 GURL expected_without("http://google.com/");
1084 EXPECT_EQ(expected_without, web_contents->GetURL());
1086 PrefService* prefs = browser()->profile()->GetPrefs();
1087 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1088 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1090 // Override the default SafeSearch setting using policies.
1091 PolicyMap policies;
1092 policies.Set(key::kForceSafeSearch,
1093 POLICY_LEVEL_MANDATORY,
1094 POLICY_SCOPE_USER,
1095 new base::FundamentalValue(true),
1096 NULL);
1097 UpdateProviderPolicy(policies);
1099 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1100 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1102 content::TestNavigationObserver safesearch_observer(
1103 browser()->tab_strip_model()->GetActiveWebContents());
1105 // Verify that searching from google.com works.
1106 chrome::FocusLocationBar(browser());
1107 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1108 safesearch_observer.Wait();
1109 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1110 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1111 std::string expected_url("http://google.com/?");
1112 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1113 chrome::kSafeSearchSsuiParameter;
1114 GURL expected_with_parameters(expected_url);
1115 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1118 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1119 MakeRequestFail make_request_fail("search.example");
1121 chrome::EnableQueryExtractionForTesting();
1123 // Verifies that a default search is made using the provider configured via
1124 // policy. Also checks that default search can be completely disabled.
1125 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1126 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1127 const std::string kInstantURL("http://does/not/exist");
1128 const std::string kAlternateURL0(
1129 "https://www.google.com/search#q={searchTerms}");
1130 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1131 const std::string kSearchTermsReplacementKey(
1132 "{google:instantExtendedEnabledKey}");
1134 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1135 browser()->profile());
1136 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1137 TemplateURL* default_search = service->GetDefaultSearchProvider();
1138 ASSERT_TRUE(default_search);
1139 EXPECT_NE(kKeyword, default_search->keyword());
1140 EXPECT_NE(kSearchURL, default_search->url());
1141 EXPECT_NE(kInstantURL, default_search->instant_url());
1142 EXPECT_FALSE(
1143 default_search->alternate_urls().size() == 2 &&
1144 default_search->alternate_urls()[0] == kAlternateURL0 &&
1145 default_search->alternate_urls()[1] == kAlternateURL1);
1147 // Override the default search provider using policies.
1148 PolicyMap policies;
1149 policies.Set(key::kDefaultSearchProviderEnabled,
1150 POLICY_LEVEL_MANDATORY,
1151 POLICY_SCOPE_USER,
1152 new base::FundamentalValue(true),
1153 NULL);
1154 policies.Set(key::kDefaultSearchProviderKeyword,
1155 POLICY_LEVEL_MANDATORY,
1156 POLICY_SCOPE_USER,
1157 new base::StringValue(kKeyword),
1158 NULL);
1159 policies.Set(key::kDefaultSearchProviderSearchURL,
1160 POLICY_LEVEL_MANDATORY,
1161 POLICY_SCOPE_USER,
1162 new base::StringValue(kSearchURL),
1163 NULL);
1164 policies.Set(key::kDefaultSearchProviderInstantURL,
1165 POLICY_LEVEL_MANDATORY,
1166 POLICY_SCOPE_USER,
1167 new base::StringValue(kInstantURL),
1168 NULL);
1169 base::ListValue* alternate_urls = new base::ListValue();
1170 alternate_urls->AppendString(kAlternateURL0);
1171 alternate_urls->AppendString(kAlternateURL1);
1172 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1173 POLICY_SCOPE_USER, alternate_urls, NULL);
1174 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1175 POLICY_LEVEL_MANDATORY,
1176 POLICY_SCOPE_USER,
1177 new base::StringValue(kSearchTermsReplacementKey),
1178 NULL);
1179 UpdateProviderPolicy(policies);
1180 default_search = service->GetDefaultSearchProvider();
1181 ASSERT_TRUE(default_search);
1182 EXPECT_EQ(kKeyword, default_search->keyword());
1183 EXPECT_EQ(kSearchURL, default_search->url());
1184 EXPECT_EQ(kInstantURL, default_search->instant_url());
1185 EXPECT_EQ(2U, default_search->alternate_urls().size());
1186 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1187 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1189 // Query terms replacement requires that the renderer process be a recognized
1190 // Instant renderer. Fake it.
1191 InstantService* instant_service =
1192 InstantServiceFactory::GetForProfile(browser()->profile());
1193 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1194 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1196 // Verify that searching from the omnibox does search term replacement with
1197 // first URL pattern.
1198 chrome::FocusLocationBar(browser());
1199 LocationBar* location_bar = browser()->window()->GetLocationBar();
1200 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1201 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1202 "https://www.google.com/?espv=1#q=foobar");
1203 EXPECT_TRUE(
1204 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1205 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1207 // Verify that not using espv=1 does not do search term replacement.
1208 chrome::FocusLocationBar(browser());
1209 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1210 "https://www.google.com/?q=foobar");
1211 EXPECT_FALSE(
1212 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1213 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1214 omnibox_view->GetText());
1216 // Verify that searching from the omnibox does search term replacement with
1217 // second URL pattern.
1218 chrome::FocusLocationBar(browser());
1219 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1220 "https://www.google.com/search?espv=1#q=banana");
1221 EXPECT_TRUE(
1222 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1223 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1225 // Verify that searching from the omnibox does search term replacement with
1226 // standard search URL pattern.
1227 chrome::FocusLocationBar(browser());
1228 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1229 "https://www.google.com/search?q=tractor+parts&espv=1");
1230 EXPECT_TRUE(
1231 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1232 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1234 // Verify that searching from the omnibox prioritizes hash over query.
1235 chrome::FocusLocationBar(browser());
1236 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1237 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1238 EXPECT_TRUE(
1239 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1240 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1243 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1244 // This test assumes Gpu access.
1245 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1246 return;
1248 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1249 // WebGL is enabled by default.
1250 content::WebContents* contents =
1251 browser()->tab_strip_model()->GetActiveWebContents();
1252 EXPECT_TRUE(IsWebGLEnabled(contents));
1253 // Disable with a policy.
1254 PolicyMap policies;
1255 policies.Set(key::kDisable3DAPIs,
1256 POLICY_LEVEL_MANDATORY,
1257 POLICY_SCOPE_USER,
1258 new base::FundamentalValue(true),
1259 NULL);
1260 UpdateProviderPolicy(policies);
1261 // Crash and reload the tab to get a new renderer.
1262 content::CrashTab(contents);
1263 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1264 EXPECT_FALSE(IsWebGLEnabled(contents));
1265 // Enable with a policy.
1266 policies.Set(key::kDisable3DAPIs,
1267 POLICY_LEVEL_MANDATORY,
1268 POLICY_SCOPE_USER,
1269 new base::FundamentalValue(false),
1270 NULL);
1271 UpdateProviderPolicy(policies);
1272 content::CrashTab(contents);
1273 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1274 EXPECT_TRUE(IsWebGLEnabled(contents));
1277 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1278 // Verifies that SPDY can be disable by policy.
1279 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1280 PolicyMap policies;
1281 policies.Set(key::kDisableSpdy,
1282 POLICY_LEVEL_MANDATORY,
1283 POLICY_SCOPE_USER,
1284 new base::FundamentalValue(true),
1285 NULL);
1286 UpdateProviderPolicy(policies);
1287 content::RunAllPendingInMessageLoop();
1288 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1289 // Verify that it can be force-enabled too.
1290 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1291 policies.Set(key::kDisableSpdy,
1292 POLICY_LEVEL_MANDATORY,
1293 POLICY_SCOPE_USER,
1294 new base::FundamentalValue(false),
1295 NULL);
1296 UpdateProviderPolicy(policies);
1297 content::RunAllPendingInMessageLoop();
1298 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1301 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1302 // Verifies that plugins can be forced to be disabled by policy.
1304 // Verify that the Flash plugin exists and that it can be enabled and disabled
1305 // by the user.
1306 std::vector<content::WebPluginInfo> plugins;
1307 GetPluginList(&plugins);
1308 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1309 if (!flash)
1310 return;
1311 PluginPrefs* plugin_prefs =
1312 PluginPrefs::GetForProfile(browser()->profile()).get();
1313 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1314 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1315 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1316 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1317 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1319 // Now disable it with a policy.
1320 base::ListValue disabled_plugins;
1321 disabled_plugins.Append(new base::StringValue("*Flash*"));
1322 PolicyMap policies;
1323 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1324 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1325 UpdateProviderPolicy(policies);
1326 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1327 // The user shouldn't be able to enable it.
1328 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1329 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1332 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1333 // Verifies that plugins with an exception in the blacklist can be enabled.
1335 // Verify that the Flash plugin exists and that it can be enabled and disabled
1336 // by the user.
1337 std::vector<content::WebPluginInfo> plugins;
1338 GetPluginList(&plugins);
1339 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1340 if (!flash)
1341 return;
1342 PluginPrefs* plugin_prefs =
1343 PluginPrefs::GetForProfile(browser()->profile()).get();
1344 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1346 // Disable all plugins.
1347 base::ListValue disabled_plugins;
1348 disabled_plugins.Append(new base::StringValue("*"));
1349 PolicyMap policies;
1350 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1351 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1352 UpdateProviderPolicy(policies);
1353 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1354 // The user shouldn't be able to enable it.
1355 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1356 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1358 // Now open an exception for flash.
1359 base::ListValue disabled_plugins_exceptions;
1360 disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1361 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1362 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1363 UpdateProviderPolicy(policies);
1364 // It should revert to the user's preference automatically.
1365 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1366 // And the user should be able to disable and enable again.
1367 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1368 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1369 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1370 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1373 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1374 // Verifies that a plugin can be force-installed with a policy.
1375 std::vector<content::WebPluginInfo> plugins;
1376 GetPluginList(&plugins);
1377 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1378 if (!flash)
1379 return;
1380 PluginPrefs* plugin_prefs =
1381 PluginPrefs::GetForProfile(browser()->profile()).get();
1382 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1384 // The user disables it and then a policy forces it to be enabled.
1385 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1386 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1387 base::ListValue plugin_list;
1388 plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1389 PolicyMap policies;
1390 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1391 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1392 UpdateProviderPolicy(policies);
1393 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1394 // The user can't disable it anymore.
1395 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1396 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1398 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1399 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1400 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1401 UpdateProviderPolicy(policies);
1402 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1405 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1406 // Verifies that dangerous plugins can be always authorized to run with
1407 // a policy.
1409 // Verify that the test page exists. It is only present in checkouts with
1410 // src-internal.
1411 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1412 base::FilePath(FILE_PATH_LITERAL("plugin")),
1413 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1414 LOG(INFO) <<
1415 "Test skipped because plugin/quicktime.html test file wasn't found.";
1416 return;
1419 ServeContentTestData();
1420 // No plugins at startup.
1421 EXPECT_EQ(0, CountPlugins());
1423 content::WebContents* contents =
1424 browser()->tab_strip_model()->GetActiveWebContents();
1425 ASSERT_TRUE(contents);
1426 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1427 ASSERT_TRUE(infobar_service);
1428 EXPECT_EQ(0u, infobar_service->infobar_count());
1430 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1431 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1432 ui_test_utils::NavigateToURL(browser(), url);
1433 // This should have triggered the dangerous plugin infobar.
1434 ASSERT_EQ(1u, infobar_service->infobar_count());
1435 EXPECT_TRUE(
1436 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1437 // And the plugin isn't running.
1438 EXPECT_EQ(0, CountPlugins());
1440 // Now set a policy to always authorize this.
1441 PolicyMap policies;
1442 policies.Set(key::kAlwaysAuthorizePlugins,
1443 POLICY_LEVEL_MANDATORY,
1444 POLICY_SCOPE_USER,
1445 new base::FundamentalValue(true),
1446 NULL);
1447 UpdateProviderPolicy(policies);
1448 // Reloading the page shouldn't trigger the infobar this time.
1449 ui_test_utils::NavigateToURL(browser(), url);
1450 EXPECT_EQ(0u, infobar_service->infobar_count());
1451 // And the plugin started automatically.
1452 EXPECT_EQ(1, CountPlugins());
1455 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1456 // Verifies that access to the developer tools can be disabled.
1458 // Open devtools.
1459 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1460 content::WebContents* contents =
1461 browser()->tab_strip_model()->GetActiveWebContents();
1462 DevToolsWindow* devtools_window =
1463 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1464 EXPECT_TRUE(devtools_window);
1466 // Disable devtools via policy.
1467 PolicyMap policies;
1468 policies.Set(key::kDeveloperToolsDisabled,
1469 POLICY_LEVEL_MANDATORY,
1470 POLICY_SCOPE_USER,
1471 new base::FundamentalValue(true),
1472 NULL);
1473 content::WindowedNotificationObserver close_observer(
1474 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1475 content::Source<content::WebContents>(
1476 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1477 UpdateProviderPolicy(policies);
1478 // wait for devtools close
1479 close_observer.Wait();
1480 // The existing devtools window should have closed.
1481 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1482 // And it's not possible to open it again.
1483 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1484 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1487 // TODO(samarth): remove along with rest of NTP4 code.
1488 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1489 #if defined(OS_WIN) && defined(USE_ASH)
1490 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1491 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1492 return;
1493 #endif
1495 // Verifies that the web store icons can be hidden from the new tab page.
1497 // Open new tab page and look for the web store icons.
1498 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1499 content::WebContents* contents =
1500 browser()->tab_strip_model()->GetActiveWebContents();
1502 #if !defined(OS_CHROMEOS)
1503 // Look for web store's app ID in the apps page.
1504 EXPECT_TRUE(ContainsVisibleElement(contents,
1505 "ahfgeienlihckogmohjhadlkjgocpleb"));
1506 #endif
1508 // The next NTP has no footer.
1509 if (ContainsVisibleElement(contents, "footer"))
1510 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1512 // Turn off the web store icons.
1513 PolicyMap policies;
1514 policies.Set(key::kHideWebStoreIcon,
1515 POLICY_LEVEL_MANDATORY,
1516 POLICY_SCOPE_USER,
1517 new base::FundamentalValue(true),
1518 NULL);
1519 UpdateProviderPolicy(policies);
1521 // The web store icons should now be hidden.
1522 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1523 EXPECT_FALSE(ContainsVisibleElement(contents,
1524 "ahfgeienlihckogmohjhadlkjgocpleb"));
1525 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1528 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1529 // Verifies that the download directory can be forced by policy.
1531 // Set the initial download directory.
1532 base::ScopedTempDir initial_dir;
1533 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1534 browser()->profile()->GetPrefs()->SetFilePath(
1535 prefs::kDownloadDefaultDirectory, initial_dir.path());
1536 // Don't prompt for the download location during this test.
1537 browser()->profile()->GetPrefs()->SetBoolean(
1538 prefs::kPromptForDownload, false);
1540 // Verify that downloads end up on the default directory.
1541 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1542 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1543 base::DieFileDie(initial_dir.path().Append(file), false);
1545 // Override the download directory with the policy and verify a download.
1546 base::ScopedTempDir forced_dir;
1547 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1548 PolicyMap policies;
1549 policies.Set(key::kDownloadDirectory,
1550 POLICY_LEVEL_MANDATORY,
1551 POLICY_SCOPE_USER,
1552 new base::StringValue(forced_dir.path().value()),
1553 NULL);
1554 UpdateProviderPolicy(policies);
1555 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1556 // Verify that the first download location wasn't affected.
1557 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1560 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1561 // Verifies that blacklisted extensions can't be installed.
1562 ExtensionService* service = extension_service();
1563 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1564 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1565 base::ListValue blacklist;
1566 blacklist.Append(new base::StringValue(kGoodCrxId));
1567 PolicyMap policies;
1568 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1569 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1570 UpdateProviderPolicy(policies);
1572 // "good.crx" is blacklisted.
1573 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1574 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1576 // "adblock.crx" is not.
1577 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1578 ASSERT_TRUE(adblock);
1579 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1580 EXPECT_EQ(adblock,
1581 service->GetExtensionById(kAdBlockCrxId, true));
1584 // Flaky on windows; http://crbug.com/307994.
1585 #if defined(OS_WIN)
1586 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1587 #else
1588 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1589 #endif
1590 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1591 // Verify that a wildcard blacklist takes effect.
1592 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1593 ExtensionService* service = extension_service();
1594 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1595 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1596 base::ListValue blacklist;
1597 blacklist.Append(new base::StringValue("*"));
1598 PolicyMap policies;
1599 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1600 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1601 UpdateProviderPolicy(policies);
1603 // AdBlock was automatically removed.
1604 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1606 // And can't be installed again, nor can good.crx.
1607 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1608 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1609 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1610 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1613 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
1614 // Verifies that shared_modules are not affected by the blacklist.
1616 const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
1617 const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
1619 // Make sure that "import" and "export" are available to these extension IDs
1620 // by mocking the release channel.
1621 extensions::ScopedCurrentChannel channel(chrome::VersionInfo::CHANNEL_DEV);
1623 // Verify that the extensions are not installed initially.
1624 ExtensionService* service = extension_service();
1625 ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
1626 ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
1628 // Mock the webstore update URL. This is where the shared module extension
1629 // will be installed from.
1630 base::FilePath update_xml_path = base::FilePath(kTestExtensionsDir)
1631 .AppendASCII("policy_shared_module")
1632 .AppendASCII("update.xml");
1633 GURL update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path));
1634 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1635 switches::kAppsGalleryUpdateURL, update_xml_url.spec());
1636 ui_test_utils::NavigateToURL(browser(), update_xml_url);
1638 // Blacklist "*" but force-install the importer extension. The shared module
1639 // should be automatically installed too.
1640 base::ListValue blacklist;
1641 blacklist.AppendString("*");
1642 base::ListValue forcelist;
1643 forcelist.AppendString(
1644 base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
1645 PolicyMap policies;
1646 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1647 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1648 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1649 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1651 extensions::ExtensionRegistry* registry =
1652 extensions::ExtensionRegistry::Get(browser()->profile());
1653 extensions::TestExtensionRegistryObserver observe_importer(
1654 registry, kImporterId);
1655 extensions::TestExtensionRegistryObserver observe_shared_module(
1656 registry, kSharedModuleId);
1657 UpdateProviderPolicy(policies);
1658 observe_importer.WaitForExtensionLoaded();
1659 observe_shared_module.WaitForExtensionLoaded();
1661 // Verify that both extensions got installed.
1662 const extensions::Extension* importer =
1663 service->GetExtensionById(kImporterId, true);
1664 ASSERT_TRUE(importer);
1665 EXPECT_EQ(kImporterId, importer->id());
1666 const extensions::Extension* shared_module =
1667 service->GetExtensionById(kSharedModuleId, true);
1668 ASSERT_TRUE(shared_module);
1669 EXPECT_EQ(kSharedModuleId, shared_module->id());
1670 EXPECT_TRUE(shared_module->is_shared_module());
1672 // Verify the dependency.
1673 scoped_ptr<extensions::ExtensionSet> set =
1674 service->shared_module_service()->GetDependentExtensions(shared_module);
1675 ASSERT_TRUE(set);
1676 EXPECT_EQ(1u, set->size());
1677 EXPECT_TRUE(set->Contains(importer->id()));
1679 std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
1680 extensions::SharedModuleInfo::GetImports(importer);
1681 ASSERT_EQ(1u, imports.size());
1682 EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
1685 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1686 // Verifies that the whitelist can open exceptions to the blacklist.
1687 ExtensionService* service = extension_service();
1688 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1689 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1690 base::ListValue blacklist;
1691 blacklist.Append(new base::StringValue("*"));
1692 base::ListValue whitelist;
1693 whitelist.Append(new base::StringValue(kGoodCrxId));
1694 PolicyMap policies;
1695 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1696 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1697 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1698 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1699 UpdateProviderPolicy(policies);
1700 // "adblock.crx" is blacklisted.
1701 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1702 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1703 // "good.crx" has a whitelist exception.
1704 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1705 ASSERT_TRUE(good);
1706 EXPECT_EQ(kGoodCrxId, good->id());
1707 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1708 // The user can also remove this extension.
1709 UninstallExtension(kGoodCrxId, true);
1712 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1713 // Verifies that extensions that are force-installed by policies are
1714 // installed and can't be uninstalled.
1715 ExtensionService* service = extension_service();
1716 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1718 // Extensions that are force-installed come from an update URL, which defaults
1719 // to the webstore. Use a mock URL for this test with an update manifest
1720 // that includes "good_v1.crx".
1721 base::FilePath path =
1722 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1723 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1725 // Setting the forcelist extension should install "good_v1.crx".
1726 base::ListValue forcelist;
1727 forcelist.Append(new base::StringValue(
1728 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1729 PolicyMap policies;
1730 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1731 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1732 content::WindowedNotificationObserver observer(
1733 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1734 content::NotificationService::AllSources());
1735 UpdateProviderPolicy(policies);
1736 observer.Wait();
1737 // Note: Cannot check that the notification details match the expected
1738 // exception, since the details object has already been freed prior to
1739 // the completion of observer.Wait().
1741 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1743 // The user is not allowed to uninstall force-installed extensions.
1744 UninstallExtension(kGoodCrxId, false);
1746 // The user is not allowed to load an unpacked extension with the
1747 // same ID as a force-installed extension.
1748 LoadUnpackedExtension(kGoodUnpackedExt, false);
1750 // Loading other unpacked extensions are not blocked.
1751 LoadUnpackedExtension(kAppUnpackedExt, true);
1753 const std::string old_version_number =
1754 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1756 base::FilePath test_path;
1757 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1759 TestRequestInterceptor interceptor(
1760 "update.extension",
1761 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1762 interceptor.PushJobCallback(
1763 TestRequestInterceptor::FileJob(
1764 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1766 // Updating the force-installed extension.
1767 extensions::ExtensionUpdater* updater = service->updater();
1768 extensions::ExtensionUpdater::CheckParams params;
1769 params.install_immediately = true;
1770 content::WindowedNotificationObserver update_observer(
1771 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1772 content::NotificationService::AllSources());
1773 updater->CheckNow(params);
1774 update_observer.Wait();
1776 const base::Version* new_version =
1777 service->GetExtensionById(kGoodCrxId, true)->version();
1778 ASSERT_TRUE(new_version->IsValid());
1779 base::Version old_version(old_version_number);
1780 ASSERT_TRUE(old_version.IsValid());
1782 EXPECT_EQ(1, new_version->CompareTo(old_version));
1784 EXPECT_EQ(0u, interceptor.GetPendingSize());
1786 // Wait until any background pages belonging to force-installed extensions
1787 // have been loaded.
1788 extensions::ProcessManager* manager =
1789 extensions::ProcessManager::Get(browser()->profile());
1790 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1791 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1792 all_views.begin();
1793 iter != all_views.end();) {
1794 if (!(*iter)->IsLoading()) {
1795 ++iter;
1796 } else {
1797 content::WebContents* web_contents =
1798 content::WebContents::FromRenderViewHost(*iter);
1799 ASSERT_TRUE(web_contents);
1800 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1802 // Test activity may have modified the set of extension processes during
1803 // message processing, so re-start the iteration to catch added/removed
1804 // processes.
1805 all_views = manager->GetAllViews();
1806 iter = all_views.begin();
1810 // Test policy-installed extensions are reloaded when killed.
1811 BackgroundContentsService::
1812 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1813 content::WindowedNotificationObserver extension_crashed_observer(
1814 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1815 content::NotificationService::AllSources());
1816 content::WindowedNotificationObserver extension_loaded_observer(
1817 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1818 content::NotificationService::AllSources());
1819 extensions::ExtensionHost* extension_host =
1820 extensions::ProcessManager::Get(browser()->profile())
1821 ->GetBackgroundHostForExtension(kGoodCrxId);
1822 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1823 content::RESULT_CODE_KILLED, false);
1824 extension_crashed_observer.Wait();
1825 extension_loaded_observer.Wait();
1828 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1829 // Verifies that extensions that are recommended-installed by policies are
1830 // installed, can be disabled but not uninstalled.
1831 ExtensionService* service = extension_service();
1832 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1834 base::FilePath path =
1835 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1836 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1838 // Setting the forcelist extension should install "good_v1.crx".
1839 base::DictionaryValue dict_value;
1840 dict_value.SetString(std::string(kGoodCrxId) + "." +
1841 extensions::schema_constants::kInstallationMode,
1842 extensions::schema_constants::kNormalInstalled);
1843 dict_value.SetString(
1844 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1845 url.spec());
1846 PolicyMap policies;
1847 policies.Set(key::kExtensionSettings,
1848 POLICY_LEVEL_MANDATORY,
1849 POLICY_SCOPE_USER,
1850 dict_value.DeepCopy(),
1851 NULL);
1852 content::WindowedNotificationObserver observer(
1853 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1854 content::NotificationService::AllSources());
1855 UpdateProviderPolicy(policies);
1856 observer.Wait();
1858 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1860 // The user is not allowed to uninstall recommended-installed extensions.
1861 UninstallExtension(kGoodCrxId, false);
1863 // Explictly re-enables the extension.
1864 service->EnableExtension(kGoodCrxId);
1866 // But the user is allowed to disable them.
1867 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1868 DisableExtension(kGoodCrxId);
1869 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1872 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1873 // Verifies that extensions are blocked if policy specifies an allowed types
1874 // list and the extension's type is not on that list.
1875 ExtensionService* service = extension_service();
1876 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1877 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1879 base::ListValue allowed_types;
1880 allowed_types.AppendString("hosted_app");
1881 PolicyMap policies;
1882 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1883 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1884 UpdateProviderPolicy(policies);
1886 // "good.crx" is blocked.
1887 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1888 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1890 // "hosted_app.crx" is of a whitelisted type.
1891 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1892 ASSERT_TRUE(hosted_app);
1893 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1894 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1896 // The user can remove the extension.
1897 UninstallExtension(kHostedAppCrxId, true);
1900 // Checks that a click on an extension CRX download triggers the extension
1901 // installation prompt without further user interaction when the source is
1902 // whitelisted by policy.
1903 // Flaky on windows; http://crbug.com/295729 .
1904 #if defined(OS_WIN)
1905 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1906 #else
1907 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1908 #endif
1909 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1910 ExtensionInstallPrompt::g_auto_confirm_for_tests =
1911 ExtensionInstallPrompt::ACCEPT;
1913 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1914 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1915 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1916 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1918 base::ScopedTempDir download_directory;
1919 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1920 DownloadPrefs* download_prefs =
1921 DownloadPrefs::FromBrowserContext(browser()->profile());
1922 download_prefs->SetDownloadPath(download_directory.path());
1924 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1925 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1926 ui_test_utils::NavigateToURL(browser(), download_page_url);
1928 // As long as the policy is not present, extensions are considered dangerous.
1929 content::DownloadTestObserverTerminal download_observer(
1930 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1931 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1932 PerformClick(0, 0);
1933 download_observer.WaitForFinished();
1935 // Install the policy and trigger another download.
1936 base::ListValue install_sources;
1937 install_sources.AppendString(install_source_url.spec());
1938 install_sources.AppendString(referrer_url.spec());
1939 PolicyMap policies;
1940 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1941 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1942 UpdateProviderPolicy(policies);
1944 content::WindowedNotificationObserver observer(
1945 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1946 content::NotificationService::AllSources());
1947 PerformClick(1, 0);
1948 observer.Wait();
1949 // Note: Cannot check that the notification details match the expected
1950 // exception, since the details object has already been freed prior to
1951 // the completion of observer.Wait().
1953 // The first extension shouldn't be present, the second should be there.
1954 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1955 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1958 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1959 #if defined(OS_WIN) && defined(USE_ASH)
1960 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1961 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1962 return;
1963 #endif
1965 // Verifies that the homepage can be configured with policies.
1966 // Set a default, and check that the home button navigates there.
1967 browser()->profile()->GetPrefs()->SetString(
1968 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1969 browser()->profile()->GetPrefs()->SetBoolean(
1970 prefs::kHomePageIsNewTabPage, false);
1971 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1972 browser()->profile()->GetHomePage());
1973 content::WebContents* contents =
1974 browser()->tab_strip_model()->GetActiveWebContents();
1975 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
1976 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1977 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1979 // Now override with policy.
1980 PolicyMap policies;
1981 policies.Set(key::kHomepageLocation,
1982 POLICY_LEVEL_MANDATORY,
1983 POLICY_SCOPE_USER,
1984 new base::StringValue(chrome::kChromeUICreditsURL),
1985 NULL);
1986 UpdateProviderPolicy(policies);
1987 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1988 content::WaitForLoadStop(contents);
1989 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1991 policies.Set(key::kHomepageIsNewTabPage,
1992 POLICY_LEVEL_MANDATORY,
1993 POLICY_SCOPE_USER,
1994 new base::FundamentalValue(true),
1995 NULL);
1996 UpdateProviderPolicy(policies);
1997 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1998 content::WaitForLoadStop(contents);
1999 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
2002 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
2003 // Verifies that incognito windows can't be opened when disabled by policy.
2005 const BrowserList* active_browser_list =
2006 BrowserList::GetInstance(chrome::GetActiveDesktop());
2008 // Disable incognito via policy and verify that incognito windows can't be
2009 // opened.
2010 EXPECT_EQ(1u, active_browser_list->size());
2011 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2012 PolicyMap policies;
2013 policies.Set(key::kIncognitoEnabled,
2014 POLICY_LEVEL_MANDATORY,
2015 POLICY_SCOPE_USER,
2016 new base::FundamentalValue(false),
2017 NULL);
2018 UpdateProviderPolicy(policies);
2019 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2020 EXPECT_EQ(1u, active_browser_list->size());
2021 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2023 // Enable via policy and verify that incognito windows can be opened.
2024 policies.Set(key::kIncognitoEnabled,
2025 POLICY_LEVEL_MANDATORY,
2026 POLICY_SCOPE_USER,
2027 new base::FundamentalValue(true),
2028 NULL);
2029 UpdateProviderPolicy(policies);
2030 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2031 EXPECT_EQ(2u, active_browser_list->size());
2032 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2035 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
2036 // Verifies that Javascript can be disabled.
2037 content::WebContents* contents =
2038 browser()->tab_strip_model()->GetActiveWebContents();
2039 EXPECT_TRUE(IsJavascriptEnabled(contents));
2040 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2041 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2042 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2044 // Disable Javascript via policy.
2045 PolicyMap policies;
2046 policies.Set(key::kJavascriptEnabled,
2047 POLICY_LEVEL_MANDATORY,
2048 POLICY_SCOPE_USER,
2049 new base::FundamentalValue(false),
2050 NULL);
2051 UpdateProviderPolicy(policies);
2052 // Reload the page.
2053 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2054 EXPECT_FALSE(IsJavascriptEnabled(contents));
2055 // Developer tools still work when javascript is disabled.
2056 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2057 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2058 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2059 // Javascript is always enabled for the internal pages.
2060 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
2061 EXPECT_TRUE(IsJavascriptEnabled(contents));
2063 // The javascript content setting policy overrides the javascript policy.
2064 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2065 EXPECT_FALSE(IsJavascriptEnabled(contents));
2066 policies.Set(key::kDefaultJavaScriptSetting,
2067 POLICY_LEVEL_MANDATORY,
2068 POLICY_SCOPE_USER,
2069 new base::FundamentalValue(CONTENT_SETTING_ALLOW),
2070 NULL);
2071 UpdateProviderPolicy(policies);
2072 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2073 EXPECT_TRUE(IsJavascriptEnabled(contents));
2076 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2077 PrefService* prefs = browser()->profile()->GetPrefs();
2079 // Enabled by default.
2080 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2082 // Disable by old, deprecated policy.
2083 PolicyMap policies;
2084 policies.Set(key::kDnsPrefetchingEnabled,
2085 POLICY_LEVEL_MANDATORY,
2086 POLICY_SCOPE_USER,
2087 new base::FundamentalValue(false),
2088 NULL);
2089 UpdateProviderPolicy(policies);
2091 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2093 // Enabled by new policy, this should override old one.
2094 policies.Set(
2095 key::kNetworkPredictionOptions,
2096 POLICY_LEVEL_MANDATORY,
2097 POLICY_SCOPE_USER,
2098 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2099 NULL);
2100 UpdateProviderPolicy(policies);
2102 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2105 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2106 // Verifies that browsing history is not saved.
2107 PolicyMap policies;
2108 policies.Set(key::kSavingBrowserHistoryDisabled,
2109 POLICY_LEVEL_MANDATORY,
2110 POLICY_SCOPE_USER,
2111 new base::FundamentalValue(true),
2112 NULL);
2113 UpdateProviderPolicy(policies);
2114 GURL url = ui_test_utils::GetTestUrl(
2115 base::FilePath(base::FilePath::kCurrentDirectory),
2116 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2117 ui_test_utils::NavigateToURL(browser(), url);
2118 // Verify that the navigation wasn't saved in the history.
2119 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2120 EXPECT_EQ(0u, enumerator1.urls().size());
2122 // Now flip the policy and try again.
2123 policies.Set(key::kSavingBrowserHistoryDisabled,
2124 POLICY_LEVEL_MANDATORY,
2125 POLICY_SCOPE_USER,
2126 new base::FundamentalValue(false),
2127 NULL);
2128 UpdateProviderPolicy(policies);
2129 ui_test_utils::NavigateToURL(browser(), url);
2130 // Verify that the navigation was saved in the history.
2131 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2132 ASSERT_EQ(1u, enumerator2.urls().size());
2133 EXPECT_EQ(url, enumerator2.urls()[0]);
2136 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2137 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2138 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2139 if (TranslateService::IsTranslateBubbleEnabled())
2140 return;
2142 scoped_ptr<test::CldDataHarness> cld_data_scope =
2143 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2144 ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2146 // Verifies that translate can be forced enabled or disabled by policy.
2148 // Get the InfoBarService, and verify that there are no infobars on startup.
2149 content::WebContents* contents =
2150 browser()->tab_strip_model()->GetActiveWebContents();
2151 ASSERT_TRUE(contents);
2152 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2153 ASSERT_TRUE(infobar_service);
2154 EXPECT_EQ(0u, infobar_service->infobar_count());
2156 // Force enable the translate feature.
2157 PolicyMap policies;
2158 policies.Set(key::kTranslateEnabled,
2159 POLICY_LEVEL_MANDATORY,
2160 POLICY_SCOPE_USER,
2161 new base::FundamentalValue(true),
2162 NULL);
2163 UpdateProviderPolicy(policies);
2164 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2165 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2166 // TranslateManager observes. This allows checking that an infobar is NOT
2167 // shown below, without polling for infobars for some indeterminate amount
2168 // of time.
2169 GURL url = ui_test_utils::GetTestUrl(
2170 base::FilePath(),
2171 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2172 content::WindowedNotificationObserver language_observer1(
2173 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2174 content::NotificationService::AllSources());
2175 ui_test_utils::NavigateToURL(browser(), url);
2176 language_observer1.Wait();
2178 // Verify the translation detected for this tab.
2179 ChromeTranslateClient* chrome_translate_client =
2180 ChromeTranslateClient::FromWebContents(contents);
2181 ASSERT_TRUE(chrome_translate_client);
2182 translate::LanguageState& language_state =
2183 chrome_translate_client->GetLanguageState();
2184 EXPECT_EQ("fr", language_state.original_language());
2185 EXPECT_TRUE(language_state.page_needs_translation());
2186 EXPECT_FALSE(language_state.translation_pending());
2187 EXPECT_FALSE(language_state.translation_declined());
2188 EXPECT_FALSE(language_state.IsPageTranslated());
2190 // Verify that the translate infobar showed up.
2191 ASSERT_EQ(1u, infobar_service->infobar_count());
2192 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2193 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2194 infobar->delegate()->AsTranslateInfoBarDelegate();
2195 ASSERT_TRUE(translate_infobar_delegate);
2196 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2197 translate_infobar_delegate->translate_step());
2198 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2200 // Now force disable translate.
2201 infobar_service->RemoveInfoBar(infobar);
2202 EXPECT_EQ(0u, infobar_service->infobar_count());
2203 policies.Set(key::kTranslateEnabled,
2204 POLICY_LEVEL_MANDATORY,
2205 POLICY_SCOPE_USER,
2206 new base::FundamentalValue(false),
2207 NULL);
2208 UpdateProviderPolicy(policies);
2209 // Navigating to the same URL now doesn't trigger an infobar.
2210 content::WindowedNotificationObserver language_observer2(
2211 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2212 content::NotificationService::AllSources());
2213 ui_test_utils::NavigateToURL(browser(), url);
2214 language_observer2.Wait();
2215 EXPECT_EQ(0u, infobar_service->infobar_count());
2218 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2219 // Checks that URLs can be blacklisted, and that exceptions can be made to
2220 // the blacklist.
2222 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2223 // as URLRequestMockHTTPJobs.
2224 const char* kURLS[] = {
2225 "http://aaa.com/empty.html",
2226 "http://bbb.com/empty.html",
2227 "http://sub.bbb.com/empty.html",
2228 "http://bbb.com/policy/blank.html",
2231 base::RunLoop loop;
2232 BrowserThread::PostTaskAndReply(
2233 BrowserThread::IO, FROM_HERE,
2234 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2235 loop.QuitClosure());
2236 loop.Run();
2239 // Verify that "bbb.com" opens before applying the blacklist.
2240 CheckCanOpenURL(browser(), kURLS[1]);
2242 // Set a blacklist.
2243 base::ListValue blacklist;
2244 blacklist.Append(new base::StringValue("bbb.com"));
2245 PolicyMap policies;
2246 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2247 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2248 UpdateProviderPolicy(policies);
2249 FlushBlacklistPolicy();
2250 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2251 CheckCanOpenURL(browser(), kURLS[0]);
2252 for (size_t i = 1; i < arraysize(kURLS); ++i)
2253 CheckURLIsBlocked(browser(), kURLS[i]);
2255 // Whitelist some sites of bbb.com.
2256 base::ListValue whitelist;
2257 whitelist.Append(new base::StringValue("sub.bbb.com"));
2258 whitelist.Append(new base::StringValue("bbb.com/policy"));
2259 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2260 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2261 UpdateProviderPolicy(policies);
2262 FlushBlacklistPolicy();
2263 CheckURLIsBlocked(browser(), kURLS[1]);
2264 CheckCanOpenURL(browser(), kURLS[2]);
2265 CheckCanOpenURL(browser(), kURLS[3]);
2268 base::RunLoop loop;
2269 BrowserThread::PostTaskAndReply(
2270 BrowserThread::IO, FROM_HERE,
2271 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2272 loop.QuitClosure());
2273 loop.Run();
2277 #if defined(OS_MACOSX)
2278 // http://crbug.com/339240
2279 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2280 #else
2281 #define MAYBE_FileURLBlacklist FileURLBlacklist
2282 #endif
2283 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2284 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2285 // with URLblacklisting and URLwhitelisting.
2287 base::FilePath test_path;
2288 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2289 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2290 const std::string folder_path = base_path + "apptest/";
2291 const std::string file_path1 = base_path + "title1.html";
2292 const std::string file_path2 = folder_path + "basic.html";
2294 CheckCanOpenURL(browser(), file_path1.c_str());
2295 CheckCanOpenURL(browser(), file_path2.c_str());
2297 // Set a blacklist for all the files.
2298 base::ListValue blacklist;
2299 blacklist.Append(new base::StringValue("file://*"));
2300 PolicyMap policies;
2301 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2302 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2303 UpdateProviderPolicy(policies);
2304 FlushBlacklistPolicy();
2306 CheckURLIsBlocked(browser(), file_path1.c_str());
2307 CheckURLIsBlocked(browser(), file_path2.c_str());
2309 // Replace the URLblacklist with disabling the file scheme.
2310 blacklist.Remove(base::StringValue("file://*"), NULL);
2311 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2312 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2313 UpdateProviderPolicy(policies);
2314 FlushBlacklistPolicy();
2316 PrefService* prefs = browser()->profile()->GetPrefs();
2317 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2318 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2319 list_url->end());
2321 base::ListValue disabledscheme;
2322 disabledscheme.Append(new base::StringValue("file"));
2323 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2324 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2325 UpdateProviderPolicy(policies);
2326 FlushBlacklistPolicy();
2328 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2329 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2330 list_url->end());
2332 // Whitelist one folder and blacklist an another just inside.
2333 base::ListValue whitelist;
2334 whitelist.Append(new base::StringValue(base_path));
2335 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2336 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2337 blacklist.Append(new base::StringValue(folder_path));
2338 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2339 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2340 UpdateProviderPolicy(policies);
2341 FlushBlacklistPolicy();
2343 CheckCanOpenURL(browser(), file_path1.c_str());
2344 CheckURLIsBlocked(browser(), file_path2.c_str());
2347 static bool IsMinSSLVersionTLS12(Profile* profile) {
2348 scoped_refptr<net::SSLConfigService> config_service(
2349 profile->GetSSLConfigService());
2350 net::SSLConfig config;
2351 config_service->GetSSLConfig(&config);
2352 return config.version_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2355 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionMin) {
2356 PrefService* prefs = g_browser_process->local_state();
2358 const std::string new_value("tls1.2");
2359 const std::string default_value(prefs->GetString(prefs::kSSLVersionMin));
2361 EXPECT_NE(default_value, new_value);
2362 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2364 PolicyMap policies;
2365 policies.Set(key::kSSLVersionMin,
2366 POLICY_LEVEL_MANDATORY,
2367 POLICY_SCOPE_USER,
2368 new base::StringValue(new_value),
2369 NULL);
2370 UpdateProviderPolicy(policies);
2372 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2375 static bool IsMinSSLFallbackVersionTLS12(Profile* profile) {
2376 scoped_refptr<net::SSLConfigService> config_service(
2377 profile->GetSSLConfigService());
2378 net::SSLConfig config;
2379 config_service->GetSSLConfig(&config);
2380 return config.version_fallback_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2383 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2384 PrefService* prefs = g_browser_process->local_state();
2386 const std::string new_value("tls1.2");
2387 const std::string default_value(
2388 prefs->GetString(prefs::kSSLVersionFallbackMin));
2390 EXPECT_NE(default_value, new_value);
2391 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2393 PolicyMap policies;
2394 policies.Set(key::kSSLVersionFallbackMin,
2395 POLICY_LEVEL_MANDATORY,
2396 POLICY_SCOPE_USER,
2397 new base::StringValue(new_value),
2398 NULL);
2399 UpdateProviderPolicy(policies);
2401 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2404 #if !defined(OS_MACOSX)
2405 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2406 PolicyMap policies;
2407 policies.Set(key::kFullscreenAllowed,
2408 POLICY_LEVEL_MANDATORY,
2409 POLICY_SCOPE_USER,
2410 new base::FundamentalValue(false),
2411 NULL);
2412 UpdateProviderPolicy(policies);
2414 BrowserWindow* browser_window = browser()->window();
2415 ASSERT_TRUE(browser_window);
2417 EXPECT_FALSE(browser_window->IsFullscreen());
2418 chrome::ToggleFullscreenMode(browser());
2419 EXPECT_FALSE(browser_window->IsFullscreen());
2422 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2423 PolicyMap policies;
2424 policies.Set(key::kFullscreenAllowed,
2425 POLICY_LEVEL_MANDATORY,
2426 POLICY_SCOPE_USER,
2427 new base::FundamentalValue(false),
2428 NULL);
2429 UpdateProviderPolicy(policies);
2431 const extensions::Extension* extension =
2432 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2433 ASSERT_TRUE(extension);
2435 // Launch an app that tries to open a fullscreen window.
2436 TestAddAppWindowObserver add_window_observer(
2437 extensions::AppWindowRegistry::Get(browser()->profile()));
2438 OpenApplication(AppLaunchParams(browser()->profile(),
2439 extension,
2440 extensions::LAUNCH_CONTAINER_NONE,
2441 NEW_WINDOW));
2442 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2443 ASSERT_TRUE(window);
2445 // Verify that the window is not in fullscreen mode.
2446 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2448 // Verify that the window cannot be toggled into fullscreen mode via apps
2449 // APIs.
2450 EXPECT_TRUE(content::ExecuteScript(
2451 window->web_contents(),
2452 "chrome.app.window.current().fullscreen();"));
2453 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2455 // Verify that the window cannot be toggled into fullscreen mode from within
2456 // Chrome (e.g., using keyboard accelerators).
2457 window->Fullscreen();
2458 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2460 #endif
2462 #if defined(OS_CHROMEOS)
2463 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2464 int screenshot_count = CountScreenshots();
2466 // Make sure screenshots are counted correctly.
2467 TestScreenshotFile(true);
2468 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2470 // Check if trying to take a screenshot fails when disabled by policy.
2471 TestScreenshotFile(false);
2472 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2475 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2476 // Set up the mock observer.
2477 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2478 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2479 audio_handler->AddAudioObserver(test_observer.get());
2481 bool prior_state = audio_handler->IsOutputMuted();
2482 // Make sure the audio is not muted and then toggle the policy and observe
2483 // if the output mute changed event is fired.
2484 audio_handler->SetOutputMute(false);
2485 EXPECT_FALSE(audio_handler->IsOutputMuted());
2486 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2487 PolicyMap policies;
2488 policies.Set(key::kAudioOutputAllowed,
2489 POLICY_LEVEL_MANDATORY,
2490 POLICY_SCOPE_USER,
2491 new base::FundamentalValue(false),
2492 NULL);
2493 UpdateProviderPolicy(policies);
2494 EXPECT_TRUE(audio_handler->IsOutputMuted());
2495 // This should not change the state now and should not trigger output mute
2496 // changed event.
2497 audio_handler->SetOutputMute(false);
2498 EXPECT_TRUE(audio_handler->IsOutputMuted());
2499 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2501 // Toggle back and observe if the output mute changed event is fired.
2502 policies.Set(key::kAudioOutputAllowed,
2503 POLICY_LEVEL_MANDATORY,
2504 POLICY_SCOPE_USER,
2505 new base::FundamentalValue(true),
2506 NULL);
2507 UpdateProviderPolicy(policies);
2508 EXPECT_FALSE(audio_handler->IsOutputMuted());
2509 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2510 audio_handler->SetOutputMute(true);
2511 EXPECT_TRUE(audio_handler->IsOutputMuted());
2512 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2513 // Revert the prior state.
2514 audio_handler->SetOutputMute(prior_state);
2515 audio_handler->RemoveAudioObserver(test_observer.get());
2518 // Disabled, see http://crbug.com/315308.
2519 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2520 // Indicate that the session started 2 hours ago and no user activity has
2521 // occurred yet.
2522 g_browser_process->local_state()->SetInt64(
2523 prefs::kSessionStartTime,
2524 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2525 .ToInternalValue());
2528 // Disabled, see http://crbug.com/315308.
2529 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2530 content::MockNotificationObserver observer;
2531 content::NotificationRegistrar registrar;
2532 registrar.Add(&observer,
2533 chrome::NOTIFICATION_APP_TERMINATING,
2534 content::NotificationService::AllSources());
2536 // Set the session length limit to 3 hours. Verify that the session is not
2537 // terminated.
2538 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2539 .Times(0);
2540 PolicyMap policies;
2541 policies.Set(key::kSessionLengthLimit,
2542 POLICY_LEVEL_MANDATORY,
2543 POLICY_SCOPE_USER,
2544 new base::FundamentalValue(kThreeHoursInMs),
2545 NULL);
2546 UpdateProviderPolicy(policies);
2547 base::RunLoop().RunUntilIdle();
2548 Mock::VerifyAndClearExpectations(&observer);
2550 // Decrease the session length limit to 1 hour. Verify that the session is
2551 // terminated immediately.
2552 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2553 policies.Set(key::kSessionLengthLimit,
2554 POLICY_LEVEL_MANDATORY,
2555 POLICY_SCOPE_USER,
2556 new base::FundamentalValue(kOneHourInMs),
2557 NULL);
2558 UpdateProviderPolicy(policies);
2559 base::RunLoop().RunUntilIdle();
2560 Mock::VerifyAndClearExpectations(&observer);
2563 // Disabled, see http://crbug.com/315308.
2564 IN_PROC_BROWSER_TEST_F(PolicyTest,
2565 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2566 // Indicate that the session started 2 hours ago and no user activity has
2567 // occurred yet.
2568 g_browser_process->local_state()->SetInt64(
2569 prefs::kSessionStartTime,
2570 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2571 .ToInternalValue());
2574 // Disabled, see http://crbug.com/315308.
2575 IN_PROC_BROWSER_TEST_F(PolicyTest,
2576 DISABLED_WaitForInitialUserActivityUsatisfied) {
2577 content::MockNotificationObserver observer;
2578 content::NotificationRegistrar registrar;
2579 registrar.Add(&observer,
2580 chrome::NOTIFICATION_APP_TERMINATING,
2581 content::NotificationService::AllSources());
2583 // Require initial user activity.
2584 PolicyMap policies;
2585 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2586 POLICY_SCOPE_USER,
2587 new base::FundamentalValue(true),
2588 NULL);
2589 UpdateProviderPolicy(policies);
2590 base::RunLoop().RunUntilIdle();
2592 // Set the session length limit to 1 hour. Verify that the session is not
2593 // terminated.
2594 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2595 .Times(0);
2596 policies.Set(key::kSessionLengthLimit,
2597 POLICY_LEVEL_MANDATORY,
2598 POLICY_SCOPE_USER,
2599 new base::FundamentalValue(kOneHourInMs),
2600 NULL);
2601 UpdateProviderPolicy(policies);
2602 base::RunLoop().RunUntilIdle();
2603 Mock::VerifyAndClearExpectations(&observer);
2606 // Disabled, see http://crbug.com/315308.
2607 IN_PROC_BROWSER_TEST_F(PolicyTest,
2608 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2609 // Indicate that initial user activity in this session occurred 2 hours ago.
2610 g_browser_process->local_state()->SetInt64(
2611 prefs::kSessionStartTime,
2612 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2613 .ToInternalValue());
2614 g_browser_process->local_state()->SetBoolean(
2615 prefs::kSessionUserActivitySeen,
2616 true);
2619 // Disabled, see http://crbug.com/315308.
2620 IN_PROC_BROWSER_TEST_F(PolicyTest,
2621 DISABLED_WaitForInitialUserActivitySatisfied) {
2622 content::MockNotificationObserver observer;
2623 content::NotificationRegistrar registrar;
2624 registrar.Add(&observer,
2625 chrome::NOTIFICATION_APP_TERMINATING,
2626 content::NotificationService::AllSources());
2628 // Require initial user activity and set the session length limit to 3 hours.
2629 // Verify that the session is not terminated.
2630 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2631 .Times(0);
2632 PolicyMap policies;
2633 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2634 POLICY_SCOPE_USER,
2635 new base::FundamentalValue(true),
2636 NULL);
2637 policies.Set(key::kSessionLengthLimit,
2638 POLICY_LEVEL_MANDATORY,
2639 POLICY_SCOPE_USER,
2640 new base::FundamentalValue(kThreeHoursInMs),
2641 NULL);
2642 UpdateProviderPolicy(policies);
2643 base::RunLoop().RunUntilIdle();
2644 Mock::VerifyAndClearExpectations(&observer);
2646 // Decrease the session length limit to 1 hour. Verify that the session is
2647 // terminated immediately.
2648 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2649 policies.Set(key::kSessionLengthLimit,
2650 POLICY_LEVEL_MANDATORY,
2651 POLICY_SCOPE_USER,
2652 new base::FundamentalValue(kOneHourInMs),
2653 NULL);
2654 UpdateProviderPolicy(policies);
2655 base::RunLoop().RunUntilIdle();
2656 Mock::VerifyAndClearExpectations(&observer);
2659 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2660 // Verifies that the large cursor accessibility feature can be controlled
2661 // through policy.
2662 chromeos::AccessibilityManager* accessibility_manager =
2663 chromeos::AccessibilityManager::Get();
2665 // Manually enable the large cursor.
2666 accessibility_manager->EnableLargeCursor(true);
2667 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2669 // Verify that policy overrides the manual setting.
2670 PolicyMap policies;
2671 policies.Set(key::kLargeCursorEnabled,
2672 POLICY_LEVEL_MANDATORY,
2673 POLICY_SCOPE_USER,
2674 new base::FundamentalValue(false),
2675 NULL);
2676 UpdateProviderPolicy(policies);
2677 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2679 // Verify that the large cursor cannot be enabled manually anymore.
2680 accessibility_manager->EnableLargeCursor(true);
2681 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2684 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2685 // Verifies that the spoken feedback accessibility feature can be controlled
2686 // through policy.
2687 chromeos::AccessibilityManager* accessibility_manager =
2688 chromeos::AccessibilityManager::Get();
2690 // Manually enable spoken feedback.
2691 accessibility_manager->EnableSpokenFeedback(
2692 true, ui::A11Y_NOTIFICATION_NONE);
2693 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2695 // Verify that policy overrides the manual setting.
2696 PolicyMap policies;
2697 policies.Set(key::kSpokenFeedbackEnabled,
2698 POLICY_LEVEL_MANDATORY,
2699 POLICY_SCOPE_USER,
2700 new base::FundamentalValue(false),
2701 NULL);
2702 UpdateProviderPolicy(policies);
2703 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2705 // Verify that spoken feedback cannot be enabled manually anymore.
2706 accessibility_manager->EnableSpokenFeedback(
2707 true, ui::A11Y_NOTIFICATION_NONE);
2708 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2711 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2712 // Verifies that the high contrast mode accessibility feature can be
2713 // controlled through policy.
2714 chromeos::AccessibilityManager* accessibility_manager =
2715 chromeos::AccessibilityManager::Get();
2717 // Manually enable high contrast mode.
2718 accessibility_manager->EnableHighContrast(true);
2719 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2721 // Verify that policy overrides the manual setting.
2722 PolicyMap policies;
2723 policies.Set(key::kHighContrastEnabled,
2724 POLICY_LEVEL_MANDATORY,
2725 POLICY_SCOPE_USER,
2726 new base::FundamentalValue(false),
2727 NULL);
2728 UpdateProviderPolicy(policies);
2729 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2731 // Verify that high contrast mode cannot be enabled manually anymore.
2732 accessibility_manager->EnableHighContrast(true);
2733 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2736 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2737 // Verifies that the screen magnifier can be disabled through policy.
2738 chromeos::MagnificationManager* magnification_manager =
2739 chromeos::MagnificationManager::Get();
2741 // Manually enable the full-screen magnifier.
2742 magnification_manager->SetMagnifierType(ui::MAGNIFIER_FULL);
2743 magnification_manager->SetMagnifierEnabled(true);
2744 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2745 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2747 // Verify that policy overrides the manual setting.
2748 PolicyMap policies;
2749 policies.Set(key::kScreenMagnifierType,
2750 POLICY_LEVEL_MANDATORY,
2751 POLICY_SCOPE_USER,
2752 new base::FundamentalValue(0),
2753 NULL);
2754 UpdateProviderPolicy(policies);
2755 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2757 // Verify that the screen magnifier cannot be enabled manually anymore.
2758 magnification_manager->SetMagnifierEnabled(true);
2759 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2762 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2763 // Verifies that the full-screen magnifier can be enabled through policy.
2764 chromeos::MagnificationManager* magnification_manager =
2765 chromeos::MagnificationManager::Get();
2767 // Verify that the screen magnifier is initially disabled.
2768 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2770 // Verify that policy can enable the full-screen magnifier.
2771 PolicyMap policies;
2772 policies.Set(key::kScreenMagnifierType,
2773 POLICY_LEVEL_MANDATORY,
2774 POLICY_SCOPE_USER,
2775 new base::FundamentalValue(ui::MAGNIFIER_FULL),
2776 NULL);
2777 UpdateProviderPolicy(policies);
2778 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2779 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2781 // Verify that the screen magnifier cannot be disabled manually anymore.
2782 magnification_manager->SetMagnifierEnabled(false);
2783 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2786 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
2787 // Verifies that the on-screen keyboard accessibility feature can be
2788 // controlled through policy.
2789 chromeos::AccessibilityManager* accessibility_manager =
2790 chromeos::AccessibilityManager::Get();
2792 // Manually enable the on-screen keyboard.
2793 accessibility_manager->EnableVirtualKeyboard(true);
2794 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2796 // Verify that policy overrides the manual setting.
2797 PolicyMap policies;
2798 policies.Set(key::kVirtualKeyboardEnabled,
2799 POLICY_LEVEL_MANDATORY,
2800 POLICY_SCOPE_USER,
2801 new base::FundamentalValue(false),
2802 NULL);
2803 UpdateProviderPolicy(policies);
2804 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2806 // Verify that the on-screen keyboard cannot be enabled manually anymore.
2807 accessibility_manager->EnableVirtualKeyboard(true);
2808 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2811 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2812 // Verify keyboard disabled by default.
2813 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2814 // Verify keyboard can be toggled by default.
2815 keyboard::SetTouchKeyboardEnabled(true);
2816 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2817 keyboard::SetTouchKeyboardEnabled(false);
2818 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2820 // Verify enabling the policy takes effect immediately and that that user
2821 // cannot disable the keyboard..
2822 PolicyMap policies;
2823 policies.Set(key::kTouchVirtualKeyboardEnabled,
2824 POLICY_LEVEL_MANDATORY,
2825 POLICY_SCOPE_USER,
2826 new base::FundamentalValue(true),
2827 NULL);
2828 UpdateProviderPolicy(policies);
2829 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2830 keyboard::SetTouchKeyboardEnabled(false);
2831 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2833 // Verify that disabling the policy takes effect immediately and that the user
2834 // cannot enable the keyboard.
2835 policies.Set(key::kTouchVirtualKeyboardEnabled,
2836 POLICY_LEVEL_MANDATORY,
2837 POLICY_SCOPE_USER,
2838 new base::FundamentalValue(false),
2839 NULL);
2840 UpdateProviderPolicy(policies);
2841 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2842 keyboard::SetTouchKeyboardEnabled(true);
2843 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2846 #endif
2848 namespace {
2850 static const char* kRestoredURLs[] = {
2851 "http://aaa.com/empty.html",
2852 "http://bbb.com/empty.html",
2855 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2856 return s.empty() || s[0] != '-';
2859 } // namespace
2861 // Similar to PolicyTest but allows setting policies before the browser is
2862 // created. Each test parameter is a method that sets up the early policies
2863 // and stores the expected startup URLs in |expected_urls_|.
2864 class RestoreOnStartupPolicyTest
2865 : public PolicyTest,
2866 public testing::WithParamInterface<
2867 void (RestoreOnStartupPolicyTest::*)(void)> {
2868 public:
2869 RestoreOnStartupPolicyTest() {}
2870 virtual ~RestoreOnStartupPolicyTest() {}
2872 #if defined(OS_CHROMEOS)
2873 virtual void SetUpCommandLine(CommandLine* command_line) override {
2874 // TODO(nkostylev): Investigate if we can remove this switch.
2875 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2876 PolicyTest::SetUpCommandLine(command_line);
2878 #endif
2880 void SetUpInProcessBrowserTestFixture() override {
2881 PolicyTest::SetUpInProcessBrowserTestFixture();
2882 // Set early policies now, before the browser is created.
2883 (this->*(GetParam()))();
2885 // Remove the non-switch arguments, so that session restore kicks in for
2886 // these tests.
2887 CommandLine* command_line = CommandLine::ForCurrentProcess();
2888 CommandLine::StringVector argv = command_line->argv();
2889 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2890 argv.end());
2891 command_line->InitFromArgv(argv);
2892 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2893 command_line->argv().begin()));
2896 void SetUpOnMainThread() override {
2897 BrowserThread::PostTask(
2898 BrowserThread::IO,
2899 FROM_HERE,
2900 base::Bind(
2901 RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
2904 void HomepageIsNotNTP() {
2905 // Verifies that policy can set the startup pages to the homepage, when
2906 // the homepage is not the NTP.
2907 PolicyMap policies;
2908 policies.Set(
2909 key::kRestoreOnStartup,
2910 POLICY_LEVEL_MANDATORY,
2911 POLICY_SCOPE_USER,
2912 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2913 NULL);
2914 policies.Set(key::kHomepageIsNewTabPage,
2915 POLICY_LEVEL_MANDATORY,
2916 POLICY_SCOPE_USER,
2917 new base::FundamentalValue(false),
2918 NULL);
2919 policies.Set(key::kHomepageLocation,
2920 POLICY_LEVEL_MANDATORY,
2921 POLICY_SCOPE_USER,
2922 new base::StringValue(kRestoredURLs[1]),
2923 NULL);
2924 provider_.UpdateChromePolicy(policies);
2926 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2929 void HomepageIsNTP() {
2930 // Verifies that policy can set the startup pages to the homepage, when
2931 // the homepage is the NTP.
2932 PolicyMap policies;
2933 policies.Set(
2934 key::kRestoreOnStartup,
2935 POLICY_LEVEL_MANDATORY,
2936 POLICY_SCOPE_USER,
2937 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2938 NULL);
2939 policies.Set(key::kHomepageIsNewTabPage,
2940 POLICY_LEVEL_MANDATORY,
2941 POLICY_SCOPE_USER,
2942 new base::FundamentalValue(true),
2943 NULL);
2944 provider_.UpdateChromePolicy(policies);
2946 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2949 void ListOfURLs() {
2950 // Verifies that policy can set the startup pages to a list of URLs.
2951 base::ListValue urls;
2952 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2953 urls.Append(new base::StringValue(kRestoredURLs[i]));
2954 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2956 PolicyMap policies;
2957 policies.Set(key::kRestoreOnStartup,
2958 POLICY_LEVEL_MANDATORY,
2959 POLICY_SCOPE_USER,
2960 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
2961 NULL);
2962 policies.Set(
2963 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2964 urls.DeepCopy(), NULL);
2965 provider_.UpdateChromePolicy(policies);
2968 void NTP() {
2969 // Verifies that policy can set the startup page to the NTP.
2970 PolicyMap policies;
2971 policies.Set(
2972 key::kRestoreOnStartup,
2973 POLICY_LEVEL_MANDATORY,
2974 POLICY_SCOPE_USER,
2975 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
2976 NULL);
2977 provider_.UpdateChromePolicy(policies);
2978 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2981 void Last() {
2982 // Verifies that policy can set the startup pages to the last session.
2983 PolicyMap policies;
2984 policies.Set(key::kRestoreOnStartup,
2985 POLICY_LEVEL_MANDATORY,
2986 POLICY_SCOPE_USER,
2987 new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
2988 NULL);
2989 provider_.UpdateChromePolicy(policies);
2990 // This should restore the tabs opened at PRE_RunTest below.
2991 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2992 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2995 std::vector<GURL> expected_urls_;
2998 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2999 // Open some tabs to verify if they are restored after the browser restarts.
3000 // Most policy settings override this, except kPrefValueLast which enforces
3001 // a restore.
3002 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
3003 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
3004 content::WindowedNotificationObserver observer(
3005 content::NOTIFICATION_LOAD_STOP,
3006 content::NotificationService::AllSources());
3007 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
3008 ui::PAGE_TRANSITION_LINK);
3009 observer.Wait();
3013 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
3014 #if defined(OS_WIN) && defined(USE_ASH)
3015 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3016 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
3017 return;
3018 #endif
3020 TabStripModel* model = browser()->tab_strip_model();
3021 int size = static_cast<int>(expected_urls_.size());
3022 EXPECT_EQ(size, model->count());
3023 for (int i = 0; i < size && i < model->count(); ++i) {
3024 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
3028 INSTANTIATE_TEST_CASE_P(
3029 RestoreOnStartupPolicyTestInstance,
3030 RestoreOnStartupPolicyTest,
3031 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
3032 &RestoreOnStartupPolicyTest::HomepageIsNTP,
3033 &RestoreOnStartupPolicyTest::ListOfURLs,
3034 &RestoreOnStartupPolicyTest::NTP,
3035 &RestoreOnStartupPolicyTest::Last));
3037 // Similar to PolicyTest but sets a couple of policies before the browser is
3038 // started.
3039 class PolicyStatisticsCollectorTest : public PolicyTest {
3040 public:
3041 PolicyStatisticsCollectorTest() {}
3042 ~PolicyStatisticsCollectorTest() override {}
3044 void SetUpInProcessBrowserTestFixture() override {
3045 PolicyTest::SetUpInProcessBrowserTestFixture();
3046 PolicyMap policies;
3047 policies.Set(key::kShowHomeButton,
3048 POLICY_LEVEL_MANDATORY,
3049 POLICY_SCOPE_USER,
3050 new base::FundamentalValue(true),
3051 NULL);
3052 policies.Set(key::kBookmarkBarEnabled,
3053 POLICY_LEVEL_MANDATORY,
3054 POLICY_SCOPE_USER,
3055 new base::FundamentalValue(false),
3056 NULL);
3057 policies.Set(key::kHomepageLocation,
3058 POLICY_LEVEL_MANDATORY,
3059 POLICY_SCOPE_USER,
3060 new base::StringValue("http://chromium.org"),
3061 NULL);
3062 provider_.UpdateChromePolicy(policies);
3066 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
3067 // Verifies that policy usage histograms are collected at startup.
3069 // BrowserPolicyConnector::Init() has already been called. Make sure the
3070 // CompleteInitialization() task has executed as well.
3071 content::RunAllPendingInMessageLoop();
3073 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
3074 std::string(url::kStandardSchemeSeparator) +
3075 std::string(content::kChromeUIHistogramHost));
3076 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3077 content::WebContents* contents =
3078 browser()->tab_strip_model()->GetActiveWebContents();
3079 std::string text;
3080 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3081 contents,
3082 "var nodes = document.querySelectorAll('body > pre');"
3083 "var result = '';"
3084 "for (var i = 0; i < nodes.length; ++i) {"
3085 " var text = nodes[i].innerHTML;"
3086 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3087 " result = text;"
3088 " break;"
3089 " }"
3091 "domAutomationController.send(result);",
3092 &text));
3093 ASSERT_FALSE(text.empty());
3094 const std::string kExpectedLabel =
3095 "Histogram: Enterprise.Policies recorded 3 samples";
3096 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3097 // HomepageLocation has policy ID 1.
3098 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
3099 // ShowHomeButton has policy ID 35.
3100 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
3101 // BookmarkBarEnabled has policy ID 82.
3102 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
3105 class MediaStreamDevicesControllerBrowserTest
3106 : public PolicyTest,
3107 public testing::WithParamInterface<bool> {
3108 public:
3109 MediaStreamDevicesControllerBrowserTest()
3110 : request_url_allowed_via_whitelist_(false) {
3111 policy_value_ = GetParam();
3113 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3115 // Configure a given policy map.
3116 // The |policy_name| is the name of either the audio or video capture allow
3117 // policy and must never be NULL.
3118 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3119 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3120 // and the whitelist policy is set to contain either the |allow_rule| (if
3121 // non-NULL) or an "allow all" wildcard.
3122 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3123 const char* whitelist_policy,
3124 const char* allow_rule) {
3125 policies->Set(policy_name,
3126 POLICY_LEVEL_MANDATORY,
3127 POLICY_SCOPE_USER,
3128 new base::FundamentalValue(policy_value_),
3129 NULL);
3131 if (whitelist_policy) {
3132 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3133 // in the media exceptions UI.
3134 // See discussion here: https://codereview.chromium.org/15738004/
3135 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
3137 // Add an entry to the whitelist that allows the specified URL regardless
3138 // of the setting of kAudioCapturedAllowed.
3139 request_url_ = GURL("http://www.example.com/foo");
3140 base::ListValue* list = new base::ListValue();
3141 if (allow_rule) {
3142 list->AppendString(allow_rule);
3143 request_url_allowed_via_whitelist_ = true;
3144 } else {
3145 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3146 // We should ignore all wildcard entries in the whitelist, so even
3147 // though we've added an entry, it should be ignored and our expectation
3148 // is that the request has not been allowed via the whitelist.
3149 request_url_allowed_via_whitelist_ = false;
3151 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3152 POLICY_SCOPE_USER, list, NULL);
3156 void Accept(const content::MediaStreamDevices& devices,
3157 content::MediaStreamRequestResult result,
3158 scoped_ptr<content::MediaStreamUI> ui) {
3159 if (policy_value_ || request_url_allowed_via_whitelist_) {
3160 ASSERT_EQ(1U, devices.size());
3161 ASSERT_EQ("fake_dev", devices[0].id);
3162 } else {
3163 ASSERT_EQ(0U, devices.size());
3167 void FinishAudioTest() {
3168 content::MediaStreamRequest request(0, 0, 0,
3169 request_url_.GetOrigin(), false,
3170 content::MEDIA_DEVICE_ACCESS,
3171 std::string(), std::string(),
3172 content::MEDIA_DEVICE_AUDIO_CAPTURE,
3173 content::MEDIA_NO_SERVICE);
3174 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3175 // and microphone permissions at the same time.
3176 MediaStreamDevicesController controller(
3177 browser()->tab_strip_model()->GetActiveWebContents(), request,
3178 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3179 controller.Accept(false);
3181 base::MessageLoop::current()->QuitWhenIdle();
3184 void FinishVideoTest() {
3185 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3186 // and microphone permissions at the same time.
3187 content::MediaStreamRequest request(0, 0, 0,
3188 request_url_.GetOrigin(), false,
3189 content::MEDIA_DEVICE_ACCESS,
3190 std::string(),
3191 std::string(),
3192 content::MEDIA_NO_SERVICE,
3193 content::MEDIA_DEVICE_VIDEO_CAPTURE);
3194 MediaStreamDevicesController controller(
3195 browser()->tab_strip_model()->GetActiveWebContents(), request,
3196 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3197 controller.Accept(false);
3199 base::MessageLoop::current()->QuitWhenIdle();
3202 bool policy_value_;
3203 bool request_url_allowed_via_whitelist_;
3204 GURL request_url_;
3205 static const char kExampleRequestPattern[];
3208 // static
3209 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3210 "http://[*.]example.com/";
3212 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3213 AudioCaptureAllowed) {
3214 content::MediaStreamDevices audio_devices;
3215 content::MediaStreamDevice fake_audio_device(
3216 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3217 audio_devices.push_back(fake_audio_device);
3219 PolicyMap policies;
3220 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3221 UpdateProviderPolicy(policies);
3223 content::BrowserThread::PostTaskAndReply(
3224 content::BrowserThread::IO, FROM_HERE,
3225 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3226 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3227 audio_devices),
3228 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3229 this));
3231 base::MessageLoop::current()->Run();
3234 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3235 AudioCaptureAllowedUrls) {
3236 content::MediaStreamDevices audio_devices;
3237 content::MediaStreamDevice fake_audio_device(
3238 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3239 audio_devices.push_back(fake_audio_device);
3241 const char* allow_pattern[] = {
3242 kExampleRequestPattern,
3243 // This will set an allow-all policy whitelist. Since we do not allow
3244 // setting an allow-all entry in the whitelist, this entry should be ignored
3245 // and therefore the request should be denied.
3246 NULL,
3249 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3250 PolicyMap policies;
3251 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3252 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3253 UpdateProviderPolicy(policies);
3255 content::BrowserThread::PostTaskAndReply(
3256 content::BrowserThread::IO, FROM_HERE,
3257 base::Bind(
3258 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3259 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3260 audio_devices),
3261 base::Bind(
3262 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3263 this));
3265 base::MessageLoop::current()->Run();
3269 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3270 VideoCaptureAllowed) {
3271 content::MediaStreamDevices video_devices;
3272 content::MediaStreamDevice fake_video_device(
3273 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3274 video_devices.push_back(fake_video_device);
3276 PolicyMap policies;
3277 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3278 UpdateProviderPolicy(policies);
3280 content::BrowserThread::PostTaskAndReply(
3281 content::BrowserThread::IO, FROM_HERE,
3282 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3283 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3284 video_devices),
3285 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3286 this));
3288 base::MessageLoop::current()->Run();
3291 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3292 VideoCaptureAllowedUrls) {
3293 content::MediaStreamDevices video_devices;
3294 content::MediaStreamDevice fake_video_device(
3295 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3296 video_devices.push_back(fake_video_device);
3298 const char* allow_pattern[] = {
3299 kExampleRequestPattern,
3300 // This will set an allow-all policy whitelist. Since we do not allow
3301 // setting an allow-all entry in the whitelist, this entry should be ignored
3302 // and therefore the request should be denied.
3303 NULL,
3306 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3307 PolicyMap policies;
3308 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3309 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3310 UpdateProviderPolicy(policies);
3312 content::BrowserThread::PostTaskAndReply(
3313 content::BrowserThread::IO, FROM_HERE,
3314 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3315 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3316 video_devices),
3317 base::Bind(
3318 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3319 this));
3321 base::MessageLoop::current()->Run();
3325 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3326 MediaStreamDevicesControllerBrowserTest,
3327 testing::Bool());
3329 #if !defined(OS_CHROMEOS)
3330 // Similar to PolicyTest but sets the proper policy before the browser is
3331 // started.
3332 class PolicyVariationsServiceTest : public PolicyTest {
3333 public:
3334 void SetUpInProcessBrowserTestFixture() override {
3335 PolicyTest::SetUpInProcessBrowserTestFixture();
3336 PolicyMap policies;
3337 policies.Set(key::kVariationsRestrictParameter,
3338 POLICY_LEVEL_MANDATORY,
3339 POLICY_SCOPE_USER,
3340 new base::StringValue("restricted"),
3341 NULL);
3342 provider_.UpdateChromePolicy(policies);
3346 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3347 const std::string default_variations_url =
3348 chrome_variations::VariationsService::
3349 GetDefaultVariationsServerURLForTesting();
3351 const GURL url =
3352 chrome_variations::VariationsService::GetVariationsServerURL(
3353 g_browser_process->local_state());
3354 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
3355 std::string value;
3356 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3357 EXPECT_EQ("restricted", value);
3360 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3361 base::ListValue blacklist;
3362 blacklist.Append(new base::StringValue("host.name"));
3363 PolicyMap policies;
3364 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3365 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3366 UpdateProviderPolicy(policies);
3368 PrefService* prefs = browser()->profile()->GetPrefs();
3369 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3370 prefs, "host.name"));
3371 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3372 prefs, "other.host.name"));
3375 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3376 base::ListValue blacklist;
3377 blacklist.Append(new base::StringValue("*"));
3378 PolicyMap policies;
3379 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3380 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3381 UpdateProviderPolicy(policies);
3383 PrefService* prefs = browser()->profile()->GetPrefs();
3384 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3385 prefs, "host.name"));
3386 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3387 prefs, "other.host.name"));
3390 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3391 base::ListValue blacklist;
3392 blacklist.Append(new base::StringValue("*"));
3393 base::ListValue whitelist;
3394 whitelist.Append(new base::StringValue("host.name"));
3395 PolicyMap policies;
3396 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3397 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3398 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3399 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3400 UpdateProviderPolicy(policies);
3402 PrefService* prefs = browser()->profile()->GetPrefs();
3403 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3404 prefs, "host.name"));
3405 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3406 prefs, "other.host.name"));
3409 IN_PROC_BROWSER_TEST_F(PolicyTest,
3410 EnableDeprecatedWebPlatformFeatures_ShowModalDialog) {
3411 base::ListValue enabled_features;
3412 enabled_features.Append(new base::StringValue(
3413 "ShowModalDialog_EffectiveUntil20150430"));
3414 PolicyMap policies;
3415 policies.Set(key::kEnableDeprecatedWebPlatformFeatures,
3416 POLICY_LEVEL_MANDATORY,
3417 POLICY_SCOPE_USER,
3418 enabled_features.DeepCopy(),
3419 NULL);
3420 UpdateProviderPolicy(policies);
3422 // Policy only takes effect on new browsers, not existing browsers, so create
3423 // a new browser.
3424 Browser* browser2 = CreateBrowser(browser()->profile());
3425 ui_test_utils::NavigateToURL(browser2, GURL(url::kAboutBlankURL));
3426 bool result = false;
3427 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3428 browser2->tab_strip_model()->GetActiveWebContents(),
3429 "domAutomationController.send(window.showModalDialog !== undefined);",
3430 &result));
3431 EXPECT_TRUE(result);
3434 #endif // !defined(CHROME_OS)
3436 } // namespace policy