Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blob0d01580ca9d8e883f51d871c697e477c27af578c
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/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/test/test_file_util.h"
26 #include "base/time/time.h"
27 #include "base/values.h"
28 #include "chrome/app/chrome_command_ids.h"
29 #include "chrome/browser/autocomplete/autocomplete_controller.h"
30 #include "chrome/browser/background/background_contents_service.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
34 #include "chrome/browser/devtools/devtools_window.h"
35 #include "chrome/browser/download/download_prefs.h"
36 #include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
37 #include "chrome/browser/extensions/crx_installer.h"
38 #include "chrome/browser/extensions/extension_host.h"
39 #include "chrome/browser/extensions/extension_service.h"
40 #include "chrome/browser/extensions/extension_system.h"
41 #include "chrome/browser/extensions/unpacked_installer.h"
42 #include "chrome/browser/extensions/updater/extension_updater.h"
43 #include "chrome/browser/infobars/infobar.h"
44 #include "chrome/browser/infobars/infobar_service.h"
45 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
46 #include "chrome/browser/media/media_stream_devices_controller.h"
47 #include "chrome/browser/metrics/variations/variations_service.h"
48 #include "chrome/browser/net/url_request_mock_util.h"
49 #include "chrome/browser/plugins/plugin_prefs.h"
50 #include "chrome/browser/policy/browser_policy_connector.h"
51 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
52 #include "chrome/browser/policy/profile_policy_connector.h"
53 #include "chrome/browser/policy/profile_policy_connector_factory.h"
54 #include "chrome/browser/prefs/session_startup_pref.h"
55 #include "chrome/browser/profiles/profile.h"
56 #include "chrome/browser/search/instant_service.h"
57 #include "chrome/browser/search/instant_service_factory.h"
58 #include "chrome/browser/search/search.h"
59 #include "chrome/browser/search_engines/template_url.h"
60 #include "chrome/browser/search_engines/template_url_service.h"
61 #include "chrome/browser/search_engines/template_url_service_factory.h"
62 #include "chrome/browser/translate/translate_infobar_delegate.h"
63 #include "chrome/browser/translate/translate_tab_helper.h"
64 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
65 #include "chrome/browser/ui/browser.h"
66 #include "chrome/browser/ui/browser_commands.h"
67 #include "chrome/browser/ui/browser_list.h"
68 #include "chrome/browser/ui/browser_tabstrip.h"
69 #include "chrome/browser/ui/browser_window.h"
70 #include "chrome/browser/ui/host_desktop.h"
71 #include "chrome/browser/ui/omnibox/location_bar.h"
72 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
73 #include "chrome/browser/ui/omnibox/omnibox_view.h"
74 #include "chrome/browser/ui/tabs/tab_strip_model.h"
75 #include "chrome/common/chrome_paths.h"
76 #include "chrome/common/chrome_switches.h"
77 #include "chrome/common/content_settings.h"
78 #include "chrome/common/content_settings_pattern.h"
79 #include "chrome/common/extensions/extension_constants.h"
80 #include "chrome/common/pref_names.h"
81 #include "chrome/common/url_constants.h"
82 #include "chrome/test/base/in_process_browser_test.h"
83 #include "chrome/test/base/test_switches.h"
84 #include "chrome/test/base/ui_test_utils.h"
85 #include "components/policy/core/common/external_data_fetcher.h"
86 #include "components/policy/core/common/mock_configuration_policy_provider.h"
87 #include "components/policy/core/common/policy_map.h"
88 #include "components/policy/core/common/policy_pref_names.h"
89 #include "components/policy/core/common/policy_service.h"
90 #include "components/policy/core/common/policy_service_impl.h"
91 #include "content/public/browser/browser_child_process_host_iterator.h"
92 #include "content/public/browser/browser_context.h"
93 #include "content/public/browser/browser_thread.h"
94 #include "content/public/browser/child_process_data.h"
95 #include "content/public/browser/download_item.h"
96 #include "content/public/browser/download_manager.h"
97 #include "content/public/browser/gpu_data_manager.h"
98 #include "content/public/browser/notification_details.h"
99 #include "content/public/browser/notification_observer.h"
100 #include "content/public/browser/notification_registrar.h"
101 #include "content/public/browser/notification_service.h"
102 #include "content/public/browser/notification_source.h"
103 #include "content/public/browser/notification_types.h"
104 #include "content/public/browser/plugin_service.h"
105 #include "content/public/browser/render_process_host.h"
106 #include "content/public/browser/render_view_host.h"
107 #include "content/public/browser/web_contents.h"
108 #include "content/public/common/content_constants.h"
109 #include "content/public/common/content_paths.h"
110 #include "content/public/common/page_transition_types.h"
111 #include "content/public/common/process_type.h"
112 #include "content/public/common/result_codes.h"
113 #include "content/public/common/url_constants.h"
114 #include "content/public/common/webplugininfo.h"
115 #include "content/public/test/browser_test_utils.h"
116 #include "content/public/test/download_test_observer.h"
117 #include "content/public/test/mock_notification_observer.h"
118 #include "content/public/test/test_navigation_observer.h"
119 #include "content/public/test/test_utils.h"
120 #include "content/test/net/url_request_failed_job.h"
121 #include "content/test/net/url_request_mock_http_job.h"
122 #include "extensions/browser/process_manager.h"
123 #include "extensions/common/constants.h"
124 #include "extensions/common/extension.h"
125 #include "extensions/common/extension_set.h"
126 #include "grit/generated_resources.h"
127 #include "net/base/net_errors.h"
128 #include "net/base/net_util.h"
129 #include "net/base/url_util.h"
130 #include "net/http/http_stream_factory.h"
131 #include "net/url_request/url_request.h"
132 #include "net/url_request/url_request_filter.h"
133 #include "policy/policy_constants.h"
134 #include "testing/gmock/include/gmock/gmock.h"
135 #include "testing/gtest/include/gtest/gtest.h"
136 #include "third_party/WebKit/public/web/WebInputEvent.h"
137 #include "ui/base/l10n/l10n_util.h"
138 #include "ui/base/resource/resource_bundle.h"
139 #include "url/gurl.h"
141 #if defined(OS_CHROMEOS)
142 #include "ash/accelerators/accelerator_controller.h"
143 #include "ash/accelerators/accelerator_table.h"
144 #include "ash/magnifier/magnifier_constants.h"
145 #include "ash/shell.h"
146 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
147 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
148 #include "chrome/browser/profiles/profile_manager.h"
149 #include "chrome/browser/ui/ash/screenshot_taker.h"
150 #include "chromeos/audio/cras_audio_handler.h"
151 #endif
153 #if !defined(OS_MACOSX)
154 #include "apps/shell_window.h"
155 #include "apps/shell_window_registry.h"
156 #include "apps/ui/native_app_window.h"
157 #include "base/basictypes.h"
158 #include "base/compiler_specific.h"
159 #include "chrome/browser/ui/extensions/application_launch.h"
160 #include "ui/base/window_open_disposition.h"
161 #endif
163 using content::BrowserThread;
164 using content::URLRequestMockHTTPJob;
165 using testing::Mock;
166 using testing::Return;
167 using testing::_;
169 namespace policy {
171 namespace {
173 #if defined(OS_CHROMEOS)
174 const int kOneHourInMs = 60 * 60 * 1000;
175 const int kThreeHoursInMs = 180 * 60 * 1000;
176 #endif
178 const char kURL[] = "http://example.com";
179 const char kCookieValue[] = "converted=true";
180 // Assigned to Philip J. Fry to fix eventually.
181 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
183 const base::FilePath::CharType kTestExtensionsDir[] =
184 FILE_PATH_LITERAL("extensions");
185 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
186 const base::FilePath::CharType kAdBlockCrxName[] =
187 FILE_PATH_LITERAL("adblock.crx");
188 const base::FilePath::CharType kHostedAppCrxName[] =
189 FILE_PATH_LITERAL("hosted_app.crx");
191 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
192 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
193 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
195 const base::FilePath::CharType kGood2CrxManifestName[] =
196 FILE_PATH_LITERAL("good2_update_manifest.xml");
197 const base::FilePath::CharType kGoodV1CrxManifestName[] =
198 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
199 const base::FilePath::CharType kGoodUnpackedExt[] =
200 FILE_PATH_LITERAL("good_unpacked");
201 const base::FilePath::CharType kAppUnpackedExt[] =
202 FILE_PATH_LITERAL("app");
204 #if !defined(OS_MACOSX)
205 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
206 FILE_PATH_LITERAL("fullscreen_app");
207 #endif // !defined(OS_MACOSX)
209 // Filters requests to the hosts in |urls| and redirects them to the test data
210 // dir through URLRequestMockHTTPJobs.
211 void RedirectHostsToTestData(const char* const urls[], size_t size) {
212 // Map the given hosts to the test data dir.
213 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
214 base::FilePath base_path;
215 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
216 for (size_t i = 0; i < size; ++i) {
217 const GURL url(urls[i]);
218 EXPECT_TRUE(url.is_valid());
219 filter->AddUrlProtocolHandler(url,
220 URLRequestMockHTTPJob::CreateProtocolHandler(base_path));
224 // Remove filters for requests to the hosts in |urls|.
225 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
226 // Map the given hosts to the test data dir.
227 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
228 for (size_t i = 0; i < size; ++i) {
229 const GURL url(urls[i]);
230 EXPECT_TRUE(url.is_valid());
231 filter->RemoveUrlHandler(url);
235 // Fails requests using ERR_CONNECTION_RESET.
236 net::URLRequestJob* FailedJobFactory(
237 net::URLRequest* request,
238 net::NetworkDelegate* network_delegate,
239 const std::string& scheme) {
240 return new content::URLRequestFailedJob(
241 request, network_delegate, net::ERR_CONNECTION_RESET);
244 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
245 class MakeRequestFail {
246 public:
247 // Sets up the filter on IO thread such that requests to |host| fail.
248 explicit MakeRequestFail(const std::string& host) : host_(host) {
249 BrowserThread::PostTaskAndReply(
250 BrowserThread::IO, FROM_HERE,
251 base::Bind(MakeRequestFailOnIO, host_),
252 base::MessageLoop::QuitClosure());
253 content::RunMessageLoop();
255 ~MakeRequestFail() {
256 BrowserThread::PostTaskAndReply(
257 BrowserThread::IO, FROM_HERE,
258 base::Bind(UndoMakeRequestFailOnIO, host_),
259 base::MessageLoop::QuitClosure());
260 content::RunMessageLoop();
263 private:
264 // Filters requests to the |host| such that they fail. Run on IO thread.
265 static void MakeRequestFailOnIO(const std::string& host) {
266 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
267 filter->AddHostnameHandler("http", host, &FailedJobFactory);
268 filter->AddHostnameHandler("https", host, &FailedJobFactory);
271 // Remove filters for requests to the |host|. Run on IO thread.
272 static void UndoMakeRequestFailOnIO(const std::string& host) {
273 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
274 filter->RemoveHostnameHandler("http", host);
275 filter->RemoveHostnameHandler("https", host);
278 const std::string host_;
281 // Verifies that the given url |spec| can be opened. This assumes that |spec|
282 // points at empty.html in the test data dir.
283 void CheckCanOpenURL(Browser* browser, const char* spec) {
284 GURL url(spec);
285 ui_test_utils::NavigateToURL(browser, url);
286 content::WebContents* contents =
287 browser->tab_strip_model()->GetActiveWebContents();
288 EXPECT_EQ(url, contents->GetURL());
289 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
290 EXPECT_NE(title, contents->GetTitle());
293 // Verifies that access to the given url |spec| is blocked.
294 void CheckURLIsBlocked(Browser* browser, const char* spec) {
295 GURL url(spec);
296 ui_test_utils::NavigateToURL(browser, url);
297 content::WebContents* contents =
298 browser->tab_strip_model()->GetActiveWebContents();
299 EXPECT_EQ(url, contents->GetURL());
300 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
301 EXPECT_EQ(title, contents->GetTitle());
303 // Verify that the expected error page is being displayed.
304 bool result = false;
305 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
306 contents,
307 "var textContent = document.body.textContent;"
308 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
309 "domAutomationController.send(hasError);",
310 &result));
311 EXPECT_TRUE(result);
314 #if !defined(OS_CHROMEOS)
315 // Downloads a file named |file| and expects it to be saved to |dir|, which
316 // must be empty.
317 void DownloadAndVerifyFile(
318 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
319 content::DownloadManager* download_manager =
320 content::BrowserContext::GetDownloadManager(browser->profile());
321 content::DownloadTestObserverTerminal observer(
322 download_manager, 1,
323 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
324 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
325 base::FilePath downloaded = dir.Append(file);
326 EXPECT_FALSE(base::PathExists(downloaded));
327 ui_test_utils::NavigateToURLWithDisposition(
328 browser, url, CURRENT_TAB,
329 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
330 observer.WaitForFinished();
331 EXPECT_EQ(
332 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
333 EXPECT_TRUE(base::PathExists(downloaded));
334 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
335 EXPECT_EQ(file, enumerator.Next().BaseName());
336 EXPECT_EQ(base::FilePath(), enumerator.Next());
339 #else
341 int CountScreenshots() {
342 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
343 ProfileManager::GetActiveUserProfile());
344 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
345 false, base::FileEnumerator::FILES,
346 "Screenshot*");
347 int count = 0;
348 while (!enumerator.Next().empty())
349 count++;
350 return count;
352 #endif
354 // Checks if WebGL is enabled in the given WebContents.
355 bool IsWebGLEnabled(content::WebContents* contents) {
356 bool result = false;
357 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
358 contents,
359 "var canvas = document.createElement('canvas');"
360 "var context = canvas.getContext('webgl');"
361 "domAutomationController.send(context != null);",
362 &result));
363 return result;
366 bool IsJavascriptEnabled(content::WebContents* contents) {
367 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
368 contents->GetRenderViewHost(), "123");
369 int result = 0;
370 if (!value->GetAsInteger(&result))
371 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
372 return result == 123;
375 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
376 const std::vector<content::WebPluginInfo>& in) {
377 *out = in;
378 base::MessageLoop::current()->QuitWhenIdle();
381 template<typename T>
382 void CopyValueAndQuit(T* out, T in) {
383 *out = in;
384 base::MessageLoop::current()->QuitWhenIdle();
387 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
388 content::PluginService* service = content::PluginService::GetInstance();
389 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
390 content::RunMessageLoop();
393 const content::WebPluginInfo* GetFlashPlugin(
394 const std::vector<content::WebPluginInfo>& plugins) {
395 const content::WebPluginInfo* flash = NULL;
396 for (size_t i = 0; i < plugins.size(); ++i) {
397 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
398 flash = &plugins[i];
399 break;
402 #if defined(OFFICIAL_BUILD)
403 // Official builds bundle Flash.
404 EXPECT_TRUE(flash);
405 #else
406 if (!flash)
407 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
408 #endif
409 return flash;
412 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
413 const content::WebPluginInfo* plugin,
414 bool enabled) {
415 bool ok = false;
416 plugin_prefs->EnablePlugin(enabled, plugin->path,
417 base::Bind(CopyValueAndQuit<bool>, &ok));
418 content::RunMessageLoop();
419 return ok;
422 int CountPluginsOnIOThread() {
423 int count = 0;
424 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
425 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
426 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
427 count++;
430 return count;
433 int CountPlugins() {
434 int count = -1;
435 BrowserThread::PostTaskAndReplyWithResult(
436 BrowserThread::IO, FROM_HERE,
437 base::Bind(CountPluginsOnIOThread),
438 base::Bind(CopyValueAndQuit<int>, &count));
439 content::RunMessageLoop();
440 EXPECT_GE(count, 0);
441 return count;
444 void FlushBlacklistPolicy() {
445 // Updates of the URLBlacklist are done on IO, after building the blacklist
446 // on FILE, which is initiated from IO.
447 content::RunAllPendingInMessageLoop(BrowserThread::IO);
448 content::RunAllPendingInMessageLoop(BrowserThread::FILE);
449 content::RunAllPendingInMessageLoop(BrowserThread::IO);
452 bool ContainsVisibleElement(content::WebContents* contents,
453 const std::string& id) {
454 bool result;
455 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
456 contents,
457 "var elem = document.getElementById('" + id + "');"
458 "domAutomationController.send(!!elem && !elem.hidden);",
459 &result));
460 return result;
463 #if defined(OS_CHROMEOS)
464 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
465 public:
466 TestAudioObserver() : output_mute_changed_count_(0) {
469 int output_mute_changed_count() const {
470 return output_mute_changed_count_;
473 virtual ~TestAudioObserver() {}
475 protected:
476 // chromeos::CrasAudioHandler::AudioObserver overrides.
477 virtual void OnOutputMuteChanged() OVERRIDE {
478 ++output_mute_changed_count_;
481 private:
482 int output_mute_changed_count_;
484 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
486 #endif
488 // This class waits until either a load stops or the WebContents is destroyed.
489 class WebContentsLoadedOrDestroyedWatcher
490 : public content::WebContentsObserver {
491 public:
492 explicit WebContentsLoadedOrDestroyedWatcher(
493 content::WebContents* web_contents);
494 virtual ~WebContentsLoadedOrDestroyedWatcher();
496 // Waits until the WebContents's load is done or until it is destroyed.
497 void Wait();
499 // Overridden WebContentsObserver methods.
500 virtual void WebContentsDestroyed(
501 content::WebContents* web_contents) OVERRIDE;
502 virtual void DidStopLoading(
503 content::RenderViewHost* render_view_host) OVERRIDE;
505 private:
506 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
508 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
511 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
512 content::WebContents* web_contents)
513 : content::WebContentsObserver(web_contents),
514 message_loop_runner_(new content::MessageLoopRunner) {
517 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
519 void WebContentsLoadedOrDestroyedWatcher::Wait() {
520 message_loop_runner_->Run();
523 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed(
524 content::WebContents* web_contents) {
525 message_loop_runner_->Quit();
528 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
529 content::RenderViewHost* render_view_host) {
530 message_loop_runner_->Quit();
533 #if !defined(OS_MACOSX)
535 // Observer used to wait for the creation of a new shell window.
536 class TestAddShellWindowObserver : public apps::ShellWindowRegistry::Observer {
537 public:
538 explicit TestAddShellWindowObserver(apps::ShellWindowRegistry* registry);
539 virtual ~TestAddShellWindowObserver();
541 // apps::ShellWindowRegistry::Observer:
542 virtual void OnShellWindowAdded(apps::ShellWindow* shell_window) OVERRIDE;
543 virtual void OnShellWindowIconChanged(
544 apps::ShellWindow* shell_window) OVERRIDE;
545 virtual void OnShellWindowRemoved(apps::ShellWindow* shell_window) OVERRIDE;
547 apps::ShellWindow* WaitForShellWindow();
549 private:
550 apps::ShellWindowRegistry* registry_; // Not owned.
551 apps::ShellWindow* window_; // Not owned.
552 base::RunLoop run_loop_;
554 DISALLOW_COPY_AND_ASSIGN(TestAddShellWindowObserver);
557 TestAddShellWindowObserver::TestAddShellWindowObserver(
558 apps::ShellWindowRegistry* registry)
559 : registry_(registry),
560 window_(NULL) {
561 registry_->AddObserver(this);
564 TestAddShellWindowObserver::~TestAddShellWindowObserver() {
565 registry_->RemoveObserver(this);
568 void TestAddShellWindowObserver::OnShellWindowAdded(
569 apps::ShellWindow* shell_window) {
570 window_ = shell_window;
571 run_loop_.Quit();
574 void TestAddShellWindowObserver::OnShellWindowIconChanged(
575 apps::ShellWindow* shell_window) {
578 void TestAddShellWindowObserver::OnShellWindowRemoved(
579 apps::ShellWindow* shell_window) {
582 apps::ShellWindow* TestAddShellWindowObserver::WaitForShellWindow() {
583 run_loop_.Run();
584 return window_;
587 #endif
589 } // namespace
591 class PolicyTest : public InProcessBrowserTest {
592 protected:
593 PolicyTest() {}
594 virtual ~PolicyTest() {}
596 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
597 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
598 EXPECT_CALL(provider_, IsInitializationComplete(_))
599 .WillRepeatedly(Return(true));
600 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
603 virtual void SetUpOnMainThread() OVERRIDE {
604 BrowserThread::PostTask(
605 BrowserThread::IO, FROM_HERE,
606 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
609 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
610 // instead of chrome::DIR_TEST_DATA.
611 void ServeContentTestData() {
612 base::FilePath root_http;
613 PathService::Get(content::DIR_TEST_DATA, &root_http);
614 BrowserThread::PostTaskAndReply(
615 BrowserThread::IO, FROM_HERE,
616 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http),
617 base::MessageLoop::current()->QuitWhenIdleClosure());
618 content::RunMessageLoop();
621 void SetScreenshotPolicy(bool enabled) {
622 PolicyMap policies;
623 policies.Set(key::kDisableScreenshots,
624 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
625 base::Value::CreateBooleanValue(!enabled), NULL);
626 UpdateProviderPolicy(policies);
629 #if defined(OS_CHROMEOS)
630 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
631 public:
632 virtual void OnScreenshotCompleted(
633 ScreenshotTakerObserver::Result screenshot_result,
634 const base::FilePath& screenshot_path) OVERRIDE {
635 BrowserThread::PostTaskAndReply(BrowserThread::IO,
636 FROM_HERE,
637 base::Bind(base::DoNothing),
638 base::MessageLoop::QuitClosure());
641 virtual ~QuitMessageLoopAfterScreenshot() {}
644 void TestScreenshotFile(bool enabled) {
645 // AddObserver is an ash-specific method, so just replace the screenshot
646 // taker with one we've created here.
647 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
648 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
649 // is tied to the test instead.
650 screenshot_taker->AddObserver(&observer_);
651 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
652 screenshot_taker.PassAs<ash::ScreenshotDelegate>());
654 SetScreenshotPolicy(enabled);
655 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
656 ash::TAKE_SCREENSHOT, ui::Accelerator());
658 content::RunMessageLoop();
660 #endif
662 ExtensionService* extension_service() {
663 extensions::ExtensionSystem* system =
664 extensions::ExtensionSystem::Get(browser()->profile());
665 return system->extension_service();
668 const extensions::Extension* InstallExtension(
669 const base::FilePath::StringType& name) {
670 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
671 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
672 scoped_refptr<extensions::CrxInstaller> installer =
673 extensions::CrxInstaller::CreateSilent(extension_service());
674 installer->set_allow_silent_install(true);
675 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
676 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
678 content::WindowedNotificationObserver observer(
679 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
680 content::NotificationService::AllSources());
681 installer->InstallCrx(extension_path);
682 observer.Wait();
683 content::Details<const extensions::Extension> details = observer.details();
684 return details.ptr();
687 const extensions::Extension* LoadUnpackedExtension(
688 const base::FilePath::StringType& name, bool expect_success) {
689 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
690 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
691 scoped_refptr<extensions::UnpackedInstaller> installer =
692 extensions::UnpackedInstaller::Create(extension_service());
693 content::WindowedNotificationObserver observer(
694 expect_success ? chrome::NOTIFICATION_EXTENSION_LOADED
695 : chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
696 content::NotificationService::AllSources());
697 installer->Load(extension_path);
698 observer.Wait();
700 const extensions::ExtensionSet* extensions =
701 extension_service()->extensions();
702 for (extensions::ExtensionSet::const_iterator it = extensions->begin();
703 it != extensions->end(); ++it) {
704 if ((*it)->path() == extension_path)
705 return it->get();
707 return NULL;
710 void UninstallExtension(const std::string& id, bool expect_success) {
711 content::WindowedNotificationObserver observer(
712 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED
713 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
714 content::NotificationService::AllSources());
715 extension_service()->UninstallExtension(id, false, NULL);
716 observer.Wait();
719 void UpdateProviderPolicy(const PolicyMap& policy) {
720 provider_.UpdateChromePolicy(policy);
721 DCHECK(base::MessageLoop::current());
722 base::RunLoop loop;
723 loop.RunUntilIdle();
726 // Sends a mouse click at the given coordinates to the current renderer.
727 void PerformClick(int x, int y) {
728 content::WebContents* contents =
729 browser()->tab_strip_model()->GetActiveWebContents();
730 blink::WebMouseEvent click_event;
731 click_event.type = blink::WebInputEvent::MouseDown;
732 click_event.button = blink::WebMouseEvent::ButtonLeft;
733 click_event.clickCount = 1;
734 click_event.x = x;
735 click_event.y = y;
736 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
737 click_event.type = blink::WebInputEvent::MouseUp;
738 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
741 MockConfigurationPolicyProvider provider_;
742 #if defined(OS_CHROMEOS)
743 QuitMessageLoopAfterScreenshot observer_;
744 #endif
747 #if defined(OS_WIN)
748 // This policy only exists on Windows.
750 // Sets the locale policy before the browser is started.
751 class LocalePolicyTest : public PolicyTest {
752 public:
753 LocalePolicyTest() {}
754 virtual ~LocalePolicyTest() {}
756 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
757 PolicyTest::SetUpInProcessBrowserTestFixture();
758 PolicyMap policies;
759 policies.Set(
760 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
761 base::Value::CreateStringValue("fr"), NULL);
762 provider_.UpdateChromePolicy(policies);
763 // The "en-US" ResourceBundle is always loaded before this step for tests,
764 // but in this test we want the browser to load the bundle as it
765 // normally would.
766 ResourceBundle::CleanupSharedInstance();
770 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
771 // Verifies that the default locale can be overridden with policy.
772 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
773 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
774 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
775 base::string16 title;
776 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
777 EXPECT_EQ(french_title, title);
779 // Make sure this is really French and differs from the English title.
780 std::string loaded =
781 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
782 EXPECT_EQ("en-US", loaded);
783 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
784 EXPECT_NE(french_title, english_title);
786 #endif
788 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
789 #if defined(OS_WIN) && defined(USE_ASH)
790 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
791 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
792 return;
793 #endif
795 // Verifies that the bookmarks bar can be forced to always or never show up.
797 // Test starts in about:blank.
798 PrefService* prefs = browser()->profile()->GetPrefs();
799 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
800 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
801 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
803 PolicyMap policies;
804 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
805 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
806 UpdateProviderPolicy(policies);
807 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
808 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar));
809 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
811 // The NTP has special handling of the bookmark bar.
812 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
813 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
815 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
816 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
817 UpdateProviderPolicy(policies);
818 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
819 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
820 // The bookmark bar is hidden in the NTP when disabled by policy.
821 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
823 policies.Clear();
824 UpdateProviderPolicy(policies);
825 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
826 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
827 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
828 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
831 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
832 // Verifies that cookies are deleted on shutdown. This test is split in 3
833 // parts because it spans 2 browser restarts.
835 Profile* profile = browser()->profile();
836 GURL url(kURL);
837 // No cookies at startup.
838 EXPECT_TRUE(content::GetCookies(profile, url).empty());
839 // Set a cookie now.
840 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
841 EXPECT_TRUE(content::SetCookie(profile, url, value));
842 // Verify it was set.
843 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
846 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
847 // Verify that the cookie persists across restarts.
848 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
849 // Now set the policy and the cookie should be gone after another restart.
850 PolicyMap policies;
851 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY,
852 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4), NULL);
853 UpdateProviderPolicy(policies);
856 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
857 // Verify that the cookie is gone.
858 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
861 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
862 MakeRequestFail make_request_fail("search.example");
864 // Verifies that a default search is made using the provider configured via
865 // policy. Also checks that default search can be completely disabled.
866 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
867 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
868 const std::string kAlternateURL0(
869 "http://search.example/search#q={searchTerms}");
870 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
871 const std::string kSearchTermsReplacementKey("zekey");
872 const std::string kImageURL("http://test.com/searchbyimage/upload");
873 const std::string kImageURLPostParams(
874 "image_content=content,image_url=http://test.com/test.png");
875 const std::string kNewTabURL("http://search.example/newtab");
877 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
878 browser()->profile());
879 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
880 TemplateURL* default_search = service->GetDefaultSearchProvider();
881 ASSERT_TRUE(default_search);
882 EXPECT_NE(kKeyword, default_search->keyword());
883 EXPECT_NE(kSearchURL, default_search->url());
884 EXPECT_FALSE(
885 default_search->alternate_urls().size() == 2 &&
886 default_search->alternate_urls()[0] == kAlternateURL0 &&
887 default_search->alternate_urls()[1] == kAlternateURL1 &&
888 default_search->search_terms_replacement_key() ==
889 kSearchTermsReplacementKey &&
890 default_search->image_url() == kImageURL &&
891 default_search->image_url_post_params() == kImageURLPostParams &&
892 default_search->new_tab_url() == kNewTabURL);
894 // Override the default search provider using policies.
895 PolicyMap policies;
896 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
897 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
898 policies.Set(key::kDefaultSearchProviderKeyword,
899 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
900 base::Value::CreateStringValue(kKeyword), NULL);
901 policies.Set(key::kDefaultSearchProviderSearchURL,
902 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
903 base::Value::CreateStringValue(kSearchURL), NULL);
904 base::ListValue* alternate_urls = new base::ListValue();
905 alternate_urls->AppendString(kAlternateURL0);
906 alternate_urls->AppendString(kAlternateURL1);
907 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
908 POLICY_SCOPE_USER, alternate_urls, NULL);
909 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
910 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
911 base::Value::CreateStringValue(kSearchTermsReplacementKey),
912 NULL);
913 policies.Set(key::kDefaultSearchProviderImageURL,
914 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
915 base::Value::CreateStringValue(kImageURL),
916 NULL);
917 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
918 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
919 base::Value::CreateStringValue(kImageURLPostParams),
920 NULL);
921 policies.Set(key::kDefaultSearchProviderNewTabURL,
922 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
923 base::Value::CreateStringValue(kNewTabURL),
924 NULL);
925 UpdateProviderPolicy(policies);
926 default_search = service->GetDefaultSearchProvider();
927 ASSERT_TRUE(default_search);
928 EXPECT_EQ(kKeyword, default_search->keyword());
929 EXPECT_EQ(kSearchURL, default_search->url());
930 EXPECT_EQ(2U, default_search->alternate_urls().size());
931 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
932 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
933 EXPECT_EQ(kSearchTermsReplacementKey,
934 default_search->search_terms_replacement_key());
935 EXPECT_EQ(kImageURL, default_search->image_url());
936 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
937 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
939 // Verify that searching from the omnibox uses kSearchURL.
940 chrome::FocusLocationBar(browser());
941 LocationBar* location_bar = browser()->window()->GetLocationBar();
942 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
943 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
944 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
945 content::WebContents* web_contents =
946 browser()->tab_strip_model()->GetActiveWebContents();
947 GURL expected("http://search.example/search?q=stuff+to+search+for");
948 EXPECT_EQ(expected, web_contents->GetURL());
950 // Verify that searching from the omnibox can be disabled.
951 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
952 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
953 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
954 EXPECT_TRUE(service->GetDefaultSearchProvider());
955 UpdateProviderPolicy(policies);
956 EXPECT_FALSE(service->GetDefaultSearchProvider());
957 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
958 // This means that submitting won't trigger any action.
959 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
960 EXPECT_EQ(GURL(content::kAboutBlankURL), web_contents->GetURL());
963 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
964 // Add an individual proxy policy value.
965 PolicyMap policies;
966 policies.Set(key::kProxyServerMode,
967 POLICY_LEVEL_MANDATORY,
968 POLICY_SCOPE_USER,
969 base::Value::CreateIntegerValue(3),
970 NULL);
971 UpdateProviderPolicy(policies);
973 // It should be removed and replaced with a dictionary.
974 PolicyMap expected;
975 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
976 expected_value->SetInteger(key::kProxyServerMode, 3);
977 expected.Set(key::kProxySettings,
978 POLICY_LEVEL_MANDATORY,
979 POLICY_SCOPE_USER,
980 expected_value.release(),
981 NULL);
983 // Check both the browser and the profile.
984 const PolicyMap& actual_from_browser =
985 g_browser_process->browser_policy_connector()
986 ->GetPolicyService()
987 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
988 EXPECT_TRUE(expected.Equals(actual_from_browser));
989 const PolicyMap& actual_from_profile =
990 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
991 ->policy_service()
992 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
993 EXPECT_TRUE(expected.Equals(actual_from_profile));
996 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
997 // Makes the requests fail since all we want to check is that the redirection
998 // is done properly.
999 MakeRequestFail make_request_fail("google.com");
1001 // Verifies that requests to Google Search engine with the SafeSearch
1002 // enabled set the safe=active&ssui=on parameters at the end of the query.
1003 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1004 browser()->profile());
1005 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1007 // First check that nothing happens.
1008 content::TestNavigationObserver no_safesearch_observer(
1009 browser()->tab_strip_model()->GetActiveWebContents());
1010 chrome::FocusLocationBar(browser());
1011 LocationBar* location_bar = browser()->window()->GetLocationBar();
1012 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1013 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1014 no_safesearch_observer.Wait();
1015 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1016 content::WebContents* web_contents =
1017 browser()->tab_strip_model()->GetActiveWebContents();
1018 GURL expected_without("http://google.com/");
1019 EXPECT_EQ(expected_without, web_contents->GetURL());
1021 PrefService* prefs = browser()->profile()->GetPrefs();
1022 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1023 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1025 // Override the default SafeSearch setting using policies.
1026 PolicyMap policies;
1027 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
1028 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1029 UpdateProviderPolicy(policies);
1031 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1032 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1034 content::TestNavigationObserver safesearch_observer(
1035 browser()->tab_strip_model()->GetActiveWebContents());
1037 // Verify that searching from google.com works.
1038 chrome::FocusLocationBar(browser());
1039 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1040 safesearch_observer.Wait();
1041 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1042 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1043 std::string expected_url("http://google.com/?");
1044 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1045 chrome::kSafeSearchSsuiParameter;
1046 GURL expected_with_parameters(expected_url);
1047 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1050 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1051 MakeRequestFail make_request_fail("search.example");
1053 chrome::EnableQueryExtractionForTesting();
1055 // Verifies that a default search is made using the provider configured via
1056 // policy. Also checks that default search can be completely disabled.
1057 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1058 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1059 const std::string kInstantURL("http://does/not/exist");
1060 const std::string kAlternateURL0(
1061 "https://www.google.com/search#q={searchTerms}");
1062 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1063 const std::string kSearchTermsReplacementKey(
1064 "{google:instantExtendedEnabledKey}");
1066 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1067 browser()->profile());
1068 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1069 TemplateURL* default_search = service->GetDefaultSearchProvider();
1070 ASSERT_TRUE(default_search);
1071 EXPECT_NE(kKeyword, default_search->keyword());
1072 EXPECT_NE(kSearchURL, default_search->url());
1073 EXPECT_NE(kInstantURL, default_search->instant_url());
1074 EXPECT_FALSE(
1075 default_search->alternate_urls().size() == 2 &&
1076 default_search->alternate_urls()[0] == kAlternateURL0 &&
1077 default_search->alternate_urls()[1] == kAlternateURL1);
1079 // Override the default search provider using policies.
1080 PolicyMap policies;
1081 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1082 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1083 policies.Set(key::kDefaultSearchProviderKeyword,
1084 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1085 base::Value::CreateStringValue(kKeyword), NULL);
1086 policies.Set(key::kDefaultSearchProviderSearchURL,
1087 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1088 base::Value::CreateStringValue(kSearchURL), NULL);
1089 policies.Set(key::kDefaultSearchProviderInstantURL,
1090 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1091 base::Value::CreateStringValue(kInstantURL), NULL);
1092 base::ListValue* alternate_urls = new base::ListValue();
1093 alternate_urls->AppendString(kAlternateURL0);
1094 alternate_urls->AppendString(kAlternateURL1);
1095 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1096 POLICY_SCOPE_USER, alternate_urls, NULL);
1097 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1098 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1099 base::Value::CreateStringValue(kSearchTermsReplacementKey),
1100 NULL);
1101 UpdateProviderPolicy(policies);
1102 default_search = service->GetDefaultSearchProvider();
1103 ASSERT_TRUE(default_search);
1104 EXPECT_EQ(kKeyword, default_search->keyword());
1105 EXPECT_EQ(kSearchURL, default_search->url());
1106 EXPECT_EQ(kInstantURL, default_search->instant_url());
1107 EXPECT_EQ(2U, default_search->alternate_urls().size());
1108 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1109 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1111 // Query terms replacement requires that the renderer process be a recognized
1112 // Instant renderer. Fake it.
1113 InstantService* instant_service =
1114 InstantServiceFactory::GetForProfile(browser()->profile());
1115 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1116 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1118 // Verify that searching from the omnibox does search term replacement with
1119 // first URL pattern.
1120 chrome::FocusLocationBar(browser());
1121 LocationBar* location_bar = browser()->window()->GetLocationBar();
1122 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1123 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1124 "https://www.google.com/?espv=1#q=foobar");
1125 EXPECT_TRUE(
1126 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1127 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1129 // Verify that not using espv=1 does not do search term replacement.
1130 chrome::FocusLocationBar(browser());
1131 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1132 "https://www.google.com/?q=foobar");
1133 EXPECT_FALSE(
1134 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1135 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1136 omnibox_view->GetText());
1138 // Verify that searching from the omnibox does search term replacement with
1139 // second URL pattern.
1140 chrome::FocusLocationBar(browser());
1141 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1142 "https://www.google.com/search?espv=1#q=banana");
1143 EXPECT_TRUE(
1144 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1145 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1147 // Verify that searching from the omnibox does search term replacement with
1148 // standard search URL pattern.
1149 chrome::FocusLocationBar(browser());
1150 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1151 "https://www.google.com/search?q=tractor+parts&espv=1");
1152 EXPECT_TRUE(
1153 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1154 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1156 // Verify that searching from the omnibox prioritizes hash over query.
1157 chrome::FocusLocationBar(browser());
1158 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1159 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1160 EXPECT_TRUE(
1161 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1162 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1165 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1166 // This test assumes Gpu access.
1167 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1168 return;
1170 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1171 // WebGL is enabled by default.
1172 content::WebContents* contents =
1173 browser()->tab_strip_model()->GetActiveWebContents();
1174 EXPECT_TRUE(IsWebGLEnabled(contents));
1175 // Disable with a policy.
1176 PolicyMap policies;
1177 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1178 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1179 UpdateProviderPolicy(policies);
1180 // Crash and reload the tab to get a new renderer.
1181 content::CrashTab(contents);
1182 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1183 EXPECT_FALSE(IsWebGLEnabled(contents));
1184 // Enable with a policy.
1185 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1186 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1187 UpdateProviderPolicy(policies);
1188 content::CrashTab(contents);
1189 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1190 EXPECT_TRUE(IsWebGLEnabled(contents));
1193 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1194 // Verifies that SPDY can be disable by policy.
1195 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1196 PolicyMap policies;
1197 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1198 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1199 UpdateProviderPolicy(policies);
1200 content::RunAllPendingInMessageLoop();
1201 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1202 // Verify that it can be force-enabled too.
1203 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1204 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1205 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1206 UpdateProviderPolicy(policies);
1207 content::RunAllPendingInMessageLoop();
1208 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1211 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1212 // Verifies that plugins can be forced to be disabled by policy.
1214 // Verify that the Flash plugin exists and that it can be enabled and disabled
1215 // by the user.
1216 std::vector<content::WebPluginInfo> plugins;
1217 GetPluginList(&plugins);
1218 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1219 if (!flash)
1220 return;
1221 PluginPrefs* plugin_prefs =
1222 PluginPrefs::GetForProfile(browser()->profile()).get();
1223 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1224 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1225 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1226 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1227 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1229 // Now disable it with a policy.
1230 base::ListValue disabled_plugins;
1231 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
1232 PolicyMap policies;
1233 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1234 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1235 UpdateProviderPolicy(policies);
1236 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1237 // The user shouldn't be able to enable it.
1238 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1239 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1242 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1243 // Verifies that plugins with an exception in the blacklist can be enabled.
1245 // Verify that the Flash plugin exists and that it can be enabled and disabled
1246 // by the user.
1247 std::vector<content::WebPluginInfo> plugins;
1248 GetPluginList(&plugins);
1249 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1250 if (!flash)
1251 return;
1252 PluginPrefs* plugin_prefs =
1253 PluginPrefs::GetForProfile(browser()->profile()).get();
1254 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1256 // Disable all plugins.
1257 base::ListValue disabled_plugins;
1258 disabled_plugins.Append(base::Value::CreateStringValue("*"));
1259 PolicyMap policies;
1260 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1261 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1262 UpdateProviderPolicy(policies);
1263 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1264 // The user shouldn't be able to enable it.
1265 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1266 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1268 // Now open an exception for flash.
1269 base::ListValue disabled_plugins_exceptions;
1270 disabled_plugins_exceptions.Append(
1271 base::Value::CreateStringValue("*Flash*"));
1272 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1273 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1274 UpdateProviderPolicy(policies);
1275 // It should revert to the user's preference automatically.
1276 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1277 // And the user should be able to disable and enable again.
1278 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1279 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1280 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1281 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1284 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1285 // Verifies that a plugin can be force-installed with a policy.
1286 std::vector<content::WebPluginInfo> plugins;
1287 GetPluginList(&plugins);
1288 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1289 if (!flash)
1290 return;
1291 PluginPrefs* plugin_prefs =
1292 PluginPrefs::GetForProfile(browser()->profile()).get();
1293 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1295 // The user disables it and then a policy forces it to be enabled.
1296 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1297 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1298 base::ListValue plugin_list;
1299 plugin_list.Append(base::Value::CreateStringValue(content::kFlashPluginName));
1300 PolicyMap policies;
1301 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1302 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1303 UpdateProviderPolicy(policies);
1304 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1305 // The user can't disable it anymore.
1306 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1307 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1309 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1310 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1311 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1312 UpdateProviderPolicy(policies);
1313 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1316 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1317 // Verifies that dangerous plugins can be always authorized to run with
1318 // a policy.
1320 // Verify that the test page exists. It is only present in checkouts with
1321 // src-internal.
1322 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1323 base::FilePath(FILE_PATH_LITERAL("plugin")),
1324 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1325 LOG(INFO) <<
1326 "Test skipped because plugin/quicktime.html test file wasn't found.";
1327 return;
1330 ServeContentTestData();
1331 // No plugins at startup.
1332 EXPECT_EQ(0, CountPlugins());
1334 content::WebContents* contents =
1335 browser()->tab_strip_model()->GetActiveWebContents();
1336 ASSERT_TRUE(contents);
1337 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1338 ASSERT_TRUE(infobar_service);
1339 EXPECT_EQ(0u, infobar_service->infobar_count());
1341 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1342 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1343 ui_test_utils::NavigateToURL(browser(), url);
1344 // This should have triggered the dangerous plugin infobar.
1345 ASSERT_EQ(1u, infobar_service->infobar_count());
1346 EXPECT_TRUE(
1347 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1348 // And the plugin isn't running.
1349 EXPECT_EQ(0, CountPlugins());
1351 // Now set a policy to always authorize this.
1352 PolicyMap policies;
1353 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1354 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1355 UpdateProviderPolicy(policies);
1356 // Reloading the page shouldn't trigger the infobar this time.
1357 ui_test_utils::NavigateToURL(browser(), url);
1358 EXPECT_EQ(0u, infobar_service->infobar_count());
1359 // And the plugin started automatically.
1360 EXPECT_EQ(1, CountPlugins());
1363 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1364 // Verifies that access to the developer tools can be disabled.
1366 // Open devtools.
1367 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1368 content::WebContents* contents =
1369 browser()->tab_strip_model()->GetActiveWebContents();
1370 DevToolsWindow *devtools_window =
1371 DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1372 contents->GetRenderViewHost());
1373 EXPECT_TRUE(devtools_window);
1375 // Disable devtools via policy.
1376 PolicyMap policies;
1377 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1378 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1379 content::WindowedNotificationObserver close_observer(
1380 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1381 content::Source<content::WebContents>(devtools_window->web_contents()));
1382 UpdateProviderPolicy(policies);
1383 // wait for devtools close
1384 close_observer.Wait();
1385 // The existing devtools window should have closed.
1386 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1387 contents->GetRenderViewHost()));
1388 // And it's not possible to open it again.
1389 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1390 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1391 contents->GetRenderViewHost()));
1394 // TODO(samarth): remove along with rest of NTP4 code.
1395 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1396 #if defined(OS_WIN) && defined(USE_ASH)
1397 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1398 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1399 return;
1400 #endif
1402 // Verifies that the web store icons can be hidden from the new tab page.
1404 // Open new tab page and look for the web store icons.
1405 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1406 content::WebContents* contents =
1407 browser()->tab_strip_model()->GetActiveWebContents();
1409 #if !defined(OS_CHROMEOS)
1410 // Look for web store's app ID in the apps page.
1411 EXPECT_TRUE(ContainsVisibleElement(contents,
1412 "ahfgeienlihckogmohjhadlkjgocpleb"));
1413 #endif
1415 // The next NTP has no footer.
1416 if (ContainsVisibleElement(contents, "footer"))
1417 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1419 // Turn off the web store icons.
1420 PolicyMap policies;
1421 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
1422 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1423 UpdateProviderPolicy(policies);
1425 // The web store icons should now be hidden.
1426 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1427 EXPECT_FALSE(ContainsVisibleElement(contents,
1428 "ahfgeienlihckogmohjhadlkjgocpleb"));
1429 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1432 // This policy isn't available on Chrome OS.
1433 #if !defined(OS_CHROMEOS)
1434 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1435 // Verifies that the download directory can be forced by policy.
1437 // Set the initial download directory.
1438 base::ScopedTempDir initial_dir;
1439 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1440 browser()->profile()->GetPrefs()->SetFilePath(
1441 prefs::kDownloadDefaultDirectory, initial_dir.path());
1442 // Don't prompt for the download location during this test.
1443 browser()->profile()->GetPrefs()->SetBoolean(
1444 prefs::kPromptForDownload, false);
1446 // Verify that downloads end up on the default directory.
1447 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1448 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1449 file_util::DieFileDie(initial_dir.path().Append(file), false);
1451 // Override the download directory with the policy and verify a download.
1452 base::ScopedTempDir forced_dir;
1453 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1454 PolicyMap policies;
1455 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1456 POLICY_SCOPE_USER,
1457 base::Value::CreateStringValue(forced_dir.path().value()), NULL);
1458 UpdateProviderPolicy(policies);
1459 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1460 // Verify that the first download location wasn't affected.
1461 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1463 #endif
1465 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1466 // Verifies that blacklisted extensions can't be installed.
1467 ExtensionService* service = extension_service();
1468 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1469 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1470 base::ListValue blacklist;
1471 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1472 PolicyMap policies;
1473 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1474 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1475 UpdateProviderPolicy(policies);
1477 // "good.crx" is blacklisted.
1478 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1479 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1481 // "adblock.crx" is not.
1482 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1483 ASSERT_TRUE(adblock);
1484 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1485 EXPECT_EQ(adblock,
1486 service->GetExtensionById(kAdBlockCrxId, true));
1489 // Flaky on windows; http://crbug.com/307994.
1490 #if defined(OS_WIN)
1491 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1492 #else
1493 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1494 #endif
1495 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1496 // Verify that a wildcard blacklist takes effect.
1497 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1498 ExtensionService* service = extension_service();
1499 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1500 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1501 base::ListValue blacklist;
1502 blacklist.Append(base::Value::CreateStringValue("*"));
1503 PolicyMap policies;
1504 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1505 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1506 UpdateProviderPolicy(policies);
1508 // AdBlock was automatically removed.
1509 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1511 // And can't be installed again, nor can good.crx.
1512 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1513 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1514 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1515 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1518 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1519 // Verifies that the whitelist can open exceptions to the blacklist.
1520 ExtensionService* service = extension_service();
1521 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1522 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1523 base::ListValue blacklist;
1524 blacklist.Append(base::Value::CreateStringValue("*"));
1525 base::ListValue whitelist;
1526 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1527 PolicyMap policies;
1528 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1529 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1530 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1531 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1532 UpdateProviderPolicy(policies);
1533 // "adblock.crx" is blacklisted.
1534 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1535 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1536 // "good.crx" has a whitelist exception.
1537 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1538 ASSERT_TRUE(good);
1539 EXPECT_EQ(kGoodCrxId, good->id());
1540 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1541 // The user can also remove this extension.
1542 UninstallExtension(kGoodCrxId, true);
1545 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1546 // Verifies that extensions that are force-installed by policies are
1547 // installed and can't be uninstalled.
1548 ExtensionService* service = extension_service();
1549 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1551 // Extensions that are force-installed come from an update URL, which defaults
1552 // to the webstore. Use a mock URL for this test with an update manifest
1553 // that includes "good_v1.crx".
1554 base::FilePath path =
1555 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1556 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1558 // Setting the forcelist extension should install "good_v1.crx".
1559 base::ListValue forcelist;
1560 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf(
1561 "%s;%s", kGoodCrxId, url.spec().c_str())));
1562 PolicyMap policies;
1563 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1564 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1565 content::WindowedNotificationObserver observer(
1566 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1567 content::NotificationService::AllSources());
1568 UpdateProviderPolicy(policies);
1569 observer.Wait();
1570 // Note: Cannot check that the notification details match the expected
1571 // exception, since the details object has already been freed prior to
1572 // the completion of observer.Wait().
1574 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1576 // The user is not allowed to uninstall force-installed extensions.
1577 UninstallExtension(kGoodCrxId, false);
1579 // The user is not allowed to load an unpacked extension with the
1580 // same ID as a force-installed extension.
1581 LoadUnpackedExtension(kGoodUnpackedExt, false);
1583 // Loading other unpacked extensions are not blocked.
1584 LoadUnpackedExtension(kAppUnpackedExt, true);
1586 const std::string old_version_number =
1587 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1589 base::FilePath test_path;
1590 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1592 TestRequestInterceptor interceptor(
1593 "update.extension",
1594 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1595 interceptor.PushJobCallback(
1596 TestRequestInterceptor::FileJob(
1597 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1599 // Updating the force-installed extension.
1600 extensions::ExtensionUpdater* updater = service->updater();
1601 extensions::ExtensionUpdater::CheckParams params;
1602 params.install_immediately = true;
1603 content::WindowedNotificationObserver update_observer(
1604 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1605 content::NotificationService::AllSources());
1606 updater->CheckNow(params);
1607 update_observer.Wait();
1609 const base::Version* new_version =
1610 service->GetExtensionById(kGoodCrxId, true)->version();
1611 ASSERT_TRUE(new_version->IsValid());
1612 base::Version old_version(old_version_number);
1613 ASSERT_TRUE(old_version.IsValid());
1615 EXPECT_EQ(1, new_version->CompareTo(old_version));
1617 EXPECT_EQ(0u, interceptor.GetPendingSize());
1619 // Wait until any background pages belonging to force-installed extensions
1620 // have been loaded.
1621 extensions::ProcessManager* manager =
1622 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1623 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1624 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1625 all_views.begin();
1626 iter != all_views.end();) {
1627 if (!(*iter)->IsLoading()) {
1628 ++iter;
1629 } else {
1630 content::WebContents* web_contents =
1631 content::WebContents::FromRenderViewHost(*iter);
1632 ASSERT_TRUE(web_contents);
1633 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1635 // Test activity may have modified the set of extension processes during
1636 // message processing, so re-start the iteration to catch added/removed
1637 // processes.
1638 all_views = manager->GetAllViews();
1639 iter = all_views.begin();
1643 // Test policy-installed extensions are reloaded when killed.
1644 BackgroundContentsService::
1645 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1646 content::WindowedNotificationObserver extension_crashed_observer(
1647 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1648 content::NotificationService::AllSources());
1649 content::WindowedNotificationObserver extension_loaded_observer(
1650 chrome::NOTIFICATION_EXTENSION_LOADED,
1651 content::NotificationService::AllSources());
1652 extensions::ExtensionHost* extension_host =
1653 extensions::ExtensionSystem::Get(browser()->profile())->
1654 process_manager()->GetBackgroundHostForExtension(kGoodCrxId);
1655 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1656 content::RESULT_CODE_KILLED, false);
1657 extension_crashed_observer.Wait();
1658 extension_loaded_observer.Wait();
1661 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1662 // Verifies that extensions are blocked if policy specifies an allowed types
1663 // list and the extension's type is not on that list.
1664 ExtensionService* service = extension_service();
1665 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1666 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1668 base::ListValue allowed_types;
1669 allowed_types.AppendString("hosted_app");
1670 PolicyMap policies;
1671 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1672 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1673 UpdateProviderPolicy(policies);
1675 // "good.crx" is blocked.
1676 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1677 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1679 // "hosted_app.crx" is of a whitelisted type.
1680 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1681 ASSERT_TRUE(hosted_app);
1682 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1683 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1685 // The user can remove the extension.
1686 UninstallExtension(kHostedAppCrxId, true);
1689 // Checks that a click on an extension CRX download triggers the extension
1690 // installation prompt without further user interaction when the source is
1691 // whitelisted by policy.
1692 // Flaky on windows; http://crbug.com/295729 .
1693 #if defined(OS_WIN)
1694 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1695 #else
1696 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1697 #endif
1698 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1699 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1700 switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
1702 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1703 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1704 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1705 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1707 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1708 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1709 ui_test_utils::NavigateToURL(browser(), download_page_url);
1711 // As long as the policy is not present, extensions are considered dangerous.
1712 content::DownloadTestObserverTerminal download_observer(
1713 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1714 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1715 PerformClick(0, 0);
1716 download_observer.WaitForFinished();
1718 // Install the policy and trigger another download.
1719 base::ListValue install_sources;
1720 install_sources.AppendString(install_source_url.spec());
1721 install_sources.AppendString(referrer_url.spec());
1722 PolicyMap policies;
1723 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1724 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1725 UpdateProviderPolicy(policies);
1727 content::WindowedNotificationObserver observer(
1728 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1729 content::NotificationService::AllSources());
1730 PerformClick(1, 0);
1731 observer.Wait();
1732 // Note: Cannot check that the notification details match the expected
1733 // exception, since the details object has already been freed prior to
1734 // the completion of observer.Wait().
1736 // The first extension shouldn't be present, the second should be there.
1737 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1738 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1741 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1742 #if defined(OS_WIN) && defined(USE_ASH)
1743 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1744 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1745 return;
1746 #endif
1748 // Verifies that the homepage can be configured with policies.
1749 // Set a default, and check that the home button navigates there.
1750 browser()->profile()->GetPrefs()->SetString(
1751 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1752 browser()->profile()->GetPrefs()->SetBoolean(
1753 prefs::kHomePageIsNewTabPage, false);
1754 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1755 browser()->profile()->GetHomePage());
1756 content::WebContents* contents =
1757 browser()->tab_strip_model()->GetActiveWebContents();
1758 EXPECT_EQ(GURL(content::kAboutBlankURL), contents->GetURL());
1759 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1760 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1762 // Now override with policy.
1763 PolicyMap policies;
1764 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1765 POLICY_SCOPE_USER,
1766 base::Value::CreateStringValue(chrome::kChromeUICreditsURL),
1767 NULL);
1768 UpdateProviderPolicy(policies);
1769 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1770 content::WaitForLoadStop(contents);
1771 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1773 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1774 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1775 UpdateProviderPolicy(policies);
1776 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1777 content::WaitForLoadStop(contents);
1778 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1781 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1782 // Verifies that incognito windows can't be opened when disabled by policy.
1784 const BrowserList* active_browser_list =
1785 BrowserList::GetInstance(chrome::GetActiveDesktop());
1787 // Disable incognito via policy and verify that incognito windows can't be
1788 // opened.
1789 EXPECT_EQ(1u, active_browser_list->size());
1790 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1791 PolicyMap policies;
1792 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1793 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1794 UpdateProviderPolicy(policies);
1795 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1796 EXPECT_EQ(1u, active_browser_list->size());
1797 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1799 // Enable via policy and verify that incognito windows can be opened.
1800 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1801 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1802 UpdateProviderPolicy(policies);
1803 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1804 EXPECT_EQ(2u, active_browser_list->size());
1805 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1808 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1809 // Verifies that Javascript can be disabled.
1810 content::WebContents* contents =
1811 browser()->tab_strip_model()->GetActiveWebContents();
1812 EXPECT_TRUE(IsJavascriptEnabled(contents));
1813 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1814 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1815 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1817 // Disable Javascript via policy.
1818 PolicyMap policies;
1819 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1820 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1821 UpdateProviderPolicy(policies);
1822 // Reload the page.
1823 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1824 EXPECT_FALSE(IsJavascriptEnabled(contents));
1825 // Developer tools still work when javascript is disabled.
1826 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1827 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1828 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1829 // Javascript is always enabled for the internal pages.
1830 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1831 EXPECT_TRUE(IsJavascriptEnabled(contents));
1833 // The javascript content setting policy overrides the javascript policy.
1834 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1835 EXPECT_FALSE(IsJavascriptEnabled(contents));
1836 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1837 POLICY_SCOPE_USER,
1838 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL);
1839 UpdateProviderPolicy(policies);
1840 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1841 EXPECT_TRUE(IsJavascriptEnabled(contents));
1844 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1845 // Verifies that browsing history is not saved.
1846 PolicyMap policies;
1847 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1848 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1849 UpdateProviderPolicy(policies);
1850 GURL url = ui_test_utils::GetTestUrl(
1851 base::FilePath(base::FilePath::kCurrentDirectory),
1852 base::FilePath(FILE_PATH_LITERAL("empty.html")));
1853 ui_test_utils::NavigateToURL(browser(), url);
1854 // Verify that the navigation wasn't saved in the history.
1855 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1856 EXPECT_EQ(0u, enumerator1.urls().size());
1858 // Now flip the policy and try again.
1859 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1860 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1861 UpdateProviderPolicy(policies);
1862 ui_test_utils::NavigateToURL(browser(), url);
1863 // Verify that the navigation was saved in the history.
1864 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1865 ASSERT_EQ(1u, enumerator2.urls().size());
1866 EXPECT_EQ(url, enumerator2.urls()[0]);
1869 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
1870 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
1871 // Verifies that translate can be forced enabled or disabled by policy.
1873 // Get the InfoBarService, and verify that there are no infobars on startup.
1874 content::WebContents* contents =
1875 browser()->tab_strip_model()->GetActiveWebContents();
1876 ASSERT_TRUE(contents);
1877 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1878 ASSERT_TRUE(infobar_service);
1879 EXPECT_EQ(0u, infobar_service->infobar_count());
1881 // Force enable the translate feature.
1882 PolicyMap policies;
1883 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1884 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1885 UpdateProviderPolicy(policies);
1886 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
1887 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
1888 // TranslateManager observes. This allows checking that an infobar is NOT
1889 // shown below, without polling for infobars for some indeterminate amount
1890 // of time.
1891 GURL url = ui_test_utils::GetTestUrl(
1892 base::FilePath(),
1893 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
1894 content::WindowedNotificationObserver language_observer1(
1895 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1896 content::NotificationService::AllSources());
1897 ui_test_utils::NavigateToURL(browser(), url);
1898 language_observer1.Wait();
1900 // Verify the translation detected for this tab.
1901 TranslateTabHelper* translate_tab_helper =
1902 TranslateTabHelper::FromWebContents(contents);
1903 ASSERT_TRUE(translate_tab_helper);
1904 LanguageState& language_state = translate_tab_helper->language_state();
1905 EXPECT_EQ("fr", language_state.original_language());
1906 EXPECT_TRUE(language_state.page_needs_translation());
1907 EXPECT_FALSE(language_state.translation_pending());
1908 EXPECT_FALSE(language_state.translation_declined());
1909 EXPECT_FALSE(language_state.IsPageTranslated());
1911 // Verify that the translate infobar showed up.
1912 ASSERT_EQ(1u, infobar_service->infobar_count());
1913 InfoBar* infobar = infobar_service->infobar_at(0);
1914 TranslateInfoBarDelegate* translate_infobar_delegate =
1915 infobar->delegate()->AsTranslateInfoBarDelegate();
1916 ASSERT_TRUE(translate_infobar_delegate);
1917 EXPECT_EQ(TranslateInfoBarDelegate::BEFORE_TRANSLATE,
1918 translate_infobar_delegate->infobar_type());
1919 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
1921 // Now force disable translate.
1922 infobar_service->RemoveInfoBar(infobar);
1923 EXPECT_EQ(0u, infobar_service->infobar_count());
1924 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1925 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1926 UpdateProviderPolicy(policies);
1927 // Navigating to the same URL now doesn't trigger an infobar.
1928 content::WindowedNotificationObserver language_observer2(
1929 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1930 content::NotificationService::AllSources());
1931 ui_test_utils::NavigateToURL(browser(), url);
1932 language_observer2.Wait();
1933 EXPECT_EQ(0u, infobar_service->infobar_count());
1936 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
1937 // Checks that URLs can be blacklisted, and that exceptions can be made to
1938 // the blacklist.
1940 // Filter |kURLS| on IO thread, so that requests to those hosts end up
1941 // as URLRequestMockHTTPJobs.
1942 const char* kURLS[] = {
1943 "http://aaa.com/empty.html",
1944 "http://bbb.com/empty.html",
1945 "http://sub.bbb.com/empty.html",
1946 "http://bbb.com/policy/blank.html",
1949 base::RunLoop loop;
1950 BrowserThread::PostTaskAndReply(
1951 BrowserThread::IO, FROM_HERE,
1952 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
1953 loop.QuitClosure());
1954 loop.Run();
1957 // Verify that "bbb.com" opens before applying the blacklist.
1958 CheckCanOpenURL(browser(), kURLS[1]);
1960 // Set a blacklist.
1961 base::ListValue blacklist;
1962 blacklist.Append(base::Value::CreateStringValue("bbb.com"));
1963 PolicyMap policies;
1964 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1965 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1966 UpdateProviderPolicy(policies);
1967 FlushBlacklistPolicy();
1968 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
1969 CheckCanOpenURL(browser(), kURLS[0]);
1970 for (size_t i = 1; i < arraysize(kURLS); ++i)
1971 CheckURLIsBlocked(browser(), kURLS[i]);
1973 // Whitelist some sites of bbb.com.
1974 base::ListValue whitelist;
1975 whitelist.Append(base::Value::CreateStringValue("sub.bbb.com"));
1976 whitelist.Append(base::Value::CreateStringValue("bbb.com/policy"));
1977 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1978 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1979 UpdateProviderPolicy(policies);
1980 FlushBlacklistPolicy();
1981 CheckURLIsBlocked(browser(), kURLS[1]);
1982 CheckCanOpenURL(browser(), kURLS[2]);
1983 CheckCanOpenURL(browser(), kURLS[3]);
1986 base::RunLoop loop;
1987 BrowserThread::PostTaskAndReply(
1988 BrowserThread::IO, FROM_HERE,
1989 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
1990 loop.QuitClosure());
1991 loop.Run();
1995 IN_PROC_BROWSER_TEST_F(PolicyTest, FileURLBlacklist) {
1996 // Check that FileURLs can be blacklisted and DisabledSchemes works together
1997 // with URLblacklisting and URLwhitelisting.
1999 base::FilePath test_path;
2000 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2001 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2002 const std::string folder_path = base_path + "apptest/";
2003 const std::string file_path1 = base_path + "title1.html";
2004 const std::string file_path2 = folder_path + "basic.html";
2006 CheckCanOpenURL(browser(), file_path1.c_str());
2007 CheckCanOpenURL(browser(), file_path2.c_str());
2009 // Set a blacklist for all the files.
2010 base::ListValue blacklist;
2011 blacklist.Append(base::Value::CreateStringValue("file://*"));
2012 PolicyMap policies;
2013 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2014 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2015 UpdateProviderPolicy(policies);
2016 FlushBlacklistPolicy();
2018 CheckURLIsBlocked(browser(), file_path1.c_str());
2019 CheckURLIsBlocked(browser(), file_path2.c_str());
2021 // Replace the URLblacklist with disabling the file scheme.
2022 blacklist.Remove(base::StringValue("file://*"), NULL);
2023 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2024 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2025 UpdateProviderPolicy(policies);
2026 FlushBlacklistPolicy();
2028 PrefService* prefs = browser()->profile()->GetPrefs();
2029 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2030 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2031 list_url->end());
2033 base::ListValue disabledscheme;
2034 disabledscheme.Append(base::Value::CreateStringValue("file"));
2035 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2036 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2037 UpdateProviderPolicy(policies);
2038 FlushBlacklistPolicy();
2040 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2041 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2042 list_url->end());
2044 // Whitelist one folder and blacklist an another just inside.
2045 base::ListValue whitelist;
2046 whitelist.Append(base::Value::CreateStringValue(base_path));
2047 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2048 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2049 blacklist.Append(base::Value::CreateStringValue(folder_path));
2050 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2051 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2052 UpdateProviderPolicy(policies);
2053 FlushBlacklistPolicy();
2055 CheckCanOpenURL(browser(), file_path1.c_str());
2056 CheckURLIsBlocked(browser(), file_path2.c_str());
2059 #if !defined(OS_MACOSX)
2060 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2061 PolicyMap policies;
2062 policies.Set(key::kFullscreenAllowed,
2063 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2064 base::Value::CreateBooleanValue(false), NULL);
2065 UpdateProviderPolicy(policies);
2067 BrowserWindow* browser_window = browser()->window();
2068 ASSERT_TRUE(browser_window);
2070 EXPECT_FALSE(browser_window->IsFullscreen());
2071 chrome::ToggleFullscreenMode(browser());
2072 EXPECT_FALSE(browser_window->IsFullscreen());
2075 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2076 PolicyMap policies;
2077 policies.Set(key::kFullscreenAllowed,
2078 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2079 base::Value::CreateBooleanValue(false), NULL);
2080 UpdateProviderPolicy(policies);
2082 const extensions::Extension* extension =
2083 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2084 ASSERT_TRUE(extension);
2086 // Launch an app that tries to open a fullscreen window.
2087 TestAddShellWindowObserver add_window_observer(
2088 apps::ShellWindowRegistry::Get(browser()->profile()));
2089 OpenApplication(AppLaunchParams(browser()->profile(),
2090 extension,
2091 extensions::LAUNCH_CONTAINER_NONE,
2092 NEW_WINDOW));
2093 apps::ShellWindow* window = add_window_observer.WaitForShellWindow();
2094 ASSERT_TRUE(window);
2096 // Verify that the window is not in fullscreen mode.
2097 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2099 // Verify that the window cannot be toggled into fullscreen mode via apps
2100 // APIs.
2101 EXPECT_TRUE(content::ExecuteScript(
2102 window->web_contents(),
2103 "chrome.app.window.current().fullscreen();"));
2104 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2106 // Verify that the window cannot be toggled into fullscreen mode from within
2107 // Chrome (e.g., using keyboard accelerators).
2108 window->Fullscreen();
2109 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2111 #endif
2113 #if defined(OS_CHROMEOS)
2114 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2115 int screenshot_count = CountScreenshots();
2117 // Make sure screenshots are counted correctly.
2118 TestScreenshotFile(true);
2119 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2121 // Check if trying to take a screenshot fails when disabled by policy.
2122 TestScreenshotFile(false);
2123 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2126 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2127 // Set up the mock observer.
2128 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2129 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2130 audio_handler->AddAudioObserver(test_observer.get());
2132 bool prior_state = audio_handler->IsOutputMuted();
2133 // Make sure the audio is not muted and then toggle the policy and observe
2134 // if the output mute changed event is fired.
2135 audio_handler->SetOutputMute(false);
2136 EXPECT_FALSE(audio_handler->IsOutputMuted());
2137 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2138 PolicyMap policies;
2139 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2140 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
2141 UpdateProviderPolicy(policies);
2142 EXPECT_TRUE(audio_handler->IsOutputMuted());
2143 // This should not change the state now and should not trigger output mute
2144 // changed event.
2145 audio_handler->SetOutputMute(false);
2146 EXPECT_TRUE(audio_handler->IsOutputMuted());
2147 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2149 // Toggle back and observe if the output mute changed event is fired.
2150 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2151 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
2152 UpdateProviderPolicy(policies);
2153 EXPECT_FALSE(audio_handler->IsOutputMuted());
2154 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2155 audio_handler->SetOutputMute(true);
2156 EXPECT_TRUE(audio_handler->IsOutputMuted());
2157 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2158 // Revert the prior state.
2159 audio_handler->SetOutputMute(prior_state);
2160 audio_handler->RemoveAudioObserver(test_observer.get());
2163 // Disabled, see http://crbug.com/315308.
2164 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2165 // Indicate that the session started 2 hours ago and no user activity has
2166 // occurred yet.
2167 g_browser_process->local_state()->SetInt64(
2168 prefs::kSessionStartTime,
2169 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2170 .ToInternalValue());
2173 // Disabled, see http://crbug.com/315308.
2174 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2175 content::MockNotificationObserver observer;
2176 content::NotificationRegistrar registrar;
2177 registrar.Add(&observer,
2178 chrome::NOTIFICATION_APP_TERMINATING,
2179 content::NotificationService::AllSources());
2181 // Set the session length limit to 3 hours. Verify that the session is not
2182 // terminated.
2183 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2184 .Times(0);
2185 PolicyMap policies;
2186 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2187 POLICY_SCOPE_USER,
2188 base::Value::CreateIntegerValue(kThreeHoursInMs),
2189 NULL);
2190 UpdateProviderPolicy(policies);
2191 base::RunLoop().RunUntilIdle();
2192 Mock::VerifyAndClearExpectations(&observer);
2194 // Decrease the session length limit to 1 hour. Verify that the session is
2195 // terminated immediately.
2196 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2197 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2198 POLICY_SCOPE_USER,
2199 base::Value::CreateIntegerValue(kOneHourInMs),
2200 NULL);
2201 UpdateProviderPolicy(policies);
2202 base::RunLoop().RunUntilIdle();
2203 Mock::VerifyAndClearExpectations(&observer);
2206 // Disabled, see http://crbug.com/315308.
2207 IN_PROC_BROWSER_TEST_F(PolicyTest,
2208 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2209 // Indicate that the session started 2 hours ago and no user activity has
2210 // occurred yet.
2211 g_browser_process->local_state()->SetInt64(
2212 prefs::kSessionStartTime,
2213 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2214 .ToInternalValue());
2217 // Disabled, see http://crbug.com/315308.
2218 IN_PROC_BROWSER_TEST_F(PolicyTest,
2219 DISABLED_WaitForInitialUserActivityUsatisfied) {
2220 content::MockNotificationObserver observer;
2221 content::NotificationRegistrar registrar;
2222 registrar.Add(&observer,
2223 chrome::NOTIFICATION_APP_TERMINATING,
2224 content::NotificationService::AllSources());
2226 // Require initial user activity.
2227 PolicyMap policies;
2228 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2229 POLICY_SCOPE_USER,
2230 new base::FundamentalValue(true),
2231 NULL);
2232 UpdateProviderPolicy(policies);
2233 base::RunLoop().RunUntilIdle();
2235 // Set the session length limit to 1 hour. Verify that the session is not
2236 // terminated.
2237 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2238 .Times(0);
2239 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2240 POLICY_SCOPE_USER,
2241 base::Value::CreateIntegerValue(kOneHourInMs),
2242 NULL);
2243 UpdateProviderPolicy(policies);
2244 base::RunLoop().RunUntilIdle();
2245 Mock::VerifyAndClearExpectations(&observer);
2248 // Disabled, see http://crbug.com/315308.
2249 IN_PROC_BROWSER_TEST_F(PolicyTest,
2250 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2251 // Indicate that initial user activity in this session occurred 2 hours ago.
2252 g_browser_process->local_state()->SetInt64(
2253 prefs::kSessionStartTime,
2254 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2255 .ToInternalValue());
2256 g_browser_process->local_state()->SetBoolean(
2257 prefs::kSessionUserActivitySeen,
2258 true);
2261 // Disabled, see http://crbug.com/315308.
2262 IN_PROC_BROWSER_TEST_F(PolicyTest,
2263 DISABLED_WaitForInitialUserActivitySatisfied) {
2264 content::MockNotificationObserver observer;
2265 content::NotificationRegistrar registrar;
2266 registrar.Add(&observer,
2267 chrome::NOTIFICATION_APP_TERMINATING,
2268 content::NotificationService::AllSources());
2270 // Require initial user activity and set the session length limit to 3 hours.
2271 // Verify that the session is not terminated.
2272 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2273 .Times(0);
2274 PolicyMap policies;
2275 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2276 POLICY_SCOPE_USER,
2277 new base::FundamentalValue(true),
2278 NULL);
2279 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2280 POLICY_SCOPE_USER,
2281 base::Value::CreateIntegerValue(kThreeHoursInMs),
2282 NULL);
2283 UpdateProviderPolicy(policies);
2284 base::RunLoop().RunUntilIdle();
2285 Mock::VerifyAndClearExpectations(&observer);
2287 // Decrease the session length limit to 1 hour. Verify that the session is
2288 // terminated immediately.
2289 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2290 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2291 POLICY_SCOPE_USER,
2292 base::Value::CreateIntegerValue(kOneHourInMs),
2293 NULL);
2294 UpdateProviderPolicy(policies);
2295 base::RunLoop().RunUntilIdle();
2296 Mock::VerifyAndClearExpectations(&observer);
2299 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2300 // Verifies that the large cursor accessibility feature can be controlled
2301 // through policy.
2302 chromeos::AccessibilityManager* accessibility_manager =
2303 chromeos::AccessibilityManager::Get();
2305 // Manually enable the large cursor.
2306 accessibility_manager->EnableLargeCursor(true);
2307 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2309 // Verify that policy overrides the manual setting.
2310 PolicyMap policies;
2311 policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY,
2312 POLICY_SCOPE_USER,
2313 base::Value::CreateBooleanValue(false), NULL);
2314 UpdateProviderPolicy(policies);
2315 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2317 // Verify that the large cursor cannot be enabled manually anymore.
2318 accessibility_manager->EnableLargeCursor(true);
2319 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2322 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2323 // Verifies that the spoken feedback accessibility feature can be controlled
2324 // through policy.
2325 chromeos::AccessibilityManager* accessibility_manager =
2326 chromeos::AccessibilityManager::Get();
2328 // Manually enable spoken feedback.
2329 accessibility_manager->EnableSpokenFeedback(
2330 true, ash::A11Y_NOTIFICATION_NONE);
2331 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2333 // Verify that policy overrides the manual setting.
2334 PolicyMap policies;
2335 policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY,
2336 POLICY_SCOPE_USER,
2337 base::Value::CreateBooleanValue(false), NULL);
2338 UpdateProviderPolicy(policies);
2339 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2341 // Verify that spoken feedback cannot be enabled manually anymore.
2342 accessibility_manager->EnableSpokenFeedback(
2343 true, ash::A11Y_NOTIFICATION_NONE);
2344 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2347 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2348 // Verifies that the high contrast mode accessibility feature can be
2349 // controlled through policy.
2350 chromeos::AccessibilityManager* accessibility_manager =
2351 chromeos::AccessibilityManager::Get();
2353 // Manually enable high contrast mode.
2354 accessibility_manager->EnableHighContrast(true);
2355 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2357 // Verify that policy overrides the manual setting.
2358 PolicyMap policies;
2359 policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY,
2360 POLICY_SCOPE_USER,
2361 base::Value::CreateBooleanValue(false), NULL);
2362 UpdateProviderPolicy(policies);
2363 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2365 // Verify that high contrast mode cannot be enabled manually anymore.
2366 accessibility_manager->EnableHighContrast(true);
2367 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2370 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2371 // Verifies that the screen magnifier can be disabled through policy.
2372 chromeos::MagnificationManager* magnification_manager =
2373 chromeos::MagnificationManager::Get();
2375 // Manually enable the full-screen magnifier.
2376 magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL);
2377 magnification_manager->SetMagnifierEnabled(true);
2378 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2379 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2381 // Verify that policy overrides the manual setting.
2382 PolicyMap policies;
2383 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2384 POLICY_SCOPE_USER,
2385 base::Value::CreateIntegerValue(0), NULL);
2386 UpdateProviderPolicy(policies);
2387 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2389 // Verify that the screen magnifier cannot be enabled manually anymore.
2390 magnification_manager->SetMagnifierEnabled(true);
2391 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2394 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2395 // Verifies that the full-screen magnifier can be enabled through policy.
2396 chromeos::MagnificationManager* magnification_manager =
2397 chromeos::MagnificationManager::Get();
2399 // Verify that the screen magnifier is initially disabled.
2400 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2402 // Verify that policy can enable the full-screen magnifier.
2403 PolicyMap policies;
2404 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2405 POLICY_SCOPE_USER,
2406 base::Value::CreateIntegerValue(ash::MAGNIFIER_FULL), NULL);
2407 UpdateProviderPolicy(policies);
2408 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2409 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2411 // Verify that the screen magnifier cannot be disabled manually anymore.
2412 magnification_manager->SetMagnifierEnabled(false);
2413 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2416 #endif
2418 namespace {
2420 static const char* kRestoredURLs[] = {
2421 "http://aaa.com/empty.html",
2422 "http://bbb.com/empty.html",
2425 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2426 return s.empty() || s[0] != '-';
2429 } // namespace
2431 // Similar to PolicyTest but allows setting policies before the browser is
2432 // created. Each test parameter is a method that sets up the early policies
2433 // and stores the expected startup URLs in |expected_urls_|.
2434 class RestoreOnStartupPolicyTest
2435 : public PolicyTest,
2436 public testing::WithParamInterface<
2437 void (RestoreOnStartupPolicyTest::*)(void)> {
2438 public:
2439 RestoreOnStartupPolicyTest() {}
2440 virtual ~RestoreOnStartupPolicyTest() {}
2442 #if defined(OS_CHROMEOS)
2443 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2444 // TODO(nkostylev): Investigate if we can remove this switch.
2445 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2446 PolicyTest::SetUpCommandLine(command_line);
2448 #endif
2450 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2451 PolicyTest::SetUpInProcessBrowserTestFixture();
2452 // Set early policies now, before the browser is created.
2453 (this->*(GetParam()))();
2455 // Remove the non-switch arguments, so that session restore kicks in for
2456 // these tests.
2457 CommandLine* command_line = CommandLine::ForCurrentProcess();
2458 CommandLine::StringVector argv = command_line->argv();
2459 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2460 argv.end());
2461 command_line->InitFromArgv(argv);
2462 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2463 command_line->argv().begin()));
2465 // Redirect the test URLs to the test data directory.
2466 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs));
2469 void HomepageIsNotNTP() {
2470 // Verifies that policy can set the startup pages to the homepage, when
2471 // the homepage is not the NTP.
2472 PolicyMap policies;
2473 policies.Set(
2474 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2475 base::Value::CreateIntegerValue(
2476 SessionStartupPref::kPrefValueHomePage),
2477 NULL);
2478 policies.Set(
2479 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2480 base::Value::CreateBooleanValue(false), NULL);
2481 policies.Set(
2482 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2483 base::Value::CreateStringValue(kRestoredURLs[1]), NULL);
2484 provider_.UpdateChromePolicy(policies);
2486 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2489 void HomepageIsNTP() {
2490 // Verifies that policy can set the startup pages to the homepage, when
2491 // the homepage is the NTP.
2492 PolicyMap policies;
2493 policies.Set(
2494 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2495 base::Value::CreateIntegerValue(
2496 SessionStartupPref::kPrefValueHomePage),
2497 NULL);
2498 policies.Set(
2499 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2500 base::Value::CreateBooleanValue(true), NULL);
2501 provider_.UpdateChromePolicy(policies);
2503 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2506 void ListOfURLs() {
2507 // Verifies that policy can set the startup pages to a list of URLs.
2508 base::ListValue urls;
2509 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2510 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i]));
2511 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2513 PolicyMap policies;
2514 policies.Set(
2515 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2516 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs),
2517 NULL);
2518 policies.Set(
2519 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2520 urls.DeepCopy(), NULL);
2521 provider_.UpdateChromePolicy(policies);
2524 void NTP() {
2525 // Verifies that policy can set the startup page to the NTP.
2526 PolicyMap policies;
2527 policies.Set(
2528 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2529 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab),
2530 NULL);
2531 provider_.UpdateChromePolicy(policies);
2532 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2535 void Last() {
2536 // Verifies that policy can set the startup pages to the last session.
2537 PolicyMap policies;
2538 policies.Set(
2539 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2540 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast),
2541 NULL);
2542 provider_.UpdateChromePolicy(policies);
2543 // This should restore the tabs opened at PRE_RunTest below.
2544 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2545 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2548 std::vector<GURL> expected_urls_;
2551 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2552 // Open some tabs to verify if they are restored after the browser restarts.
2553 // Most policy settings override this, except kPrefValueLast which enforces
2554 // a restore.
2555 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2556 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2557 content::WindowedNotificationObserver observer(
2558 content::NOTIFICATION_LOAD_STOP,
2559 content::NotificationService::AllSources());
2560 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2561 content::PAGE_TRANSITION_LINK);
2562 observer.Wait();
2566 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2567 #if defined(OS_WIN) && defined(USE_ASH)
2568 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2569 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2570 return;
2571 #endif
2573 TabStripModel* model = browser()->tab_strip_model();
2574 int size = static_cast<int>(expected_urls_.size());
2575 EXPECT_EQ(size, model->count());
2576 for (int i = 0; i < size && i < model->count(); ++i) {
2577 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2581 INSTANTIATE_TEST_CASE_P(
2582 RestoreOnStartupPolicyTestInstance,
2583 RestoreOnStartupPolicyTest,
2584 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2585 &RestoreOnStartupPolicyTest::HomepageIsNTP,
2586 &RestoreOnStartupPolicyTest::ListOfURLs,
2587 &RestoreOnStartupPolicyTest::NTP,
2588 &RestoreOnStartupPolicyTest::Last));
2590 // Similar to PolicyTest but sets a couple of policies before the browser is
2591 // started.
2592 class PolicyStatisticsCollectorTest : public PolicyTest {
2593 public:
2594 PolicyStatisticsCollectorTest() {}
2595 virtual ~PolicyStatisticsCollectorTest() {}
2597 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2598 PolicyTest::SetUpInProcessBrowserTestFixture();
2599 PolicyMap policies;
2600 policies.Set(
2601 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2602 base::Value::CreateBooleanValue(true), NULL);
2603 policies.Set(
2604 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2605 base::Value::CreateBooleanValue(false), NULL);
2606 policies.Set(
2607 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2608 base::Value::CreateStringValue("http://chromium.org"), NULL);
2609 provider_.UpdateChromePolicy(policies);
2613 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2614 // Verifies that policy usage histograms are collected at startup.
2616 // BrowserPolicyConnector::Init() has already been called. Make sure the
2617 // CompleteInitialization() task has executed as well.
2618 content::RunAllPendingInMessageLoop();
2620 GURL kAboutHistograms = GURL(std::string(chrome::kAboutScheme) +
2621 std::string(content::kStandardSchemeSeparator) +
2622 std::string(content::kChromeUIHistogramHost));
2623 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
2624 content::WebContents* contents =
2625 browser()->tab_strip_model()->GetActiveWebContents();
2626 std::string text;
2627 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2628 contents,
2629 "var nodes = document.querySelectorAll('body > pre');"
2630 "var result = '';"
2631 "for (var i = 0; i < nodes.length; ++i) {"
2632 " var text = nodes[i].innerHTML;"
2633 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
2634 " result = text;"
2635 " break;"
2636 " }"
2638 "domAutomationController.send(result);",
2639 &text));
2640 ASSERT_FALSE(text.empty());
2641 const std::string kExpectedLabel =
2642 "Histogram: Enterprise.Policies recorded 3 samples";
2643 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
2644 // HomepageLocation has policy ID 1.
2645 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
2646 // ShowHomeButton has policy ID 35.
2647 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
2648 // BookmarkBarEnabled has policy ID 82.
2649 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
2652 class MediaStreamDevicesControllerBrowserTest
2653 : public PolicyTest,
2654 public testing::WithParamInterface<bool> {
2655 public:
2656 MediaStreamDevicesControllerBrowserTest()
2657 : request_url_allowed_via_whitelist_(false) {
2658 policy_value_ = GetParam();
2660 virtual ~MediaStreamDevicesControllerBrowserTest() {}
2662 // Configure a given policy map.
2663 // The |policy_name| is the name of either the audio or video capture allow
2664 // policy and must never be NULL.
2665 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
2666 // policy is set. If non-NULL, the request_url_ will be set to be non empty
2667 // and the whitelist policy is set to contain either the |allow_rule| (if
2668 // non-NULL) or an "allow all" wildcard.
2669 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
2670 const char* whitelist_policy,
2671 const char* allow_rule) {
2672 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2673 base::Value::CreateBooleanValue(policy_value_), NULL);
2675 if (whitelist_policy) {
2676 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
2677 // in the media exceptions UI.
2678 // See discussion here: https://codereview.chromium.org/15738004/
2679 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
2681 // Add an entry to the whitelist that allows the specified URL regardless
2682 // of the setting of kAudioCapturedAllowed.
2683 request_url_ = GURL("http://www.example.com/foo");
2684 base::ListValue* list = new base::ListValue();
2685 if (allow_rule) {
2686 list->AppendString(allow_rule);
2687 request_url_allowed_via_whitelist_ = true;
2688 } else {
2689 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
2690 // We should ignore all wildcard entries in the whitelist, so even
2691 // though we've added an entry, it should be ignored and our expectation
2692 // is that the request has not been allowed via the whitelist.
2693 request_url_allowed_via_whitelist_ = false;
2695 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
2696 POLICY_SCOPE_USER, list, NULL);
2700 void Accept(const content::MediaStreamDevices& devices,
2701 scoped_ptr<content::MediaStreamUI> ui) {
2702 if (policy_value_ || request_url_allowed_via_whitelist_) {
2703 ASSERT_EQ(1U, devices.size());
2704 ASSERT_EQ("fake_dev", devices[0].id);
2705 } else {
2706 ASSERT_EQ(0U, devices.size());
2710 void FinishAudioTest() {
2711 content::MediaStreamRequest request(0, 0, 0,
2712 request_url_.GetOrigin(),
2713 content::MEDIA_DEVICE_ACCESS,
2714 std::string(), std::string(),
2715 content::MEDIA_DEVICE_AUDIO_CAPTURE,
2716 content::MEDIA_NO_SERVICE);
2717 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2718 // and microphone permissions at the same time.
2719 MediaStreamDevicesController controller(
2720 browser()->tab_strip_model()->GetActiveWebContents(), request,
2721 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2722 controller.Accept(false);
2724 base::MessageLoop::current()->QuitWhenIdle();
2727 void FinishVideoTest() {
2728 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2729 // and microphone permissions at the same time.
2730 content::MediaStreamRequest request(0, 0, 0,
2731 request_url_.GetOrigin(),
2732 content::MEDIA_DEVICE_ACCESS,
2733 std::string(),
2734 std::string(),
2735 content::MEDIA_NO_SERVICE,
2736 content::MEDIA_DEVICE_VIDEO_CAPTURE);
2737 MediaStreamDevicesController controller(
2738 browser()->tab_strip_model()->GetActiveWebContents(), request,
2739 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2740 controller.Accept(false);
2742 base::MessageLoop::current()->QuitWhenIdle();
2745 bool policy_value_;
2746 bool request_url_allowed_via_whitelist_;
2747 GURL request_url_;
2748 static const char kExampleRequestPattern[];
2751 // static
2752 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
2753 "http://[*.]example.com/";
2755 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2756 AudioCaptureAllowed) {
2757 content::MediaStreamDevices audio_devices;
2758 content::MediaStreamDevice fake_audio_device(
2759 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2760 audio_devices.push_back(fake_audio_device);
2762 PolicyMap policies;
2763 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
2764 UpdateProviderPolicy(policies);
2766 content::BrowserThread::PostTaskAndReply(
2767 content::BrowserThread::IO, FROM_HERE,
2768 base::Bind(&MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2769 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2770 audio_devices),
2771 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2772 this));
2774 base::MessageLoop::current()->Run();
2777 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2778 AudioCaptureAllowedUrls) {
2779 content::MediaStreamDevices audio_devices;
2780 content::MediaStreamDevice fake_audio_device(
2781 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2782 audio_devices.push_back(fake_audio_device);
2784 const char* allow_pattern[] = {
2785 kExampleRequestPattern,
2786 // This will set an allow-all policy whitelist. Since we do not allow
2787 // setting an allow-all entry in the whitelist, this entry should be ignored
2788 // and therefore the request should be denied.
2789 NULL,
2792 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2793 PolicyMap policies;
2794 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
2795 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
2796 UpdateProviderPolicy(policies);
2798 content::BrowserThread::PostTaskAndReply(
2799 content::BrowserThread::IO, FROM_HERE,
2800 base::Bind(
2801 &MediaCaptureDevicesDispatcher::OnAudioCaptureDevicesChanged,
2802 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2803 audio_devices),
2804 base::Bind(
2805 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2806 this));
2808 base::MessageLoop::current()->Run();
2812 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2813 VideoCaptureAllowed) {
2814 content::MediaStreamDevices video_devices;
2815 content::MediaStreamDevice fake_video_device(
2816 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2817 video_devices.push_back(fake_video_device);
2819 PolicyMap policies;
2820 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
2821 UpdateProviderPolicy(policies);
2823 content::BrowserThread::PostTaskAndReply(
2824 content::BrowserThread::IO, FROM_HERE,
2825 base::Bind(&MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2826 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2827 video_devices),
2828 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2829 this));
2831 base::MessageLoop::current()->Run();
2834 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2835 VideoCaptureAllowedUrls) {
2836 content::MediaStreamDevices video_devices;
2837 content::MediaStreamDevice fake_video_device(
2838 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2839 video_devices.push_back(fake_video_device);
2841 const char* allow_pattern[] = {
2842 kExampleRequestPattern,
2843 // This will set an allow-all policy whitelist. Since we do not allow
2844 // setting an allow-all entry in the whitelist, this entry should be ignored
2845 // and therefore the request should be denied.
2846 NULL,
2849 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2850 PolicyMap policies;
2851 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
2852 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
2853 UpdateProviderPolicy(policies);
2855 content::BrowserThread::PostTaskAndReply(
2856 content::BrowserThread::IO, FROM_HERE,
2857 base::Bind(
2858 &MediaCaptureDevicesDispatcher::OnVideoCaptureDevicesChanged,
2859 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2860 video_devices),
2861 base::Bind(
2862 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2863 this));
2865 base::MessageLoop::current()->Run();
2869 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
2870 MediaStreamDevicesControllerBrowserTest,
2871 testing::Bool());
2873 #if !defined(OS_CHROMEOS)
2874 // Similar to PolicyTest but sets the proper policy before the browser is
2875 // started.
2876 class PolicyVariationsServiceTest : public PolicyTest {
2877 public:
2878 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2879 PolicyTest::SetUpInProcessBrowserTestFixture();
2880 PolicyMap policies;
2881 policies.Set(
2882 key::kVariationsRestrictParameter,
2883 POLICY_LEVEL_MANDATORY,
2884 POLICY_SCOPE_USER,
2885 base::Value::CreateStringValue("restricted"),
2886 NULL);
2887 provider_.UpdateChromePolicy(policies);
2891 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
2892 const std::string default_variations_url =
2893 chrome_variations::VariationsService::
2894 GetDefaultVariationsServerURLForTesting();
2896 const GURL url =
2897 chrome_variations::VariationsService::GetVariationsServerURL(
2898 g_browser_process->local_state());
2899 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
2900 std::string value;
2901 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
2902 EXPECT_EQ("restricted", value);
2905 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
2906 base::ListValue blacklist;
2907 blacklist.Append(base::Value::CreateStringValue("host.name"));
2908 PolicyMap policies;
2909 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2910 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2911 UpdateProviderPolicy(policies);
2913 PrefService* prefs = browser()->profile()->GetPrefs();
2914 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2915 prefs, "host.name"));
2916 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2917 prefs, "other.host.name"));
2920 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
2921 base::ListValue blacklist;
2922 blacklist.Append(base::Value::CreateStringValue("*"));
2923 PolicyMap policies;
2924 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2925 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2926 UpdateProviderPolicy(policies);
2928 PrefService* prefs = browser()->profile()->GetPrefs();
2929 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2930 prefs, "host.name"));
2931 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2932 prefs, "other.host.name"));
2935 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
2936 base::ListValue blacklist;
2937 blacklist.Append(base::Value::CreateStringValue("*"));
2938 base::ListValue whitelist;
2939 whitelist.Append(base::Value::CreateStringValue("host.name"));
2940 PolicyMap policies;
2941 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2942 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2943 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
2944 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2945 UpdateProviderPolicy(policies);
2947 PrefService* prefs = browser()->profile()->GetPrefs();
2948 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2949 prefs, "host.name"));
2950 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2951 prefs, "other.host.name"));
2954 #endif // !defined(CHROME_OS)
2956 } // namespace policy