Adding instrumentation to locate the source of jankiness
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blobb4332684629f60cf9801475df59860c789f516d0
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <algorithm>
6 #include <string>
7 #include <vector>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/test/test_file_util.h"
26 #include "base/threading/sequenced_worker_pool.h"
27 #include "base/time/time.h"
28 #include "base/values.h"
29 #include "chrome/app/chrome_command_ids.h"
30 #include "chrome/browser/autocomplete/autocomplete_controller.h"
31 #include "chrome/browser/background/background_contents_service.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
35 #include "chrome/browser/devtools/devtools_window_testing.h"
36 #include "chrome/browser/download/download_prefs.h"
37 #include "chrome/browser/extensions/api/messaging/message_service.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/extension_management_constants.h"
40 #include "chrome/browser/extensions/extension_service.h"
41 #include "chrome/browser/extensions/unpacked_installer.h"
42 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
43 #include "chrome/browser/extensions/updater/extension_updater.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/prediction_options.h"
49 #include "chrome/browser/net/ssl_config_service_manager.h"
50 #include "chrome/browser/net/url_request_mock_util.h"
51 #include "chrome/browser/plugins/plugin_prefs.h"
52 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
53 #include "chrome/browser/policy/profile_policy_connector.h"
54 #include "chrome/browser/policy/profile_policy_connector_factory.h"
55 #include "chrome/browser/prefs/session_startup_pref.h"
56 #include "chrome/browser/profiles/profile.h"
57 #include "chrome/browser/search/instant_service.h"
58 #include "chrome/browser/search/instant_service_factory.h"
59 #include "chrome/browser/search/search.h"
60 #include "chrome/browser/search_engines/template_url_service_factory.h"
61 #include "chrome/browser/translate/chrome_translate_client.h"
62 #include "chrome/browser/translate/cld_data_harness.h"
63 #include "chrome/browser/translate/translate_service.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/location_bar/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/extensions/extension_constants.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/grit/generated_resources.h"
81 #include "chrome/test/base/in_process_browser_test.h"
82 #include "chrome/test/base/test_switches.h"
83 #include "chrome/test/base/ui_test_utils.h"
84 #include "components/content_settings/core/common/content_settings.h"
85 #include "components/content_settings/core/common/content_settings_pattern.h"
86 #include "components/infobars/core/infobar.h"
87 #include "components/policy/core/browser/browser_policy_connector.h"
88 #include "components/policy/core/common/external_data_fetcher.h"
89 #include "components/policy/core/common/mock_configuration_policy_provider.h"
90 #include "components/policy/core/common/policy_map.h"
91 #include "components/policy/core/common/policy_pref_names.h"
92 #include "components/policy/core/common/policy_service.h"
93 #include "components/policy/core/common/policy_service_impl.h"
94 #include "components/search_engines/template_url.h"
95 #include "components/search_engines/template_url_service.h"
96 #include "components/translate/core/browser/language_state.h"
97 #include "components/translate/core/browser/translate_infobar_delegate.h"
98 #include "content/public/browser/browser_child_process_host_iterator.h"
99 #include "content/public/browser/browser_context.h"
100 #include "content/public/browser/browser_thread.h"
101 #include "content/public/browser/child_process_data.h"
102 #include "content/public/browser/download_item.h"
103 #include "content/public/browser/download_manager.h"
104 #include "content/public/browser/gpu_data_manager.h"
105 #include "content/public/browser/notification_details.h"
106 #include "content/public/browser/notification_observer.h"
107 #include "content/public/browser/notification_registrar.h"
108 #include "content/public/browser/notification_service.h"
109 #include "content/public/browser/notification_source.h"
110 #include "content/public/browser/notification_types.h"
111 #include "content/public/browser/plugin_service.h"
112 #include "content/public/browser/render_process_host.h"
113 #include "content/public/browser/render_view_host.h"
114 #include "content/public/browser/web_contents.h"
115 #include "content/public/common/content_constants.h"
116 #include "content/public/common/content_paths.h"
117 #include "content/public/common/process_type.h"
118 #include "content/public/common/result_codes.h"
119 #include "content/public/common/url_constants.h"
120 #include "content/public/common/webplugininfo.h"
121 #include "content/public/test/browser_test_utils.h"
122 #include "content/public/test/download_test_observer.h"
123 #include "content/public/test/mock_notification_observer.h"
124 #include "content/public/test/test_navigation_observer.h"
125 #include "content/public/test/test_utils.h"
126 #include "extensions/browser/extension_host.h"
127 #include "extensions/browser/extension_system.h"
128 #include "extensions/browser/process_manager.h"
129 #include "extensions/browser/uninstall_reason.h"
130 #include "extensions/common/constants.h"
131 #include "extensions/common/extension.h"
132 #include "extensions/common/extension_set.h"
133 #include "net/base/net_errors.h"
134 #include "net/base/net_util.h"
135 #include "net/base/url_util.h"
136 #include "net/http/http_stream_factory.h"
137 #include "net/ssl/ssl_config.h"
138 #include "net/ssl/ssl_config_service.h"
139 #include "net/test/url_request/url_request_failed_job.h"
140 #include "net/test/url_request/url_request_mock_http_job.h"
141 #include "net/url_request/url_request.h"
142 #include "net/url_request/url_request_filter.h"
143 #include "policy/policy_constants.h"
144 #include "testing/gmock/include/gmock/gmock.h"
145 #include "testing/gtest/include/gtest/gtest.h"
146 #include "third_party/WebKit/public/web/WebInputEvent.h"
147 #include "ui/base/l10n/l10n_util.h"
148 #include "ui/base/page_transition_types.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "url/gurl.h"
152 #if defined(OS_CHROMEOS)
153 #include "ash/accelerators/accelerator_controller.h"
154 #include "ash/accelerators/accelerator_table.h"
155 #include "ash/magnifier/magnifier_constants.h"
156 #include "ash/shell.h"
157 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
158 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
159 #include "chrome/browser/profiles/profile_manager.h"
160 #include "chrome/browser/ui/ash/screenshot_taker.h"
161 #include "chromeos/audio/cras_audio_handler.h"
162 #include "ui/keyboard/keyboard_util.h"
163 #endif
165 #if !defined(OS_MACOSX)
166 #include "base/basictypes.h"
167 #include "base/compiler_specific.h"
168 #include "chrome/browser/ui/extensions/application_launch.h"
169 #include "extensions/browser/app_window/app_window.h"
170 #include "extensions/browser/app_window/app_window_registry.h"
171 #include "extensions/browser/app_window/native_app_window.h"
172 #include "ui/base/window_open_disposition.h"
173 #endif
175 using content::BrowserThread;
176 using net::URLRequestMockHTTPJob;
177 using testing::Mock;
178 using testing::Return;
179 using testing::_;
181 namespace policy {
183 namespace {
185 #if defined(OS_CHROMEOS)
186 const int kOneHourInMs = 60 * 60 * 1000;
187 const int kThreeHoursInMs = 180 * 60 * 1000;
188 #endif
190 const char kURL[] = "http://example.com";
191 const char kCookieValue[] = "converted=true";
192 // Assigned to Philip J. Fry to fix eventually.
193 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
195 const base::FilePath::CharType kTestExtensionsDir[] =
196 FILE_PATH_LITERAL("extensions");
197 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
198 const base::FilePath::CharType kAdBlockCrxName[] =
199 FILE_PATH_LITERAL("adblock.crx");
200 const base::FilePath::CharType kHostedAppCrxName[] =
201 FILE_PATH_LITERAL("hosted_app.crx");
203 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
204 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
205 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
207 const base::FilePath::CharType kGood2CrxManifestName[] =
208 FILE_PATH_LITERAL("good2_update_manifest.xml");
209 const base::FilePath::CharType kGoodV1CrxManifestName[] =
210 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
211 const base::FilePath::CharType kGoodUnpackedExt[] =
212 FILE_PATH_LITERAL("good_unpacked");
213 const base::FilePath::CharType kAppUnpackedExt[] =
214 FILE_PATH_LITERAL("app");
216 #if !defined(OS_MACOSX)
217 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
218 FILE_PATH_LITERAL("fullscreen_app");
219 #endif // !defined(OS_MACOSX)
221 // Filters requests to the hosts in |urls| and redirects them to the test data
222 // dir through URLRequestMockHTTPJobs.
223 void RedirectHostsToTestData(const char* const urls[], size_t size) {
224 // Map the given hosts to the test data dir.
225 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
226 base::FilePath base_path;
227 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
228 for (size_t i = 0; i < size; ++i) {
229 const GURL url(urls[i]);
230 EXPECT_TRUE(url.is_valid());
231 filter->AddUrlInterceptor(url,
232 URLRequestMockHTTPJob::CreateInterceptor(
233 base_path, BrowserThread::GetBlockingPool()));
237 // Remove filters for requests to the hosts in |urls|.
238 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
239 // Map the given hosts to the test data dir.
240 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
241 for (size_t i = 0; i < size; ++i) {
242 const GURL url(urls[i]);
243 EXPECT_TRUE(url.is_valid());
244 filter->RemoveUrlHandler(url);
248 // Fails requests using ERR_CONNECTION_RESET.
249 net::URLRequestJob* FailedJobFactory(
250 net::URLRequest* request,
251 net::NetworkDelegate* network_delegate,
252 const std::string& scheme) {
253 return new net::URLRequestFailedJob(
254 request, network_delegate, net::ERR_CONNECTION_RESET);
257 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
258 class MakeRequestFail {
259 public:
260 // Sets up the filter on IO thread such that requests to |host| fail.
261 explicit MakeRequestFail(const std::string& host) : host_(host) {
262 BrowserThread::PostTaskAndReply(
263 BrowserThread::IO, FROM_HERE,
264 base::Bind(MakeRequestFailOnIO, host_),
265 base::MessageLoop::QuitClosure());
266 content::RunMessageLoop();
268 ~MakeRequestFail() {
269 BrowserThread::PostTaskAndReply(
270 BrowserThread::IO, FROM_HERE,
271 base::Bind(UndoMakeRequestFailOnIO, host_),
272 base::MessageLoop::QuitClosure());
273 content::RunMessageLoop();
276 private:
277 // Filters requests to the |host| such that they fail. Run on IO thread.
278 static void MakeRequestFailOnIO(const std::string& host) {
279 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
280 filter->AddHostnameHandler("http", host, &FailedJobFactory);
281 filter->AddHostnameHandler("https", host, &FailedJobFactory);
284 // Remove filters for requests to the |host|. Run on IO thread.
285 static void UndoMakeRequestFailOnIO(const std::string& host) {
286 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
287 filter->RemoveHostnameHandler("http", host);
288 filter->RemoveHostnameHandler("https", host);
291 const std::string host_;
294 // Verifies that the given url |spec| can be opened. This assumes that |spec|
295 // points at empty.html in the test data dir.
296 void CheckCanOpenURL(Browser* browser, const char* spec) {
297 GURL url(spec);
298 ui_test_utils::NavigateToURL(browser, url);
299 content::WebContents* contents =
300 browser->tab_strip_model()->GetActiveWebContents();
301 EXPECT_EQ(url, contents->GetURL());
302 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
303 base::string16 title =
304 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
305 EXPECT_NE(title, contents->GetTitle());
308 // Verifies that access to the given url |spec| is blocked.
309 void CheckURLIsBlocked(Browser* browser, const char* spec) {
310 GURL url(spec);
311 ui_test_utils::NavigateToURL(browser, url);
312 content::WebContents* contents =
313 browser->tab_strip_model()->GetActiveWebContents();
314 EXPECT_EQ(url, contents->GetURL());
315 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
316 base::string16 title =
317 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
318 EXPECT_EQ(title, contents->GetTitle());
320 // Verify that the expected error page is being displayed.
321 bool result = false;
322 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
323 contents,
324 "var textContent = document.body.textContent;"
325 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
326 "domAutomationController.send(hasError);",
327 &result));
328 EXPECT_TRUE(result);
331 // Downloads a file named |file| and expects it to be saved to |dir|, which
332 // must be empty.
333 void DownloadAndVerifyFile(
334 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
335 content::DownloadManager* download_manager =
336 content::BrowserContext::GetDownloadManager(browser->profile());
337 content::DownloadTestObserverTerminal observer(
338 download_manager, 1,
339 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
340 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
341 base::FilePath downloaded = dir.Append(file);
342 EXPECT_FALSE(base::PathExists(downloaded));
343 ui_test_utils::NavigateToURLWithDisposition(
344 browser, url, CURRENT_TAB,
345 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
346 observer.WaitForFinished();
347 EXPECT_EQ(
348 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
349 EXPECT_TRUE(base::PathExists(downloaded));
350 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
351 EXPECT_EQ(file, enumerator.Next().BaseName());
352 EXPECT_EQ(base::FilePath(), enumerator.Next());
355 #if defined(OS_CHROMEOS)
356 int CountScreenshots() {
357 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
358 ProfileManager::GetActiveUserProfile());
359 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
360 false, base::FileEnumerator::FILES,
361 "Screenshot*");
362 int count = 0;
363 while (!enumerator.Next().empty())
364 count++;
365 return count;
367 #endif
369 // Checks if WebGL is enabled in the given WebContents.
370 bool IsWebGLEnabled(content::WebContents* contents) {
371 bool result = false;
372 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
373 contents,
374 "var canvas = document.createElement('canvas');"
375 "var context = canvas.getContext('webgl');"
376 "domAutomationController.send(context != null);",
377 &result));
378 return result;
381 bool IsJavascriptEnabled(content::WebContents* contents) {
382 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
383 contents->GetMainFrame(), "123");
384 int result = 0;
385 if (!value->GetAsInteger(&result))
386 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
387 return result == 123;
390 bool IsNetworkPredictionEnabled(PrefService* prefs) {
391 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs);
394 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
395 const std::vector<content::WebPluginInfo>& in) {
396 *out = in;
397 base::MessageLoop::current()->QuitWhenIdle();
400 template<typename T>
401 void CopyValueAndQuit(T* out, T in) {
402 *out = in;
403 base::MessageLoop::current()->QuitWhenIdle();
406 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
407 content::PluginService* service = content::PluginService::GetInstance();
408 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
409 content::RunMessageLoop();
412 const content::WebPluginInfo* GetFlashPlugin(
413 const std::vector<content::WebPluginInfo>& plugins) {
414 const content::WebPluginInfo* flash = NULL;
415 for (size_t i = 0; i < plugins.size(); ++i) {
416 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
417 flash = &plugins[i];
418 break;
421 #if defined(OFFICIAL_BUILD)
422 // Official builds bundle Flash.
423 EXPECT_TRUE(flash);
424 #else
425 if (!flash)
426 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
427 #endif
428 return flash;
431 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
432 const content::WebPluginInfo* plugin,
433 bool enabled) {
434 bool ok = false;
435 plugin_prefs->EnablePlugin(enabled, plugin->path,
436 base::Bind(CopyValueAndQuit<bool>, &ok));
437 content::RunMessageLoop();
438 return ok;
441 int CountPluginsOnIOThread() {
442 int count = 0;
443 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
444 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
445 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
446 count++;
449 return count;
452 int CountPlugins() {
453 int count = -1;
454 BrowserThread::PostTaskAndReplyWithResult(
455 BrowserThread::IO, FROM_HERE,
456 base::Bind(CountPluginsOnIOThread),
457 base::Bind(CopyValueAndQuit<int>, &count));
458 content::RunMessageLoop();
459 EXPECT_GE(count, 0);
460 return count;
463 void FlushBlacklistPolicy() {
464 // Updates of the URLBlacklist are done on IO, after building the blacklist
465 // on the blocking pool, which is initiated from IO.
466 content::RunAllPendingInMessageLoop(BrowserThread::IO);
467 BrowserThread::GetBlockingPool()->FlushForTesting();
468 content::RunAllPendingInMessageLoop(BrowserThread::IO);
471 bool ContainsVisibleElement(content::WebContents* contents,
472 const std::string& id) {
473 bool result;
474 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
475 contents,
476 "var elem = document.getElementById('" + id + "');"
477 "domAutomationController.send(!!elem && !elem.hidden);",
478 &result));
479 return result;
482 #if defined(OS_CHROMEOS)
483 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
484 public:
485 TestAudioObserver() : output_mute_changed_count_(0) {
488 int output_mute_changed_count() const {
489 return output_mute_changed_count_;
492 virtual ~TestAudioObserver() {}
494 protected:
495 // chromeos::CrasAudioHandler::AudioObserver overrides.
496 virtual void OnOutputMuteChanged() override {
497 ++output_mute_changed_count_;
500 private:
501 int output_mute_changed_count_;
503 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
505 #endif
507 // This class waits until either a load stops or the WebContents is destroyed.
508 class WebContentsLoadedOrDestroyedWatcher
509 : public content::WebContentsObserver {
510 public:
511 explicit WebContentsLoadedOrDestroyedWatcher(
512 content::WebContents* web_contents);
513 virtual ~WebContentsLoadedOrDestroyedWatcher();
515 // Waits until the WebContents's load is done or until it is destroyed.
516 void Wait();
518 // Overridden WebContentsObserver methods.
519 virtual void WebContentsDestroyed() override;
520 virtual void DidStopLoading(
521 content::RenderViewHost* render_view_host) override;
523 private:
524 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
526 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
529 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
530 content::WebContents* web_contents)
531 : content::WebContentsObserver(web_contents),
532 message_loop_runner_(new content::MessageLoopRunner) {
535 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
537 void WebContentsLoadedOrDestroyedWatcher::Wait() {
538 message_loop_runner_->Run();
541 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
542 message_loop_runner_->Quit();
545 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
546 content::RenderViewHost* render_view_host) {
547 message_loop_runner_->Quit();
550 #if !defined(OS_MACOSX)
552 // Observer used to wait for the creation of a new app window.
553 class TestAddAppWindowObserver
554 : public extensions::AppWindowRegistry::Observer {
555 public:
556 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
557 virtual ~TestAddAppWindowObserver();
559 // extensions::AppWindowRegistry::Observer:
560 virtual void OnAppWindowAdded(extensions::AppWindow* app_window) override;
562 extensions::AppWindow* WaitForAppWindow();
564 private:
565 extensions::AppWindowRegistry* registry_; // Not owned.
566 extensions::AppWindow* window_; // Not owned.
567 base::RunLoop run_loop_;
569 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
572 TestAddAppWindowObserver::TestAddAppWindowObserver(
573 extensions::AppWindowRegistry* registry)
574 : registry_(registry), window_(NULL) {
575 registry_->AddObserver(this);
578 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
579 registry_->RemoveObserver(this);
582 void TestAddAppWindowObserver::OnAppWindowAdded(
583 extensions::AppWindow* app_window) {
584 window_ = app_window;
585 run_loop_.Quit();
588 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
589 run_loop_.Run();
590 return window_;
593 #endif
595 } // namespace
597 class PolicyTest : public InProcessBrowserTest {
598 protected:
599 PolicyTest() {}
600 virtual ~PolicyTest() {}
602 virtual void SetUp() override {
603 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
604 InProcessBrowserTest::SetUp();
607 virtual void SetUpInProcessBrowserTestFixture() override {
608 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
609 EXPECT_CALL(provider_, IsInitializationComplete(_))
610 .WillRepeatedly(Return(true));
611 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
614 virtual void SetUpOnMainThread() override {
615 BrowserThread::PostTask(
616 BrowserThread::IO, FROM_HERE,
617 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
618 if (extension_service()->updater()) {
619 extension_service()->updater()->SetExtensionCacheForTesting(
620 test_extension_cache_.get());
624 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
625 // instead of chrome::DIR_TEST_DATA.
626 void ServeContentTestData() {
627 base::FilePath root_http;
628 PathService::Get(content::DIR_TEST_DATA, &root_http);
629 BrowserThread::PostTaskAndReply(
630 BrowserThread::IO,
631 FROM_HERE,
632 base::Bind(URLRequestMockHTTPJob::AddUrlHandler,
633 root_http,
634 make_scoped_refptr(BrowserThread::GetBlockingPool())),
635 base::MessageLoop::current()->QuitWhenIdleClosure());
636 content::RunMessageLoop();
639 void SetScreenshotPolicy(bool enabled) {
640 PolicyMap policies;
641 policies.Set(key::kDisableScreenshots,
642 POLICY_LEVEL_MANDATORY,
643 POLICY_SCOPE_USER,
644 new base::FundamentalValue(!enabled),
645 NULL);
646 UpdateProviderPolicy(policies);
649 #if defined(OS_CHROMEOS)
650 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
651 public:
652 virtual void OnScreenshotCompleted(
653 ScreenshotTakerObserver::Result screenshot_result,
654 const base::FilePath& screenshot_path) override {
655 BrowserThread::PostTaskAndReply(BrowserThread::IO,
656 FROM_HERE,
657 base::Bind(base::DoNothing),
658 base::MessageLoop::QuitClosure());
661 virtual ~QuitMessageLoopAfterScreenshot() {}
664 void TestScreenshotFile(bool enabled) {
665 // AddObserver is an ash-specific method, so just replace the screenshot
666 // taker with one we've created here.
667 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
668 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
669 // is tied to the test instead.
670 screenshot_taker->AddObserver(&observer_);
671 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
672 screenshot_taker.Pass());
674 SetScreenshotPolicy(enabled);
675 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
676 ash::TAKE_SCREENSHOT, ui::Accelerator());
678 content::RunMessageLoop();
680 #endif
682 ExtensionService* extension_service() {
683 extensions::ExtensionSystem* system =
684 extensions::ExtensionSystem::Get(browser()->profile());
685 return system->extension_service();
688 const extensions::Extension* InstallExtension(
689 const base::FilePath::StringType& name) {
690 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
691 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
692 scoped_refptr<extensions::CrxInstaller> installer =
693 extensions::CrxInstaller::CreateSilent(extension_service());
694 installer->set_allow_silent_install(true);
695 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
696 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
698 content::WindowedNotificationObserver observer(
699 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
700 content::NotificationService::AllSources());
701 installer->InstallCrx(extension_path);
702 observer.Wait();
703 content::Details<const extensions::Extension> details = observer.details();
704 return details.ptr();
707 const extensions::Extension* LoadUnpackedExtension(
708 const base::FilePath::StringType& name, bool expect_success) {
709 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
710 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
711 scoped_refptr<extensions::UnpackedInstaller> installer =
712 extensions::UnpackedInstaller::Create(extension_service());
713 content::WindowedNotificationObserver observer(
714 expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
715 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
716 content::NotificationService::AllSources());
717 installer->Load(extension_path);
718 observer.Wait();
720 const extensions::ExtensionSet* extensions =
721 extension_service()->extensions();
722 for (extensions::ExtensionSet::const_iterator it = extensions->begin();
723 it != extensions->end(); ++it) {
724 if ((*it)->path() == extension_path)
725 return it->get();
727 return NULL;
730 void UninstallExtension(const std::string& id, bool expect_success) {
731 content::WindowedNotificationObserver observer(
732 expect_success
733 ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
734 : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
735 content::NotificationService::AllSources());
736 extension_service()->UninstallExtension(
738 extensions::UNINSTALL_REASON_FOR_TESTING,
739 base::Bind(&base::DoNothing),
740 NULL);
741 observer.Wait();
744 void DisableExtension(const std::string& id) {
745 content::WindowedNotificationObserver observer(
746 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
747 content::NotificationService::AllSources());
748 extension_service()->DisableExtension(id,
749 extensions::Extension::DISABLE_NONE);
750 observer.Wait();
753 void UpdateProviderPolicy(const PolicyMap& policy) {
754 provider_.UpdateChromePolicy(policy);
755 DCHECK(base::MessageLoop::current());
756 base::RunLoop loop;
757 loop.RunUntilIdle();
760 // Sends a mouse click at the given coordinates to the current renderer.
761 void PerformClick(int x, int y) {
762 content::WebContents* contents =
763 browser()->tab_strip_model()->GetActiveWebContents();
764 blink::WebMouseEvent click_event;
765 click_event.type = blink::WebInputEvent::MouseDown;
766 click_event.button = blink::WebMouseEvent::ButtonLeft;
767 click_event.clickCount = 1;
768 click_event.x = x;
769 click_event.y = y;
770 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
771 click_event.type = blink::WebInputEvent::MouseUp;
772 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
775 MockConfigurationPolicyProvider provider_;
776 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
777 #if defined(OS_CHROMEOS)
778 QuitMessageLoopAfterScreenshot observer_;
779 #endif
782 #if defined(OS_WIN)
783 // This policy only exists on Windows.
785 // Sets the locale policy before the browser is started.
786 class LocalePolicyTest : public PolicyTest {
787 public:
788 LocalePolicyTest() {}
789 virtual ~LocalePolicyTest() {}
791 virtual void SetUpInProcessBrowserTestFixture() override {
792 PolicyTest::SetUpInProcessBrowserTestFixture();
793 PolicyMap policies;
794 policies.Set(key::kApplicationLocaleValue,
795 POLICY_LEVEL_MANDATORY,
796 POLICY_SCOPE_USER,
797 new base::StringValue("fr"),
798 NULL);
799 provider_.UpdateChromePolicy(policies);
800 // The "en-US" ResourceBundle is always loaded before this step for tests,
801 // but in this test we want the browser to load the bundle as it
802 // normally would.
803 ResourceBundle::CleanupSharedInstance();
807 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
808 // Verifies that the default locale can be overridden with policy.
809 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
810 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
811 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
812 base::string16 title;
813 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
814 EXPECT_EQ(french_title, title);
816 // Make sure this is really French and differs from the English title.
817 std::string loaded =
818 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
819 EXPECT_EQ("en-US", loaded);
820 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
821 EXPECT_NE(french_title, english_title);
823 #endif
825 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
826 #if defined(OS_WIN) && defined(USE_ASH)
827 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
828 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
829 return;
830 #endif
832 // Verifies that the bookmarks bar can be forced to always or never show up.
834 // Test starts in about:blank.
835 PrefService* prefs = browser()->profile()->GetPrefs();
836 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
837 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
838 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
840 PolicyMap policies;
841 policies.Set(key::kBookmarkBarEnabled,
842 POLICY_LEVEL_MANDATORY,
843 POLICY_SCOPE_USER,
844 new base::FundamentalValue(true),
845 NULL);
846 UpdateProviderPolicy(policies);
847 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
848 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
849 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
851 // The NTP has special handling of the bookmark bar.
852 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
853 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
855 policies.Set(key::kBookmarkBarEnabled,
856 POLICY_LEVEL_MANDATORY,
857 POLICY_SCOPE_USER,
858 new base::FundamentalValue(false),
859 NULL);
860 UpdateProviderPolicy(policies);
861 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
862 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
863 // The bookmark bar is hidden in the NTP when disabled by policy.
864 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
866 policies.Clear();
867 UpdateProviderPolicy(policies);
868 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
869 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
870 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
871 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
874 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
875 // Verifies that cookies are deleted on shutdown. This test is split in 3
876 // parts because it spans 2 browser restarts.
878 Profile* profile = browser()->profile();
879 GURL url(kURL);
880 // No cookies at startup.
881 EXPECT_TRUE(content::GetCookies(profile, url).empty());
882 // Set a cookie now.
883 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
884 EXPECT_TRUE(content::SetCookie(profile, url, value));
885 // Verify it was set.
886 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
889 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
890 // Verify that the cookie persists across restarts.
891 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
892 // Now set the policy and the cookie should be gone after another restart.
893 PolicyMap policies;
894 policies.Set(key::kDefaultCookiesSetting,
895 POLICY_LEVEL_MANDATORY,
896 POLICY_SCOPE_USER,
897 new base::FundamentalValue(4),
898 NULL);
899 UpdateProviderPolicy(policies);
902 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
903 // Verify that the cookie is gone.
904 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
907 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
908 MakeRequestFail make_request_fail("search.example");
910 // Verifies that a default search is made using the provider configured via
911 // policy. Also checks that default search can be completely disabled.
912 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
913 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
914 const std::string kAlternateURL0(
915 "http://search.example/search#q={searchTerms}");
916 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
917 const std::string kSearchTermsReplacementKey("zekey");
918 const std::string kImageURL("http://test.com/searchbyimage/upload");
919 const std::string kImageURLPostParams(
920 "image_content=content,image_url=http://test.com/test.png");
921 const std::string kNewTabURL("http://search.example/newtab");
923 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
924 browser()->profile());
925 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
926 TemplateURL* default_search = service->GetDefaultSearchProvider();
927 ASSERT_TRUE(default_search);
928 EXPECT_NE(kKeyword, default_search->keyword());
929 EXPECT_NE(kSearchURL, default_search->url());
930 EXPECT_FALSE(
931 default_search->alternate_urls().size() == 2 &&
932 default_search->alternate_urls()[0] == kAlternateURL0 &&
933 default_search->alternate_urls()[1] == kAlternateURL1 &&
934 default_search->search_terms_replacement_key() ==
935 kSearchTermsReplacementKey &&
936 default_search->image_url() == kImageURL &&
937 default_search->image_url_post_params() == kImageURLPostParams &&
938 default_search->new_tab_url() == kNewTabURL);
940 // Override the default search provider using policies.
941 PolicyMap policies;
942 policies.Set(key::kDefaultSearchProviderEnabled,
943 POLICY_LEVEL_MANDATORY,
944 POLICY_SCOPE_USER,
945 new base::FundamentalValue(true),
946 NULL);
947 policies.Set(key::kDefaultSearchProviderKeyword,
948 POLICY_LEVEL_MANDATORY,
949 POLICY_SCOPE_USER,
950 new base::StringValue(kKeyword),
951 NULL);
952 policies.Set(key::kDefaultSearchProviderSearchURL,
953 POLICY_LEVEL_MANDATORY,
954 POLICY_SCOPE_USER,
955 new base::StringValue(kSearchURL),
956 NULL);
957 base::ListValue* alternate_urls = new base::ListValue();
958 alternate_urls->AppendString(kAlternateURL0);
959 alternate_urls->AppendString(kAlternateURL1);
960 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
961 POLICY_SCOPE_USER, alternate_urls, NULL);
962 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
963 POLICY_LEVEL_MANDATORY,
964 POLICY_SCOPE_USER,
965 new base::StringValue(kSearchTermsReplacementKey),
966 NULL);
967 policies.Set(key::kDefaultSearchProviderImageURL,
968 POLICY_LEVEL_MANDATORY,
969 POLICY_SCOPE_USER,
970 new base::StringValue(kImageURL),
971 NULL);
972 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
973 POLICY_LEVEL_MANDATORY,
974 POLICY_SCOPE_USER,
975 new base::StringValue(kImageURLPostParams),
976 NULL);
977 policies.Set(key::kDefaultSearchProviderNewTabURL,
978 POLICY_LEVEL_MANDATORY,
979 POLICY_SCOPE_USER,
980 new base::StringValue(kNewTabURL),
981 NULL);
982 UpdateProviderPolicy(policies);
983 default_search = service->GetDefaultSearchProvider();
984 ASSERT_TRUE(default_search);
985 EXPECT_EQ(kKeyword, default_search->keyword());
986 EXPECT_EQ(kSearchURL, default_search->url());
987 EXPECT_EQ(2U, default_search->alternate_urls().size());
988 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
989 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
990 EXPECT_EQ(kSearchTermsReplacementKey,
991 default_search->search_terms_replacement_key());
992 EXPECT_EQ(kImageURL, default_search->image_url());
993 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
994 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
996 // Verify that searching from the omnibox uses kSearchURL.
997 chrome::FocusLocationBar(browser());
998 LocationBar* location_bar = browser()->window()->GetLocationBar();
999 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1000 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1001 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1002 content::WebContents* web_contents =
1003 browser()->tab_strip_model()->GetActiveWebContents();
1004 GURL expected("http://search.example/search?q=stuff+to+search+for");
1005 EXPECT_EQ(expected, web_contents->GetURL());
1007 // Verify that searching from the omnibox can be disabled.
1008 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1009 policies.Set(key::kDefaultSearchProviderEnabled,
1010 POLICY_LEVEL_MANDATORY,
1011 POLICY_SCOPE_USER,
1012 new base::FundamentalValue(false),
1013 NULL);
1014 EXPECT_TRUE(service->GetDefaultSearchProvider());
1015 UpdateProviderPolicy(policies);
1016 EXPECT_FALSE(service->GetDefaultSearchProvider());
1017 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1018 // This means that submitting won't trigger any action.
1019 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1020 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1023 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1024 // Add an individual proxy policy value.
1025 PolicyMap policies;
1026 policies.Set(key::kProxyServerMode,
1027 POLICY_LEVEL_MANDATORY,
1028 POLICY_SCOPE_USER,
1029 new base::FundamentalValue(3),
1030 NULL);
1031 UpdateProviderPolicy(policies);
1033 // It should be removed and replaced with a dictionary.
1034 PolicyMap expected;
1035 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1036 expected_value->SetInteger(key::kProxyServerMode, 3);
1037 expected.Set(key::kProxySettings,
1038 POLICY_LEVEL_MANDATORY,
1039 POLICY_SCOPE_USER,
1040 expected_value.release(),
1041 NULL);
1043 // Check both the browser and the profile.
1044 const PolicyMap& actual_from_browser =
1045 g_browser_process->browser_policy_connector()
1046 ->GetPolicyService()
1047 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1048 EXPECT_TRUE(expected.Equals(actual_from_browser));
1049 const PolicyMap& actual_from_profile =
1050 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
1051 ->policy_service()
1052 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1053 EXPECT_TRUE(expected.Equals(actual_from_profile));
1056 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1057 // Makes the requests fail since all we want to check is that the redirection
1058 // is done properly.
1059 MakeRequestFail make_request_fail("google.com");
1061 // Verifies that requests to Google Search engine with the SafeSearch
1062 // enabled set the safe=active&ssui=on parameters at the end of the query.
1063 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1064 browser()->profile());
1065 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1067 // First check that nothing happens.
1068 content::TestNavigationObserver no_safesearch_observer(
1069 browser()->tab_strip_model()->GetActiveWebContents());
1070 chrome::FocusLocationBar(browser());
1071 LocationBar* location_bar = browser()->window()->GetLocationBar();
1072 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1073 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1074 no_safesearch_observer.Wait();
1075 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1076 content::WebContents* web_contents =
1077 browser()->tab_strip_model()->GetActiveWebContents();
1078 GURL expected_without("http://google.com/");
1079 EXPECT_EQ(expected_without, web_contents->GetURL());
1081 PrefService* prefs = browser()->profile()->GetPrefs();
1082 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1083 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1085 // Override the default SafeSearch setting using policies.
1086 PolicyMap policies;
1087 policies.Set(key::kForceSafeSearch,
1088 POLICY_LEVEL_MANDATORY,
1089 POLICY_SCOPE_USER,
1090 new base::FundamentalValue(true),
1091 NULL);
1092 UpdateProviderPolicy(policies);
1094 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1095 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1097 content::TestNavigationObserver safesearch_observer(
1098 browser()->tab_strip_model()->GetActiveWebContents());
1100 // Verify that searching from google.com works.
1101 chrome::FocusLocationBar(browser());
1102 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1103 safesearch_observer.Wait();
1104 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1105 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1106 std::string expected_url("http://google.com/?");
1107 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1108 chrome::kSafeSearchSsuiParameter;
1109 GURL expected_with_parameters(expected_url);
1110 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1113 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1114 MakeRequestFail make_request_fail("search.example");
1116 chrome::EnableQueryExtractionForTesting();
1118 // Verifies that a default search is made using the provider configured via
1119 // policy. Also checks that default search can be completely disabled.
1120 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1121 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1122 const std::string kInstantURL("http://does/not/exist");
1123 const std::string kAlternateURL0(
1124 "https://www.google.com/search#q={searchTerms}");
1125 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1126 const std::string kSearchTermsReplacementKey(
1127 "{google:instantExtendedEnabledKey}");
1129 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1130 browser()->profile());
1131 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1132 TemplateURL* default_search = service->GetDefaultSearchProvider();
1133 ASSERT_TRUE(default_search);
1134 EXPECT_NE(kKeyword, default_search->keyword());
1135 EXPECT_NE(kSearchURL, default_search->url());
1136 EXPECT_NE(kInstantURL, default_search->instant_url());
1137 EXPECT_FALSE(
1138 default_search->alternate_urls().size() == 2 &&
1139 default_search->alternate_urls()[0] == kAlternateURL0 &&
1140 default_search->alternate_urls()[1] == kAlternateURL1);
1142 // Override the default search provider using policies.
1143 PolicyMap policies;
1144 policies.Set(key::kDefaultSearchProviderEnabled,
1145 POLICY_LEVEL_MANDATORY,
1146 POLICY_SCOPE_USER,
1147 new base::FundamentalValue(true),
1148 NULL);
1149 policies.Set(key::kDefaultSearchProviderKeyword,
1150 POLICY_LEVEL_MANDATORY,
1151 POLICY_SCOPE_USER,
1152 new base::StringValue(kKeyword),
1153 NULL);
1154 policies.Set(key::kDefaultSearchProviderSearchURL,
1155 POLICY_LEVEL_MANDATORY,
1156 POLICY_SCOPE_USER,
1157 new base::StringValue(kSearchURL),
1158 NULL);
1159 policies.Set(key::kDefaultSearchProviderInstantURL,
1160 POLICY_LEVEL_MANDATORY,
1161 POLICY_SCOPE_USER,
1162 new base::StringValue(kInstantURL),
1163 NULL);
1164 base::ListValue* alternate_urls = new base::ListValue();
1165 alternate_urls->AppendString(kAlternateURL0);
1166 alternate_urls->AppendString(kAlternateURL1);
1167 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1168 POLICY_SCOPE_USER, alternate_urls, NULL);
1169 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1170 POLICY_LEVEL_MANDATORY,
1171 POLICY_SCOPE_USER,
1172 new base::StringValue(kSearchTermsReplacementKey),
1173 NULL);
1174 UpdateProviderPolicy(policies);
1175 default_search = service->GetDefaultSearchProvider();
1176 ASSERT_TRUE(default_search);
1177 EXPECT_EQ(kKeyword, default_search->keyword());
1178 EXPECT_EQ(kSearchURL, default_search->url());
1179 EXPECT_EQ(kInstantURL, default_search->instant_url());
1180 EXPECT_EQ(2U, default_search->alternate_urls().size());
1181 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1182 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1184 // Query terms replacement requires that the renderer process be a recognized
1185 // Instant renderer. Fake it.
1186 InstantService* instant_service =
1187 InstantServiceFactory::GetForProfile(browser()->profile());
1188 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1189 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1191 // Verify that searching from the omnibox does search term replacement with
1192 // first URL pattern.
1193 chrome::FocusLocationBar(browser());
1194 LocationBar* location_bar = browser()->window()->GetLocationBar();
1195 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1196 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1197 "https://www.google.com/?espv=1#q=foobar");
1198 EXPECT_TRUE(
1199 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1200 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1202 // Verify that not using espv=1 does not do search term replacement.
1203 chrome::FocusLocationBar(browser());
1204 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1205 "https://www.google.com/?q=foobar");
1206 EXPECT_FALSE(
1207 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1208 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1209 omnibox_view->GetText());
1211 // Verify that searching from the omnibox does search term replacement with
1212 // second URL pattern.
1213 chrome::FocusLocationBar(browser());
1214 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1215 "https://www.google.com/search?espv=1#q=banana");
1216 EXPECT_TRUE(
1217 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1218 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1220 // Verify that searching from the omnibox does search term replacement with
1221 // standard search URL pattern.
1222 chrome::FocusLocationBar(browser());
1223 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1224 "https://www.google.com/search?q=tractor+parts&espv=1");
1225 EXPECT_TRUE(
1226 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1227 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1229 // Verify that searching from the omnibox prioritizes hash over query.
1230 chrome::FocusLocationBar(browser());
1231 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1232 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1233 EXPECT_TRUE(
1234 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1235 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1238 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1239 // This test assumes Gpu access.
1240 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1241 return;
1243 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1244 // WebGL is enabled by default.
1245 content::WebContents* contents =
1246 browser()->tab_strip_model()->GetActiveWebContents();
1247 EXPECT_TRUE(IsWebGLEnabled(contents));
1248 // Disable with a policy.
1249 PolicyMap policies;
1250 policies.Set(key::kDisable3DAPIs,
1251 POLICY_LEVEL_MANDATORY,
1252 POLICY_SCOPE_USER,
1253 new base::FundamentalValue(true),
1254 NULL);
1255 UpdateProviderPolicy(policies);
1256 // Crash and reload the tab to get a new renderer.
1257 content::CrashTab(contents);
1258 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1259 EXPECT_FALSE(IsWebGLEnabled(contents));
1260 // Enable with a policy.
1261 policies.Set(key::kDisable3DAPIs,
1262 POLICY_LEVEL_MANDATORY,
1263 POLICY_SCOPE_USER,
1264 new base::FundamentalValue(false),
1265 NULL);
1266 UpdateProviderPolicy(policies);
1267 content::CrashTab(contents);
1268 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1269 EXPECT_TRUE(IsWebGLEnabled(contents));
1272 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1273 // Verifies that SPDY can be disable by policy.
1274 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1275 PolicyMap policies;
1276 policies.Set(key::kDisableSpdy,
1277 POLICY_LEVEL_MANDATORY,
1278 POLICY_SCOPE_USER,
1279 new base::FundamentalValue(true),
1280 NULL);
1281 UpdateProviderPolicy(policies);
1282 content::RunAllPendingInMessageLoop();
1283 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1284 // Verify that it can be force-enabled too.
1285 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1286 policies.Set(key::kDisableSpdy,
1287 POLICY_LEVEL_MANDATORY,
1288 POLICY_SCOPE_USER,
1289 new base::FundamentalValue(false),
1290 NULL);
1291 UpdateProviderPolicy(policies);
1292 content::RunAllPendingInMessageLoop();
1293 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1296 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1297 // Verifies that plugins can be forced to be disabled by policy.
1299 // Verify that the Flash plugin exists and that it can be enabled and disabled
1300 // by the user.
1301 std::vector<content::WebPluginInfo> plugins;
1302 GetPluginList(&plugins);
1303 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1304 if (!flash)
1305 return;
1306 PluginPrefs* plugin_prefs =
1307 PluginPrefs::GetForProfile(browser()->profile()).get();
1308 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1309 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1310 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1311 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1312 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1314 // Now disable it with a policy.
1315 base::ListValue disabled_plugins;
1316 disabled_plugins.Append(new base::StringValue("*Flash*"));
1317 PolicyMap policies;
1318 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1319 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1320 UpdateProviderPolicy(policies);
1321 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1322 // The user shouldn't be able to enable it.
1323 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1324 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1327 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1328 // Verifies that plugins with an exception in the blacklist can be enabled.
1330 // Verify that the Flash plugin exists and that it can be enabled and disabled
1331 // by the user.
1332 std::vector<content::WebPluginInfo> plugins;
1333 GetPluginList(&plugins);
1334 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1335 if (!flash)
1336 return;
1337 PluginPrefs* plugin_prefs =
1338 PluginPrefs::GetForProfile(browser()->profile()).get();
1339 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1341 // Disable all plugins.
1342 base::ListValue disabled_plugins;
1343 disabled_plugins.Append(new base::StringValue("*"));
1344 PolicyMap policies;
1345 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1346 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1347 UpdateProviderPolicy(policies);
1348 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1349 // The user shouldn't be able to enable it.
1350 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1351 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1353 // Now open an exception for flash.
1354 base::ListValue disabled_plugins_exceptions;
1355 disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1356 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1357 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1358 UpdateProviderPolicy(policies);
1359 // It should revert to the user's preference automatically.
1360 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1361 // And the user should be able to disable and enable again.
1362 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1363 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1364 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1365 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1368 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1369 // Verifies that a plugin can be force-installed with a policy.
1370 std::vector<content::WebPluginInfo> plugins;
1371 GetPluginList(&plugins);
1372 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1373 if (!flash)
1374 return;
1375 PluginPrefs* plugin_prefs =
1376 PluginPrefs::GetForProfile(browser()->profile()).get();
1377 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1379 // The user disables it and then a policy forces it to be enabled.
1380 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1381 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1382 base::ListValue plugin_list;
1383 plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1384 PolicyMap policies;
1385 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1386 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1387 UpdateProviderPolicy(policies);
1388 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1389 // The user can't disable it anymore.
1390 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1391 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1393 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1394 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1395 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1396 UpdateProviderPolicy(policies);
1397 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1400 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1401 // Verifies that dangerous plugins can be always authorized to run with
1402 // a policy.
1404 // Verify that the test page exists. It is only present in checkouts with
1405 // src-internal.
1406 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1407 base::FilePath(FILE_PATH_LITERAL("plugin")),
1408 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1409 LOG(INFO) <<
1410 "Test skipped because plugin/quicktime.html test file wasn't found.";
1411 return;
1414 ServeContentTestData();
1415 // No plugins at startup.
1416 EXPECT_EQ(0, CountPlugins());
1418 content::WebContents* contents =
1419 browser()->tab_strip_model()->GetActiveWebContents();
1420 ASSERT_TRUE(contents);
1421 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1422 ASSERT_TRUE(infobar_service);
1423 EXPECT_EQ(0u, infobar_service->infobar_count());
1425 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1426 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1427 ui_test_utils::NavigateToURL(browser(), url);
1428 // This should have triggered the dangerous plugin infobar.
1429 ASSERT_EQ(1u, infobar_service->infobar_count());
1430 EXPECT_TRUE(
1431 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1432 // And the plugin isn't running.
1433 EXPECT_EQ(0, CountPlugins());
1435 // Now set a policy to always authorize this.
1436 PolicyMap policies;
1437 policies.Set(key::kAlwaysAuthorizePlugins,
1438 POLICY_LEVEL_MANDATORY,
1439 POLICY_SCOPE_USER,
1440 new base::FundamentalValue(true),
1441 NULL);
1442 UpdateProviderPolicy(policies);
1443 // Reloading the page shouldn't trigger the infobar this time.
1444 ui_test_utils::NavigateToURL(browser(), url);
1445 EXPECT_EQ(0u, infobar_service->infobar_count());
1446 // And the plugin started automatically.
1447 EXPECT_EQ(1, CountPlugins());
1450 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1451 // Verifies that access to the developer tools can be disabled.
1453 // Open devtools.
1454 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1455 content::WebContents* contents =
1456 browser()->tab_strip_model()->GetActiveWebContents();
1457 DevToolsWindow *devtools_window =
1458 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1459 EXPECT_TRUE(devtools_window);
1461 // Disable devtools via policy.
1462 PolicyMap policies;
1463 policies.Set(key::kDeveloperToolsDisabled,
1464 POLICY_LEVEL_MANDATORY,
1465 POLICY_SCOPE_USER,
1466 new base::FundamentalValue(true),
1467 NULL);
1468 content::WindowedNotificationObserver close_observer(
1469 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1470 content::Source<content::WebContents>(
1471 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1472 UpdateProviderPolicy(policies);
1473 // wait for devtools close
1474 close_observer.Wait();
1475 // The existing devtools window should have closed.
1476 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1477 // And it's not possible to open it again.
1478 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1479 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1482 // TODO(samarth): remove along with rest of NTP4 code.
1483 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1484 #if defined(OS_WIN) && defined(USE_ASH)
1485 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1486 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1487 return;
1488 #endif
1490 // Verifies that the web store icons can be hidden from the new tab page.
1492 // Open new tab page and look for the web store icons.
1493 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1494 content::WebContents* contents =
1495 browser()->tab_strip_model()->GetActiveWebContents();
1497 #if !defined(OS_CHROMEOS)
1498 // Look for web store's app ID in the apps page.
1499 EXPECT_TRUE(ContainsVisibleElement(contents,
1500 "ahfgeienlihckogmohjhadlkjgocpleb"));
1501 #endif
1503 // The next NTP has no footer.
1504 if (ContainsVisibleElement(contents, "footer"))
1505 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1507 // Turn off the web store icons.
1508 PolicyMap policies;
1509 policies.Set(key::kHideWebStoreIcon,
1510 POLICY_LEVEL_MANDATORY,
1511 POLICY_SCOPE_USER,
1512 new base::FundamentalValue(true),
1513 NULL);
1514 UpdateProviderPolicy(policies);
1516 // The web store icons should now be hidden.
1517 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1518 EXPECT_FALSE(ContainsVisibleElement(contents,
1519 "ahfgeienlihckogmohjhadlkjgocpleb"));
1520 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1523 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1524 // Verifies that the download directory can be forced by policy.
1526 // Set the initial download directory.
1527 base::ScopedTempDir initial_dir;
1528 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1529 browser()->profile()->GetPrefs()->SetFilePath(
1530 prefs::kDownloadDefaultDirectory, initial_dir.path());
1531 // Don't prompt for the download location during this test.
1532 browser()->profile()->GetPrefs()->SetBoolean(
1533 prefs::kPromptForDownload, false);
1535 // Verify that downloads end up on the default directory.
1536 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1537 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1538 base::DieFileDie(initial_dir.path().Append(file), false);
1540 // Override the download directory with the policy and verify a download.
1541 base::ScopedTempDir forced_dir;
1542 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1543 PolicyMap policies;
1544 policies.Set(key::kDownloadDirectory,
1545 POLICY_LEVEL_MANDATORY,
1546 POLICY_SCOPE_USER,
1547 new base::StringValue(forced_dir.path().value()),
1548 NULL);
1549 UpdateProviderPolicy(policies);
1550 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1551 // Verify that the first download location wasn't affected.
1552 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1555 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1556 // Verifies that blacklisted extensions can't be installed.
1557 ExtensionService* service = extension_service();
1558 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1559 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1560 base::ListValue blacklist;
1561 blacklist.Append(new base::StringValue(kGoodCrxId));
1562 PolicyMap policies;
1563 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1564 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1565 UpdateProviderPolicy(policies);
1567 // "good.crx" is blacklisted.
1568 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1569 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1571 // "adblock.crx" is not.
1572 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1573 ASSERT_TRUE(adblock);
1574 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1575 EXPECT_EQ(adblock,
1576 service->GetExtensionById(kAdBlockCrxId, true));
1579 // Flaky on windows; http://crbug.com/307994.
1580 #if defined(OS_WIN)
1581 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1582 #else
1583 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1584 #endif
1585 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1586 // Verify that a wildcard blacklist takes effect.
1587 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1588 ExtensionService* service = extension_service();
1589 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1590 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1591 base::ListValue blacklist;
1592 blacklist.Append(new base::StringValue("*"));
1593 PolicyMap policies;
1594 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1595 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1596 UpdateProviderPolicy(policies);
1598 // AdBlock was automatically removed.
1599 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1601 // And can't be installed again, nor can good.crx.
1602 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1603 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1604 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1605 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1608 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1609 // Verifies that the whitelist can open exceptions to the blacklist.
1610 ExtensionService* service = extension_service();
1611 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1612 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1613 base::ListValue blacklist;
1614 blacklist.Append(new base::StringValue("*"));
1615 base::ListValue whitelist;
1616 whitelist.Append(new base::StringValue(kGoodCrxId));
1617 PolicyMap policies;
1618 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1619 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1620 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1621 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1622 UpdateProviderPolicy(policies);
1623 // "adblock.crx" is blacklisted.
1624 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1625 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1626 // "good.crx" has a whitelist exception.
1627 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1628 ASSERT_TRUE(good);
1629 EXPECT_EQ(kGoodCrxId, good->id());
1630 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1631 // The user can also remove this extension.
1632 UninstallExtension(kGoodCrxId, true);
1635 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1636 // Verifies that extensions that are force-installed by policies are
1637 // installed and can't be uninstalled.
1638 ExtensionService* service = extension_service();
1639 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1641 // Extensions that are force-installed come from an update URL, which defaults
1642 // to the webstore. Use a mock URL for this test with an update manifest
1643 // that includes "good_v1.crx".
1644 base::FilePath path =
1645 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1646 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1648 // Setting the forcelist extension should install "good_v1.crx".
1649 base::ListValue forcelist;
1650 forcelist.Append(new base::StringValue(
1651 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1652 PolicyMap policies;
1653 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1654 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1655 content::WindowedNotificationObserver observer(
1656 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1657 content::NotificationService::AllSources());
1658 UpdateProviderPolicy(policies);
1659 observer.Wait();
1660 // Note: Cannot check that the notification details match the expected
1661 // exception, since the details object has already been freed prior to
1662 // the completion of observer.Wait().
1664 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1666 // The user is not allowed to uninstall force-installed extensions.
1667 UninstallExtension(kGoodCrxId, false);
1669 // The user is not allowed to load an unpacked extension with the
1670 // same ID as a force-installed extension.
1671 LoadUnpackedExtension(kGoodUnpackedExt, false);
1673 // Loading other unpacked extensions are not blocked.
1674 LoadUnpackedExtension(kAppUnpackedExt, true);
1676 const std::string old_version_number =
1677 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1679 base::FilePath test_path;
1680 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1682 TestRequestInterceptor interceptor(
1683 "update.extension",
1684 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1685 interceptor.PushJobCallback(
1686 TestRequestInterceptor::FileJob(
1687 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1689 // Updating the force-installed extension.
1690 extensions::ExtensionUpdater* updater = service->updater();
1691 extensions::ExtensionUpdater::CheckParams params;
1692 params.install_immediately = true;
1693 content::WindowedNotificationObserver update_observer(
1694 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1695 content::NotificationService::AllSources());
1696 updater->CheckNow(params);
1697 update_observer.Wait();
1699 const base::Version* new_version =
1700 service->GetExtensionById(kGoodCrxId, true)->version();
1701 ASSERT_TRUE(new_version->IsValid());
1702 base::Version old_version(old_version_number);
1703 ASSERT_TRUE(old_version.IsValid());
1705 EXPECT_EQ(1, new_version->CompareTo(old_version));
1707 EXPECT_EQ(0u, interceptor.GetPendingSize());
1709 // Wait until any background pages belonging to force-installed extensions
1710 // have been loaded.
1711 extensions::ProcessManager* manager =
1712 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1713 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1714 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1715 all_views.begin();
1716 iter != all_views.end();) {
1717 if (!(*iter)->IsLoading()) {
1718 ++iter;
1719 } else {
1720 content::WebContents* web_contents =
1721 content::WebContents::FromRenderViewHost(*iter);
1722 ASSERT_TRUE(web_contents);
1723 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1725 // Test activity may have modified the set of extension processes during
1726 // message processing, so re-start the iteration to catch added/removed
1727 // processes.
1728 all_views = manager->GetAllViews();
1729 iter = all_views.begin();
1733 // Test policy-installed extensions are reloaded when killed.
1734 BackgroundContentsService::
1735 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1736 content::WindowedNotificationObserver extension_crashed_observer(
1737 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1738 content::NotificationService::AllSources());
1739 content::WindowedNotificationObserver extension_loaded_observer(
1740 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1741 content::NotificationService::AllSources());
1742 extensions::ExtensionHost* extension_host =
1743 extensions::ExtensionSystem::Get(browser()->profile())->
1744 process_manager()->GetBackgroundHostForExtension(kGoodCrxId);
1745 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1746 content::RESULT_CODE_KILLED, false);
1747 extension_crashed_observer.Wait();
1748 extension_loaded_observer.Wait();
1751 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1752 // Verifies that extensions that are recommended-installed by policies are
1753 // installed, can be disabled but not uninstalled.
1754 ExtensionService* service = extension_service();
1755 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1757 base::FilePath path =
1758 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1759 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1761 // Setting the forcelist extension should install "good_v1.crx".
1762 base::DictionaryValue dict_value;
1763 dict_value.SetString(std::string(kGoodCrxId) + "." +
1764 extensions::schema_constants::kInstallationMode,
1765 extensions::schema_constants::kNormalInstalled);
1766 dict_value.SetString(
1767 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1768 url.spec());
1769 PolicyMap policies;
1770 policies.Set(key::kExtensionSettings,
1771 POLICY_LEVEL_MANDATORY,
1772 POLICY_SCOPE_USER,
1773 dict_value.DeepCopy(),
1774 NULL);
1775 content::WindowedNotificationObserver observer(
1776 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1777 content::NotificationService::AllSources());
1778 UpdateProviderPolicy(policies);
1779 observer.Wait();
1781 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1783 // The user is not allowed to uninstall recommended-installed extensions.
1784 UninstallExtension(kGoodCrxId, false);
1786 // Explictly re-enables the extension.
1787 service->EnableExtension(kGoodCrxId);
1789 // But the user is allowed to disable them.
1790 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1791 DisableExtension(kGoodCrxId);
1792 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1795 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1796 // Verifies that extensions are blocked if policy specifies an allowed types
1797 // list and the extension's type is not on that list.
1798 ExtensionService* service = extension_service();
1799 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1800 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1802 base::ListValue allowed_types;
1803 allowed_types.AppendString("hosted_app");
1804 PolicyMap policies;
1805 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1806 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1807 UpdateProviderPolicy(policies);
1809 // "good.crx" is blocked.
1810 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1811 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1813 // "hosted_app.crx" is of a whitelisted type.
1814 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1815 ASSERT_TRUE(hosted_app);
1816 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1817 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1819 // The user can remove the extension.
1820 UninstallExtension(kHostedAppCrxId, true);
1823 // Checks that a click on an extension CRX download triggers the extension
1824 // installation prompt without further user interaction when the source is
1825 // whitelisted by policy.
1826 // Flaky on windows; http://crbug.com/295729 .
1827 #if defined(OS_WIN)
1828 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1829 #else
1830 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1831 #endif
1832 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1833 ExtensionInstallPrompt::g_auto_confirm_for_tests =
1834 ExtensionInstallPrompt::ACCEPT;
1836 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1837 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1838 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1839 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1841 base::ScopedTempDir download_directory;
1842 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1843 DownloadPrefs* download_prefs =
1844 DownloadPrefs::FromBrowserContext(browser()->profile());
1845 download_prefs->SetDownloadPath(download_directory.path());
1847 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1848 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1849 ui_test_utils::NavigateToURL(browser(), download_page_url);
1851 // As long as the policy is not present, extensions are considered dangerous.
1852 content::DownloadTestObserverTerminal download_observer(
1853 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1854 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1855 PerformClick(0, 0);
1856 download_observer.WaitForFinished();
1858 // Install the policy and trigger another download.
1859 base::ListValue install_sources;
1860 install_sources.AppendString(install_source_url.spec());
1861 install_sources.AppendString(referrer_url.spec());
1862 PolicyMap policies;
1863 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1864 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1865 UpdateProviderPolicy(policies);
1867 content::WindowedNotificationObserver observer(
1868 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1869 content::NotificationService::AllSources());
1870 PerformClick(1, 0);
1871 observer.Wait();
1872 // Note: Cannot check that the notification details match the expected
1873 // exception, since the details object has already been freed prior to
1874 // the completion of observer.Wait().
1876 // The first extension shouldn't be present, the second should be there.
1877 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1878 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1881 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1882 #if defined(OS_WIN) && defined(USE_ASH)
1883 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1884 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1885 return;
1886 #endif
1888 // Verifies that the homepage can be configured with policies.
1889 // Set a default, and check that the home button navigates there.
1890 browser()->profile()->GetPrefs()->SetString(
1891 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1892 browser()->profile()->GetPrefs()->SetBoolean(
1893 prefs::kHomePageIsNewTabPage, false);
1894 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1895 browser()->profile()->GetHomePage());
1896 content::WebContents* contents =
1897 browser()->tab_strip_model()->GetActiveWebContents();
1898 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
1899 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1900 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1902 // Now override with policy.
1903 PolicyMap policies;
1904 policies.Set(key::kHomepageLocation,
1905 POLICY_LEVEL_MANDATORY,
1906 POLICY_SCOPE_USER,
1907 new base::StringValue(chrome::kChromeUICreditsURL),
1908 NULL);
1909 UpdateProviderPolicy(policies);
1910 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1911 content::WaitForLoadStop(contents);
1912 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1914 policies.Set(key::kHomepageIsNewTabPage,
1915 POLICY_LEVEL_MANDATORY,
1916 POLICY_SCOPE_USER,
1917 new base::FundamentalValue(true),
1918 NULL);
1919 UpdateProviderPolicy(policies);
1920 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1921 content::WaitForLoadStop(contents);
1922 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1925 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1926 // Verifies that incognito windows can't be opened when disabled by policy.
1928 const BrowserList* active_browser_list =
1929 BrowserList::GetInstance(chrome::GetActiveDesktop());
1931 // Disable incognito via policy and verify that incognito windows can't be
1932 // opened.
1933 EXPECT_EQ(1u, active_browser_list->size());
1934 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1935 PolicyMap policies;
1936 policies.Set(key::kIncognitoEnabled,
1937 POLICY_LEVEL_MANDATORY,
1938 POLICY_SCOPE_USER,
1939 new base::FundamentalValue(false),
1940 NULL);
1941 UpdateProviderPolicy(policies);
1942 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1943 EXPECT_EQ(1u, active_browser_list->size());
1944 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1946 // Enable via policy and verify that incognito windows can be opened.
1947 policies.Set(key::kIncognitoEnabled,
1948 POLICY_LEVEL_MANDATORY,
1949 POLICY_SCOPE_USER,
1950 new base::FundamentalValue(true),
1951 NULL);
1952 UpdateProviderPolicy(policies);
1953 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1954 EXPECT_EQ(2u, active_browser_list->size());
1955 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1958 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1959 // Verifies that Javascript can be disabled.
1960 content::WebContents* contents =
1961 browser()->tab_strip_model()->GetActiveWebContents();
1962 EXPECT_TRUE(IsJavascriptEnabled(contents));
1963 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1964 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1965 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1967 // Disable Javascript via policy.
1968 PolicyMap policies;
1969 policies.Set(key::kJavascriptEnabled,
1970 POLICY_LEVEL_MANDATORY,
1971 POLICY_SCOPE_USER,
1972 new base::FundamentalValue(false),
1973 NULL);
1974 UpdateProviderPolicy(policies);
1975 // Reload the page.
1976 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1977 EXPECT_FALSE(IsJavascriptEnabled(contents));
1978 // Developer tools still work when javascript is disabled.
1979 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1980 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1981 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1982 // Javascript is always enabled for the internal pages.
1983 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1984 EXPECT_TRUE(IsJavascriptEnabled(contents));
1986 // The javascript content setting policy overrides the javascript policy.
1987 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1988 EXPECT_FALSE(IsJavascriptEnabled(contents));
1989 policies.Set(key::kDefaultJavaScriptSetting,
1990 POLICY_LEVEL_MANDATORY,
1991 POLICY_SCOPE_USER,
1992 new base::FundamentalValue(CONTENT_SETTING_ALLOW),
1993 NULL);
1994 UpdateProviderPolicy(policies);
1995 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1996 EXPECT_TRUE(IsJavascriptEnabled(contents));
1999 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2000 PrefService* prefs = browser()->profile()->GetPrefs();
2002 // Enabled by default.
2003 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2005 // Disable by old, deprecated policy.
2006 PolicyMap policies;
2007 policies.Set(key::kDnsPrefetchingEnabled,
2008 POLICY_LEVEL_MANDATORY,
2009 POLICY_SCOPE_USER,
2010 new base::FundamentalValue(false),
2011 NULL);
2012 UpdateProviderPolicy(policies);
2014 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2016 // Enabled by new policy, this should override old one.
2017 policies.Set(
2018 key::kNetworkPredictionOptions,
2019 POLICY_LEVEL_MANDATORY,
2020 POLICY_SCOPE_USER,
2021 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2022 NULL);
2023 UpdateProviderPolicy(policies);
2025 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2028 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2029 // Verifies that browsing history is not saved.
2030 PolicyMap policies;
2031 policies.Set(key::kSavingBrowserHistoryDisabled,
2032 POLICY_LEVEL_MANDATORY,
2033 POLICY_SCOPE_USER,
2034 new base::FundamentalValue(true),
2035 NULL);
2036 UpdateProviderPolicy(policies);
2037 GURL url = ui_test_utils::GetTestUrl(
2038 base::FilePath(base::FilePath::kCurrentDirectory),
2039 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2040 ui_test_utils::NavigateToURL(browser(), url);
2041 // Verify that the navigation wasn't saved in the history.
2042 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2043 EXPECT_EQ(0u, enumerator1.urls().size());
2045 // Now flip the policy and try again.
2046 policies.Set(key::kSavingBrowserHistoryDisabled,
2047 POLICY_LEVEL_MANDATORY,
2048 POLICY_SCOPE_USER,
2049 new base::FundamentalValue(false),
2050 NULL);
2051 UpdateProviderPolicy(policies);
2052 ui_test_utils::NavigateToURL(browser(), url);
2053 // Verify that the navigation was saved in the history.
2054 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2055 ASSERT_EQ(1u, enumerator2.urls().size());
2056 EXPECT_EQ(url, enumerator2.urls()[0]);
2059 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2060 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2061 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2062 if (TranslateService::IsTranslateBubbleEnabled())
2063 return;
2065 scoped_ptr<test::CldDataHarness> cld_data_scope =
2066 test::CreateCldDataHarness();
2067 ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2069 // Verifies that translate can be forced enabled or disabled by policy.
2071 // Get the InfoBarService, and verify that there are no infobars on startup.
2072 content::WebContents* contents =
2073 browser()->tab_strip_model()->GetActiveWebContents();
2074 ASSERT_TRUE(contents);
2075 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2076 ASSERT_TRUE(infobar_service);
2077 EXPECT_EQ(0u, infobar_service->infobar_count());
2079 // Force enable the translate feature.
2080 PolicyMap policies;
2081 policies.Set(key::kTranslateEnabled,
2082 POLICY_LEVEL_MANDATORY,
2083 POLICY_SCOPE_USER,
2084 new base::FundamentalValue(true),
2085 NULL);
2086 UpdateProviderPolicy(policies);
2087 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2088 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2089 // TranslateManager observes. This allows checking that an infobar is NOT
2090 // shown below, without polling for infobars for some indeterminate amount
2091 // of time.
2092 GURL url = ui_test_utils::GetTestUrl(
2093 base::FilePath(),
2094 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2095 content::WindowedNotificationObserver language_observer1(
2096 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2097 content::NotificationService::AllSources());
2098 ui_test_utils::NavigateToURL(browser(), url);
2099 language_observer1.Wait();
2101 // Verify the translation detected for this tab.
2102 ChromeTranslateClient* chrome_translate_client =
2103 ChromeTranslateClient::FromWebContents(contents);
2104 ASSERT_TRUE(chrome_translate_client);
2105 translate::LanguageState& language_state =
2106 chrome_translate_client->GetLanguageState();
2107 EXPECT_EQ("fr", language_state.original_language());
2108 EXPECT_TRUE(language_state.page_needs_translation());
2109 EXPECT_FALSE(language_state.translation_pending());
2110 EXPECT_FALSE(language_state.translation_declined());
2111 EXPECT_FALSE(language_state.IsPageTranslated());
2113 // Verify that the translate infobar showed up.
2114 ASSERT_EQ(1u, infobar_service->infobar_count());
2115 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2116 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2117 infobar->delegate()->AsTranslateInfoBarDelegate();
2118 ASSERT_TRUE(translate_infobar_delegate);
2119 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2120 translate_infobar_delegate->translate_step());
2121 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2123 // Now force disable translate.
2124 infobar_service->RemoveInfoBar(infobar);
2125 EXPECT_EQ(0u, infobar_service->infobar_count());
2126 policies.Set(key::kTranslateEnabled,
2127 POLICY_LEVEL_MANDATORY,
2128 POLICY_SCOPE_USER,
2129 new base::FundamentalValue(false),
2130 NULL);
2131 UpdateProviderPolicy(policies);
2132 // Navigating to the same URL now doesn't trigger an infobar.
2133 content::WindowedNotificationObserver language_observer2(
2134 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2135 content::NotificationService::AllSources());
2136 ui_test_utils::NavigateToURL(browser(), url);
2137 language_observer2.Wait();
2138 EXPECT_EQ(0u, infobar_service->infobar_count());
2141 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2142 // Checks that URLs can be blacklisted, and that exceptions can be made to
2143 // the blacklist.
2145 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2146 // as URLRequestMockHTTPJobs.
2147 const char* kURLS[] = {
2148 "http://aaa.com/empty.html",
2149 "http://bbb.com/empty.html",
2150 "http://sub.bbb.com/empty.html",
2151 "http://bbb.com/policy/blank.html",
2154 base::RunLoop loop;
2155 BrowserThread::PostTaskAndReply(
2156 BrowserThread::IO, FROM_HERE,
2157 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2158 loop.QuitClosure());
2159 loop.Run();
2162 // Verify that "bbb.com" opens before applying the blacklist.
2163 CheckCanOpenURL(browser(), kURLS[1]);
2165 // Set a blacklist.
2166 base::ListValue blacklist;
2167 blacklist.Append(new base::StringValue("bbb.com"));
2168 PolicyMap policies;
2169 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2170 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2171 UpdateProviderPolicy(policies);
2172 FlushBlacklistPolicy();
2173 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2174 CheckCanOpenURL(browser(), kURLS[0]);
2175 for (size_t i = 1; i < arraysize(kURLS); ++i)
2176 CheckURLIsBlocked(browser(), kURLS[i]);
2178 // Whitelist some sites of bbb.com.
2179 base::ListValue whitelist;
2180 whitelist.Append(new base::StringValue("sub.bbb.com"));
2181 whitelist.Append(new base::StringValue("bbb.com/policy"));
2182 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2183 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2184 UpdateProviderPolicy(policies);
2185 FlushBlacklistPolicy();
2186 CheckURLIsBlocked(browser(), kURLS[1]);
2187 CheckCanOpenURL(browser(), kURLS[2]);
2188 CheckCanOpenURL(browser(), kURLS[3]);
2191 base::RunLoop loop;
2192 BrowserThread::PostTaskAndReply(
2193 BrowserThread::IO, FROM_HERE,
2194 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2195 loop.QuitClosure());
2196 loop.Run();
2200 #if defined(OS_MACOSX)
2201 // http://crbug.com/339240
2202 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2203 #else
2204 #define MAYBE_FileURLBlacklist FileURLBlacklist
2205 #endif
2206 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2207 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2208 // with URLblacklisting and URLwhitelisting.
2210 base::FilePath test_path;
2211 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2212 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2213 const std::string folder_path = base_path + "apptest/";
2214 const std::string file_path1 = base_path + "title1.html";
2215 const std::string file_path2 = folder_path + "basic.html";
2217 CheckCanOpenURL(browser(), file_path1.c_str());
2218 CheckCanOpenURL(browser(), file_path2.c_str());
2220 // Set a blacklist for all the files.
2221 base::ListValue blacklist;
2222 blacklist.Append(new base::StringValue("file://*"));
2223 PolicyMap policies;
2224 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2225 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2226 UpdateProviderPolicy(policies);
2227 FlushBlacklistPolicy();
2229 CheckURLIsBlocked(browser(), file_path1.c_str());
2230 CheckURLIsBlocked(browser(), file_path2.c_str());
2232 // Replace the URLblacklist with disabling the file scheme.
2233 blacklist.Remove(base::StringValue("file://*"), NULL);
2234 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2235 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2236 UpdateProviderPolicy(policies);
2237 FlushBlacklistPolicy();
2239 PrefService* prefs = browser()->profile()->GetPrefs();
2240 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2241 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2242 list_url->end());
2244 base::ListValue disabledscheme;
2245 disabledscheme.Append(new base::StringValue("file"));
2246 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2247 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2248 UpdateProviderPolicy(policies);
2249 FlushBlacklistPolicy();
2251 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2252 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2253 list_url->end());
2255 // Whitelist one folder and blacklist an another just inside.
2256 base::ListValue whitelist;
2257 whitelist.Append(new base::StringValue(base_path));
2258 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2259 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2260 blacklist.Append(new base::StringValue(folder_path));
2261 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2262 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2263 UpdateProviderPolicy(policies);
2264 FlushBlacklistPolicy();
2266 CheckCanOpenURL(browser(), file_path1.c_str());
2267 CheckURLIsBlocked(browser(), file_path2.c_str());
2270 static bool IsMinSSLVersionTLS12(Profile* profile) {
2271 scoped_refptr<net::SSLConfigService> config_service(
2272 profile->GetSSLConfigService());
2273 net::SSLConfig config;
2274 config_service->GetSSLConfig(&config);
2275 return config.version_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2278 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionMin) {
2279 PrefService* prefs = g_browser_process->local_state();
2281 const std::string new_value("tls1.2");
2282 const std::string default_value(prefs->GetString(prefs::kSSLVersionMin));
2284 EXPECT_NE(default_value, new_value);
2285 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2287 PolicyMap policies;
2288 policies.Set(key::kSSLVersionMin,
2289 POLICY_LEVEL_MANDATORY,
2290 POLICY_SCOPE_USER,
2291 new base::StringValue(new_value),
2292 NULL);
2293 UpdateProviderPolicy(policies);
2295 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2298 static bool IsMinSSLFallbackVersionTLS12(Profile* profile) {
2299 scoped_refptr<net::SSLConfigService> config_service(
2300 profile->GetSSLConfigService());
2301 net::SSLConfig config;
2302 config_service->GetSSLConfig(&config);
2303 return config.version_fallback_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2306 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2307 PrefService* prefs = g_browser_process->local_state();
2309 const std::string new_value("tls1.2");
2310 const std::string default_value(
2311 prefs->GetString(prefs::kSSLVersionFallbackMin));
2313 EXPECT_NE(default_value, new_value);
2314 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2316 PolicyMap policies;
2317 policies.Set(key::kSSLVersionFallbackMin,
2318 POLICY_LEVEL_MANDATORY,
2319 POLICY_SCOPE_USER,
2320 new base::StringValue(new_value),
2321 NULL);
2322 UpdateProviderPolicy(policies);
2324 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2327 #if !defined(OS_MACOSX)
2328 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2329 PolicyMap policies;
2330 policies.Set(key::kFullscreenAllowed,
2331 POLICY_LEVEL_MANDATORY,
2332 POLICY_SCOPE_USER,
2333 new base::FundamentalValue(false),
2334 NULL);
2335 UpdateProviderPolicy(policies);
2337 BrowserWindow* browser_window = browser()->window();
2338 ASSERT_TRUE(browser_window);
2340 EXPECT_FALSE(browser_window->IsFullscreen());
2341 chrome::ToggleFullscreenMode(browser());
2342 EXPECT_FALSE(browser_window->IsFullscreen());
2345 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2346 PolicyMap policies;
2347 policies.Set(key::kFullscreenAllowed,
2348 POLICY_LEVEL_MANDATORY,
2349 POLICY_SCOPE_USER,
2350 new base::FundamentalValue(false),
2351 NULL);
2352 UpdateProviderPolicy(policies);
2354 const extensions::Extension* extension =
2355 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2356 ASSERT_TRUE(extension);
2358 // Launch an app that tries to open a fullscreen window.
2359 TestAddAppWindowObserver add_window_observer(
2360 extensions::AppWindowRegistry::Get(browser()->profile()));
2361 OpenApplication(AppLaunchParams(browser()->profile(),
2362 extension,
2363 extensions::LAUNCH_CONTAINER_NONE,
2364 NEW_WINDOW));
2365 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2366 ASSERT_TRUE(window);
2368 // Verify that the window is not in fullscreen mode.
2369 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2371 // Verify that the window cannot be toggled into fullscreen mode via apps
2372 // APIs.
2373 EXPECT_TRUE(content::ExecuteScript(
2374 window->web_contents(),
2375 "chrome.app.window.current().fullscreen();"));
2376 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2378 // Verify that the window cannot be toggled into fullscreen mode from within
2379 // Chrome (e.g., using keyboard accelerators).
2380 window->Fullscreen();
2381 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2383 #endif
2385 #if defined(OS_CHROMEOS)
2386 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2387 int screenshot_count = CountScreenshots();
2389 // Make sure screenshots are counted correctly.
2390 TestScreenshotFile(true);
2391 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2393 // Check if trying to take a screenshot fails when disabled by policy.
2394 TestScreenshotFile(false);
2395 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2398 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2399 // Set up the mock observer.
2400 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2401 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2402 audio_handler->AddAudioObserver(test_observer.get());
2404 bool prior_state = audio_handler->IsOutputMuted();
2405 // Make sure the audio is not muted and then toggle the policy and observe
2406 // if the output mute changed event is fired.
2407 audio_handler->SetOutputMute(false);
2408 EXPECT_FALSE(audio_handler->IsOutputMuted());
2409 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2410 PolicyMap policies;
2411 policies.Set(key::kAudioOutputAllowed,
2412 POLICY_LEVEL_MANDATORY,
2413 POLICY_SCOPE_USER,
2414 new base::FundamentalValue(false),
2415 NULL);
2416 UpdateProviderPolicy(policies);
2417 EXPECT_TRUE(audio_handler->IsOutputMuted());
2418 // This should not change the state now and should not trigger output mute
2419 // changed event.
2420 audio_handler->SetOutputMute(false);
2421 EXPECT_TRUE(audio_handler->IsOutputMuted());
2422 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2424 // Toggle back and observe if the output mute changed event is fired.
2425 policies.Set(key::kAudioOutputAllowed,
2426 POLICY_LEVEL_MANDATORY,
2427 POLICY_SCOPE_USER,
2428 new base::FundamentalValue(true),
2429 NULL);
2430 UpdateProviderPolicy(policies);
2431 EXPECT_FALSE(audio_handler->IsOutputMuted());
2432 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2433 audio_handler->SetOutputMute(true);
2434 EXPECT_TRUE(audio_handler->IsOutputMuted());
2435 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2436 // Revert the prior state.
2437 audio_handler->SetOutputMute(prior_state);
2438 audio_handler->RemoveAudioObserver(test_observer.get());
2441 // Disabled, see http://crbug.com/315308.
2442 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2443 // Indicate that the session started 2 hours ago and no user activity has
2444 // occurred yet.
2445 g_browser_process->local_state()->SetInt64(
2446 prefs::kSessionStartTime,
2447 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2448 .ToInternalValue());
2451 // Disabled, see http://crbug.com/315308.
2452 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2453 content::MockNotificationObserver observer;
2454 content::NotificationRegistrar registrar;
2455 registrar.Add(&observer,
2456 chrome::NOTIFICATION_APP_TERMINATING,
2457 content::NotificationService::AllSources());
2459 // Set the session length limit to 3 hours. Verify that the session is not
2460 // terminated.
2461 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2462 .Times(0);
2463 PolicyMap policies;
2464 policies.Set(key::kSessionLengthLimit,
2465 POLICY_LEVEL_MANDATORY,
2466 POLICY_SCOPE_USER,
2467 new base::FundamentalValue(kThreeHoursInMs),
2468 NULL);
2469 UpdateProviderPolicy(policies);
2470 base::RunLoop().RunUntilIdle();
2471 Mock::VerifyAndClearExpectations(&observer);
2473 // Decrease the session length limit to 1 hour. Verify that the session is
2474 // terminated immediately.
2475 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2476 policies.Set(key::kSessionLengthLimit,
2477 POLICY_LEVEL_MANDATORY,
2478 POLICY_SCOPE_USER,
2479 new base::FundamentalValue(kOneHourInMs),
2480 NULL);
2481 UpdateProviderPolicy(policies);
2482 base::RunLoop().RunUntilIdle();
2483 Mock::VerifyAndClearExpectations(&observer);
2486 // Disabled, see http://crbug.com/315308.
2487 IN_PROC_BROWSER_TEST_F(PolicyTest,
2488 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2489 // Indicate that the session started 2 hours ago and no user activity has
2490 // occurred yet.
2491 g_browser_process->local_state()->SetInt64(
2492 prefs::kSessionStartTime,
2493 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2494 .ToInternalValue());
2497 // Disabled, see http://crbug.com/315308.
2498 IN_PROC_BROWSER_TEST_F(PolicyTest,
2499 DISABLED_WaitForInitialUserActivityUsatisfied) {
2500 content::MockNotificationObserver observer;
2501 content::NotificationRegistrar registrar;
2502 registrar.Add(&observer,
2503 chrome::NOTIFICATION_APP_TERMINATING,
2504 content::NotificationService::AllSources());
2506 // Require initial user activity.
2507 PolicyMap policies;
2508 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2509 POLICY_SCOPE_USER,
2510 new base::FundamentalValue(true),
2511 NULL);
2512 UpdateProviderPolicy(policies);
2513 base::RunLoop().RunUntilIdle();
2515 // Set the session length limit to 1 hour. Verify that the session is not
2516 // terminated.
2517 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2518 .Times(0);
2519 policies.Set(key::kSessionLengthLimit,
2520 POLICY_LEVEL_MANDATORY,
2521 POLICY_SCOPE_USER,
2522 new base::FundamentalValue(kOneHourInMs),
2523 NULL);
2524 UpdateProviderPolicy(policies);
2525 base::RunLoop().RunUntilIdle();
2526 Mock::VerifyAndClearExpectations(&observer);
2529 // Disabled, see http://crbug.com/315308.
2530 IN_PROC_BROWSER_TEST_F(PolicyTest,
2531 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2532 // Indicate that initial user activity in this session occurred 2 hours ago.
2533 g_browser_process->local_state()->SetInt64(
2534 prefs::kSessionStartTime,
2535 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2536 .ToInternalValue());
2537 g_browser_process->local_state()->SetBoolean(
2538 prefs::kSessionUserActivitySeen,
2539 true);
2542 // Disabled, see http://crbug.com/315308.
2543 IN_PROC_BROWSER_TEST_F(PolicyTest,
2544 DISABLED_WaitForInitialUserActivitySatisfied) {
2545 content::MockNotificationObserver observer;
2546 content::NotificationRegistrar registrar;
2547 registrar.Add(&observer,
2548 chrome::NOTIFICATION_APP_TERMINATING,
2549 content::NotificationService::AllSources());
2551 // Require initial user activity and set the session length limit to 3 hours.
2552 // Verify that the session is not terminated.
2553 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2554 .Times(0);
2555 PolicyMap policies;
2556 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2557 POLICY_SCOPE_USER,
2558 new base::FundamentalValue(true),
2559 NULL);
2560 policies.Set(key::kSessionLengthLimit,
2561 POLICY_LEVEL_MANDATORY,
2562 POLICY_SCOPE_USER,
2563 new base::FundamentalValue(kThreeHoursInMs),
2564 NULL);
2565 UpdateProviderPolicy(policies);
2566 base::RunLoop().RunUntilIdle();
2567 Mock::VerifyAndClearExpectations(&observer);
2569 // Decrease the session length limit to 1 hour. Verify that the session is
2570 // terminated immediately.
2571 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2572 policies.Set(key::kSessionLengthLimit,
2573 POLICY_LEVEL_MANDATORY,
2574 POLICY_SCOPE_USER,
2575 new base::FundamentalValue(kOneHourInMs),
2576 NULL);
2577 UpdateProviderPolicy(policies);
2578 base::RunLoop().RunUntilIdle();
2579 Mock::VerifyAndClearExpectations(&observer);
2582 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2583 // Verifies that the large cursor accessibility feature can be controlled
2584 // through policy.
2585 chromeos::AccessibilityManager* accessibility_manager =
2586 chromeos::AccessibilityManager::Get();
2588 // Manually enable the large cursor.
2589 accessibility_manager->EnableLargeCursor(true);
2590 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2592 // Verify that policy overrides the manual setting.
2593 PolicyMap policies;
2594 policies.Set(key::kLargeCursorEnabled,
2595 POLICY_LEVEL_MANDATORY,
2596 POLICY_SCOPE_USER,
2597 new base::FundamentalValue(false),
2598 NULL);
2599 UpdateProviderPolicy(policies);
2600 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2602 // Verify that the large cursor cannot be enabled manually anymore.
2603 accessibility_manager->EnableLargeCursor(true);
2604 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2607 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2608 // Verifies that the spoken feedback accessibility feature can be controlled
2609 // through policy.
2610 chromeos::AccessibilityManager* accessibility_manager =
2611 chromeos::AccessibilityManager::Get();
2613 // Manually enable spoken feedback.
2614 accessibility_manager->EnableSpokenFeedback(
2615 true, ash::A11Y_NOTIFICATION_NONE);
2616 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2618 // Verify that policy overrides the manual setting.
2619 PolicyMap policies;
2620 policies.Set(key::kSpokenFeedbackEnabled,
2621 POLICY_LEVEL_MANDATORY,
2622 POLICY_SCOPE_USER,
2623 new base::FundamentalValue(false),
2624 NULL);
2625 UpdateProviderPolicy(policies);
2626 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2628 // Verify that spoken feedback cannot be enabled manually anymore.
2629 accessibility_manager->EnableSpokenFeedback(
2630 true, ash::A11Y_NOTIFICATION_NONE);
2631 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2634 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2635 // Verifies that the high contrast mode accessibility feature can be
2636 // controlled through policy.
2637 chromeos::AccessibilityManager* accessibility_manager =
2638 chromeos::AccessibilityManager::Get();
2640 // Manually enable high contrast mode.
2641 accessibility_manager->EnableHighContrast(true);
2642 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2644 // Verify that policy overrides the manual setting.
2645 PolicyMap policies;
2646 policies.Set(key::kHighContrastEnabled,
2647 POLICY_LEVEL_MANDATORY,
2648 POLICY_SCOPE_USER,
2649 new base::FundamentalValue(false),
2650 NULL);
2651 UpdateProviderPolicy(policies);
2652 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2654 // Verify that high contrast mode cannot be enabled manually anymore.
2655 accessibility_manager->EnableHighContrast(true);
2656 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2659 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2660 // Verifies that the screen magnifier can be disabled through policy.
2661 chromeos::MagnificationManager* magnification_manager =
2662 chromeos::MagnificationManager::Get();
2664 // Manually enable the full-screen magnifier.
2665 magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL);
2666 magnification_manager->SetMagnifierEnabled(true);
2667 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2668 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2670 // Verify that policy overrides the manual setting.
2671 PolicyMap policies;
2672 policies.Set(key::kScreenMagnifierType,
2673 POLICY_LEVEL_MANDATORY,
2674 POLICY_SCOPE_USER,
2675 new base::FundamentalValue(0),
2676 NULL);
2677 UpdateProviderPolicy(policies);
2678 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2680 // Verify that the screen magnifier cannot be enabled manually anymore.
2681 magnification_manager->SetMagnifierEnabled(true);
2682 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2685 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2686 // Verifies that the full-screen magnifier can be enabled through policy.
2687 chromeos::MagnificationManager* magnification_manager =
2688 chromeos::MagnificationManager::Get();
2690 // Verify that the screen magnifier is initially disabled.
2691 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2693 // Verify that policy can enable the full-screen magnifier.
2694 PolicyMap policies;
2695 policies.Set(key::kScreenMagnifierType,
2696 POLICY_LEVEL_MANDATORY,
2697 POLICY_SCOPE_USER,
2698 new base::FundamentalValue(ash::MAGNIFIER_FULL),
2699 NULL);
2700 UpdateProviderPolicy(policies);
2701 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2702 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2704 // Verify that the screen magnifier cannot be disabled manually anymore.
2705 magnification_manager->SetMagnifierEnabled(false);
2706 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2709 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
2710 // Verifies that the on-screen keyboard accessibility feature can be
2711 // controlled through policy.
2712 chromeos::AccessibilityManager* accessibility_manager =
2713 chromeos::AccessibilityManager::Get();
2715 // Manually enable the on-screen keyboard.
2716 accessibility_manager->EnableVirtualKeyboard(true);
2717 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2719 // Verify that policy overrides the manual setting.
2720 PolicyMap policies;
2721 policies.Set(key::kVirtualKeyboardEnabled,
2722 POLICY_LEVEL_MANDATORY,
2723 POLICY_SCOPE_USER,
2724 new base::FundamentalValue(false),
2725 NULL);
2726 UpdateProviderPolicy(policies);
2727 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2729 // Verify that the on-screen keyboard cannot be enabled manually anymore.
2730 accessibility_manager->EnableVirtualKeyboard(true);
2731 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2734 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2735 // Verify keyboard disabled by default.
2736 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2737 // Verify keyboard can be toggled by default.
2738 keyboard::SetTouchKeyboardEnabled(true);
2739 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2740 keyboard::SetTouchKeyboardEnabled(false);
2741 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2743 // Verify enabling the policy takes effect immediately and that that user
2744 // cannot disable the keyboard..
2745 PolicyMap policies;
2746 policies.Set(key::kTouchVirtualKeyboardEnabled,
2747 POLICY_LEVEL_MANDATORY,
2748 POLICY_SCOPE_USER,
2749 new base::FundamentalValue(true),
2750 NULL);
2751 UpdateProviderPolicy(policies);
2752 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2753 keyboard::SetTouchKeyboardEnabled(false);
2754 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2756 // Verify that disabling the policy takes effect immediately and that the user
2757 // cannot enable the keyboard.
2758 policies.Set(key::kTouchVirtualKeyboardEnabled,
2759 POLICY_LEVEL_MANDATORY,
2760 POLICY_SCOPE_USER,
2761 new base::FundamentalValue(false),
2762 NULL);
2763 UpdateProviderPolicy(policies);
2764 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2765 keyboard::SetTouchKeyboardEnabled(true);
2766 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2769 #endif
2771 namespace {
2773 static const char* kRestoredURLs[] = {
2774 "http://aaa.com/empty.html",
2775 "http://bbb.com/empty.html",
2778 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2779 return s.empty() || s[0] != '-';
2782 } // namespace
2784 // Similar to PolicyTest but allows setting policies before the browser is
2785 // created. Each test parameter is a method that sets up the early policies
2786 // and stores the expected startup URLs in |expected_urls_|.
2787 class RestoreOnStartupPolicyTest
2788 : public PolicyTest,
2789 public testing::WithParamInterface<
2790 void (RestoreOnStartupPolicyTest::*)(void)> {
2791 public:
2792 RestoreOnStartupPolicyTest() {}
2793 virtual ~RestoreOnStartupPolicyTest() {}
2795 #if defined(OS_CHROMEOS)
2796 virtual void SetUpCommandLine(CommandLine* command_line) override {
2797 // TODO(nkostylev): Investigate if we can remove this switch.
2798 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2799 PolicyTest::SetUpCommandLine(command_line);
2801 #endif
2803 virtual void SetUpInProcessBrowserTestFixture() override {
2804 PolicyTest::SetUpInProcessBrowserTestFixture();
2805 // Set early policies now, before the browser is created.
2806 (this->*(GetParam()))();
2808 // Remove the non-switch arguments, so that session restore kicks in for
2809 // these tests.
2810 CommandLine* command_line = CommandLine::ForCurrentProcess();
2811 CommandLine::StringVector argv = command_line->argv();
2812 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2813 argv.end());
2814 command_line->InitFromArgv(argv);
2815 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2816 command_line->argv().begin()));
2819 virtual void SetUpOnMainThread() override {
2820 BrowserThread::PostTask(
2821 BrowserThread::IO,
2822 FROM_HERE,
2823 base::Bind(
2824 RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
2827 void HomepageIsNotNTP() {
2828 // Verifies that policy can set the startup pages to the homepage, when
2829 // the homepage is not the NTP.
2830 PolicyMap policies;
2831 policies.Set(
2832 key::kRestoreOnStartup,
2833 POLICY_LEVEL_MANDATORY,
2834 POLICY_SCOPE_USER,
2835 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2836 NULL);
2837 policies.Set(key::kHomepageIsNewTabPage,
2838 POLICY_LEVEL_MANDATORY,
2839 POLICY_SCOPE_USER,
2840 new base::FundamentalValue(false),
2841 NULL);
2842 policies.Set(key::kHomepageLocation,
2843 POLICY_LEVEL_MANDATORY,
2844 POLICY_SCOPE_USER,
2845 new base::StringValue(kRestoredURLs[1]),
2846 NULL);
2847 provider_.UpdateChromePolicy(policies);
2849 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2852 void HomepageIsNTP() {
2853 // Verifies that policy can set the startup pages to the homepage, when
2854 // the homepage is the NTP.
2855 PolicyMap policies;
2856 policies.Set(
2857 key::kRestoreOnStartup,
2858 POLICY_LEVEL_MANDATORY,
2859 POLICY_SCOPE_USER,
2860 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
2861 NULL);
2862 policies.Set(key::kHomepageIsNewTabPage,
2863 POLICY_LEVEL_MANDATORY,
2864 POLICY_SCOPE_USER,
2865 new base::FundamentalValue(true),
2866 NULL);
2867 provider_.UpdateChromePolicy(policies);
2869 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2872 void ListOfURLs() {
2873 // Verifies that policy can set the startup pages to a list of URLs.
2874 base::ListValue urls;
2875 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2876 urls.Append(new base::StringValue(kRestoredURLs[i]));
2877 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2879 PolicyMap policies;
2880 policies.Set(key::kRestoreOnStartup,
2881 POLICY_LEVEL_MANDATORY,
2882 POLICY_SCOPE_USER,
2883 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
2884 NULL);
2885 policies.Set(
2886 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2887 urls.DeepCopy(), NULL);
2888 provider_.UpdateChromePolicy(policies);
2891 void NTP() {
2892 // Verifies that policy can set the startup page to the NTP.
2893 PolicyMap policies;
2894 policies.Set(
2895 key::kRestoreOnStartup,
2896 POLICY_LEVEL_MANDATORY,
2897 POLICY_SCOPE_USER,
2898 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
2899 NULL);
2900 provider_.UpdateChromePolicy(policies);
2901 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2904 void Last() {
2905 // Verifies that policy can set the startup pages to the last session.
2906 PolicyMap policies;
2907 policies.Set(key::kRestoreOnStartup,
2908 POLICY_LEVEL_MANDATORY,
2909 POLICY_SCOPE_USER,
2910 new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
2911 NULL);
2912 provider_.UpdateChromePolicy(policies);
2913 // This should restore the tabs opened at PRE_RunTest below.
2914 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2915 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2918 std::vector<GURL> expected_urls_;
2921 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2922 // Open some tabs to verify if they are restored after the browser restarts.
2923 // Most policy settings override this, except kPrefValueLast which enforces
2924 // a restore.
2925 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2926 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2927 content::WindowedNotificationObserver observer(
2928 content::NOTIFICATION_LOAD_STOP,
2929 content::NotificationService::AllSources());
2930 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2931 ui::PAGE_TRANSITION_LINK);
2932 observer.Wait();
2936 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2937 #if defined(OS_WIN) && defined(USE_ASH)
2938 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2939 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2940 return;
2941 #endif
2943 TabStripModel* model = browser()->tab_strip_model();
2944 int size = static_cast<int>(expected_urls_.size());
2945 EXPECT_EQ(size, model->count());
2946 for (int i = 0; i < size && i < model->count(); ++i) {
2947 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2951 INSTANTIATE_TEST_CASE_P(
2952 RestoreOnStartupPolicyTestInstance,
2953 RestoreOnStartupPolicyTest,
2954 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2955 &RestoreOnStartupPolicyTest::HomepageIsNTP,
2956 &RestoreOnStartupPolicyTest::ListOfURLs,
2957 &RestoreOnStartupPolicyTest::NTP,
2958 &RestoreOnStartupPolicyTest::Last));
2960 // Similar to PolicyTest but sets a couple of policies before the browser is
2961 // started.
2962 class PolicyStatisticsCollectorTest : public PolicyTest {
2963 public:
2964 PolicyStatisticsCollectorTest() {}
2965 virtual ~PolicyStatisticsCollectorTest() {}
2967 virtual void SetUpInProcessBrowserTestFixture() override {
2968 PolicyTest::SetUpInProcessBrowserTestFixture();
2969 PolicyMap policies;
2970 policies.Set(key::kShowHomeButton,
2971 POLICY_LEVEL_MANDATORY,
2972 POLICY_SCOPE_USER,
2973 new base::FundamentalValue(true),
2974 NULL);
2975 policies.Set(key::kBookmarkBarEnabled,
2976 POLICY_LEVEL_MANDATORY,
2977 POLICY_SCOPE_USER,
2978 new base::FundamentalValue(false),
2979 NULL);
2980 policies.Set(key::kHomepageLocation,
2981 POLICY_LEVEL_MANDATORY,
2982 POLICY_SCOPE_USER,
2983 new base::StringValue("http://chromium.org"),
2984 NULL);
2985 provider_.UpdateChromePolicy(policies);
2989 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2990 // Verifies that policy usage histograms are collected at startup.
2992 // BrowserPolicyConnector::Init() has already been called. Make sure the
2993 // CompleteInitialization() task has executed as well.
2994 content::RunAllPendingInMessageLoop();
2996 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
2997 std::string(url::kStandardSchemeSeparator) +
2998 std::string(content::kChromeUIHistogramHost));
2999 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3000 content::WebContents* contents =
3001 browser()->tab_strip_model()->GetActiveWebContents();
3002 std::string text;
3003 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3004 contents,
3005 "var nodes = document.querySelectorAll('body > pre');"
3006 "var result = '';"
3007 "for (var i = 0; i < nodes.length; ++i) {"
3008 " var text = nodes[i].innerHTML;"
3009 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3010 " result = text;"
3011 " break;"
3012 " }"
3014 "domAutomationController.send(result);",
3015 &text));
3016 ASSERT_FALSE(text.empty());
3017 const std::string kExpectedLabel =
3018 "Histogram: Enterprise.Policies recorded 3 samples";
3019 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3020 // HomepageLocation has policy ID 1.
3021 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
3022 // ShowHomeButton has policy ID 35.
3023 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
3024 // BookmarkBarEnabled has policy ID 82.
3025 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
3028 class MediaStreamDevicesControllerBrowserTest
3029 : public PolicyTest,
3030 public testing::WithParamInterface<bool> {
3031 public:
3032 MediaStreamDevicesControllerBrowserTest()
3033 : request_url_allowed_via_whitelist_(false) {
3034 policy_value_ = GetParam();
3036 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3038 // Configure a given policy map.
3039 // The |policy_name| is the name of either the audio or video capture allow
3040 // policy and must never be NULL.
3041 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3042 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3043 // and the whitelist policy is set to contain either the |allow_rule| (if
3044 // non-NULL) or an "allow all" wildcard.
3045 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3046 const char* whitelist_policy,
3047 const char* allow_rule) {
3048 policies->Set(policy_name,
3049 POLICY_LEVEL_MANDATORY,
3050 POLICY_SCOPE_USER,
3051 new base::FundamentalValue(policy_value_),
3052 NULL);
3054 if (whitelist_policy) {
3055 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3056 // in the media exceptions UI.
3057 // See discussion here: https://codereview.chromium.org/15738004/
3058 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
3060 // Add an entry to the whitelist that allows the specified URL regardless
3061 // of the setting of kAudioCapturedAllowed.
3062 request_url_ = GURL("http://www.example.com/foo");
3063 base::ListValue* list = new base::ListValue();
3064 if (allow_rule) {
3065 list->AppendString(allow_rule);
3066 request_url_allowed_via_whitelist_ = true;
3067 } else {
3068 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3069 // We should ignore all wildcard entries in the whitelist, so even
3070 // though we've added an entry, it should be ignored and our expectation
3071 // is that the request has not been allowed via the whitelist.
3072 request_url_allowed_via_whitelist_ = false;
3074 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3075 POLICY_SCOPE_USER, list, NULL);
3079 void Accept(const content::MediaStreamDevices& devices,
3080 content::MediaStreamRequestResult result,
3081 scoped_ptr<content::MediaStreamUI> ui) {
3082 if (policy_value_ || request_url_allowed_via_whitelist_) {
3083 ASSERT_EQ(1U, devices.size());
3084 ASSERT_EQ("fake_dev", devices[0].id);
3085 } else {
3086 ASSERT_EQ(0U, devices.size());
3090 void FinishAudioTest() {
3091 content::MediaStreamRequest request(0, 0, 0,
3092 request_url_.GetOrigin(), false,
3093 content::MEDIA_DEVICE_ACCESS,
3094 std::string(), std::string(),
3095 content::MEDIA_DEVICE_AUDIO_CAPTURE,
3096 content::MEDIA_NO_SERVICE);
3097 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3098 // and microphone permissions at the same time.
3099 MediaStreamDevicesController controller(
3100 browser()->tab_strip_model()->GetActiveWebContents(), request,
3101 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3102 controller.Accept(false);
3104 base::MessageLoop::current()->QuitWhenIdle();
3107 void FinishVideoTest() {
3108 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3109 // and microphone permissions at the same time.
3110 content::MediaStreamRequest request(0, 0, 0,
3111 request_url_.GetOrigin(), false,
3112 content::MEDIA_DEVICE_ACCESS,
3113 std::string(),
3114 std::string(),
3115 content::MEDIA_NO_SERVICE,
3116 content::MEDIA_DEVICE_VIDEO_CAPTURE);
3117 MediaStreamDevicesController controller(
3118 browser()->tab_strip_model()->GetActiveWebContents(), request,
3119 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3120 controller.Accept(false);
3122 base::MessageLoop::current()->QuitWhenIdle();
3125 bool policy_value_;
3126 bool request_url_allowed_via_whitelist_;
3127 GURL request_url_;
3128 static const char kExampleRequestPattern[];
3131 // static
3132 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3133 "http://[*.]example.com/";
3135 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3136 AudioCaptureAllowed) {
3137 content::MediaStreamDevices audio_devices;
3138 content::MediaStreamDevice fake_audio_device(
3139 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3140 audio_devices.push_back(fake_audio_device);
3142 PolicyMap policies;
3143 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3144 UpdateProviderPolicy(policies);
3146 content::BrowserThread::PostTaskAndReply(
3147 content::BrowserThread::IO, FROM_HERE,
3148 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3149 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3150 audio_devices),
3151 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3152 this));
3154 base::MessageLoop::current()->Run();
3157 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3158 AudioCaptureAllowedUrls) {
3159 content::MediaStreamDevices audio_devices;
3160 content::MediaStreamDevice fake_audio_device(
3161 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3162 audio_devices.push_back(fake_audio_device);
3164 const char* allow_pattern[] = {
3165 kExampleRequestPattern,
3166 // This will set an allow-all policy whitelist. Since we do not allow
3167 // setting an allow-all entry in the whitelist, this entry should be ignored
3168 // and therefore the request should be denied.
3169 NULL,
3172 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3173 PolicyMap policies;
3174 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3175 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3176 UpdateProviderPolicy(policies);
3178 content::BrowserThread::PostTaskAndReply(
3179 content::BrowserThread::IO, FROM_HERE,
3180 base::Bind(
3181 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3182 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3183 audio_devices),
3184 base::Bind(
3185 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3186 this));
3188 base::MessageLoop::current()->Run();
3192 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3193 VideoCaptureAllowed) {
3194 content::MediaStreamDevices video_devices;
3195 content::MediaStreamDevice fake_video_device(
3196 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3197 video_devices.push_back(fake_video_device);
3199 PolicyMap policies;
3200 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3201 UpdateProviderPolicy(policies);
3203 content::BrowserThread::PostTaskAndReply(
3204 content::BrowserThread::IO, FROM_HERE,
3205 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3206 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3207 video_devices),
3208 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3209 this));
3211 base::MessageLoop::current()->Run();
3214 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3215 VideoCaptureAllowedUrls) {
3216 content::MediaStreamDevices video_devices;
3217 content::MediaStreamDevice fake_video_device(
3218 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3219 video_devices.push_back(fake_video_device);
3221 const char* allow_pattern[] = {
3222 kExampleRequestPattern,
3223 // This will set an allow-all policy whitelist. Since we do not allow
3224 // setting an allow-all entry in the whitelist, this entry should be ignored
3225 // and therefore the request should be denied.
3226 NULL,
3229 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3230 PolicyMap policies;
3231 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3232 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3233 UpdateProviderPolicy(policies);
3235 content::BrowserThread::PostTaskAndReply(
3236 content::BrowserThread::IO, FROM_HERE,
3237 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3238 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3239 video_devices),
3240 base::Bind(
3241 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3242 this));
3244 base::MessageLoop::current()->Run();
3248 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3249 MediaStreamDevicesControllerBrowserTest,
3250 testing::Bool());
3252 #if !defined(OS_CHROMEOS)
3253 // Similar to PolicyTest but sets the proper policy before the browser is
3254 // started.
3255 class PolicyVariationsServiceTest : public PolicyTest {
3256 public:
3257 virtual void SetUpInProcessBrowserTestFixture() override {
3258 PolicyTest::SetUpInProcessBrowserTestFixture();
3259 PolicyMap policies;
3260 policies.Set(key::kVariationsRestrictParameter,
3261 POLICY_LEVEL_MANDATORY,
3262 POLICY_SCOPE_USER,
3263 new base::StringValue("restricted"),
3264 NULL);
3265 provider_.UpdateChromePolicy(policies);
3269 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3270 const std::string default_variations_url =
3271 chrome_variations::VariationsService::
3272 GetDefaultVariationsServerURLForTesting();
3274 const GURL url =
3275 chrome_variations::VariationsService::GetVariationsServerURL(
3276 g_browser_process->local_state());
3277 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
3278 std::string value;
3279 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3280 EXPECT_EQ("restricted", value);
3283 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3284 base::ListValue blacklist;
3285 blacklist.Append(new base::StringValue("host.name"));
3286 PolicyMap policies;
3287 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3288 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3289 UpdateProviderPolicy(policies);
3291 PrefService* prefs = browser()->profile()->GetPrefs();
3292 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3293 prefs, "host.name"));
3294 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3295 prefs, "other.host.name"));
3298 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3299 base::ListValue blacklist;
3300 blacklist.Append(new base::StringValue("*"));
3301 PolicyMap policies;
3302 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3303 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3304 UpdateProviderPolicy(policies);
3306 PrefService* prefs = browser()->profile()->GetPrefs();
3307 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3308 prefs, "host.name"));
3309 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3310 prefs, "other.host.name"));
3313 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3314 base::ListValue blacklist;
3315 blacklist.Append(new base::StringValue("*"));
3316 base::ListValue whitelist;
3317 whitelist.Append(new base::StringValue("host.name"));
3318 PolicyMap policies;
3319 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3320 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3321 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3322 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3323 UpdateProviderPolicy(policies);
3325 PrefService* prefs = browser()->profile()->GetPrefs();
3326 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3327 prefs, "host.name"));
3328 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3329 prefs, "other.host.name"));
3332 IN_PROC_BROWSER_TEST_F(PolicyTest,
3333 EnableDeprecatedWebPlatformFeatures_ShowModalDialog) {
3334 base::ListValue enabled_features;
3335 enabled_features.Append(new base::StringValue(
3336 "ShowModalDialog_EffectiveUntil20150430"));
3337 PolicyMap policies;
3338 policies.Set(key::kEnableDeprecatedWebPlatformFeatures,
3339 POLICY_LEVEL_MANDATORY,
3340 POLICY_SCOPE_USER,
3341 enabled_features.DeepCopy(),
3342 NULL);
3343 UpdateProviderPolicy(policies);
3345 // Policy only takes effect on new browsers, not existing browsers, so create
3346 // a new browser.
3347 Browser* browser2 = CreateBrowser(browser()->profile());
3348 ui_test_utils::NavigateToURL(browser2, GURL(url::kAboutBlankURL));
3349 bool result = false;
3350 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3351 browser2->tab_strip_model()->GetActiveWebContents(),
3352 "domAutomationController.send(window.showModalDialog !== undefined);",
3353 &result));
3354 EXPECT_TRUE(result);
3357 #endif // !defined(CHROME_OS)
3359 } // namespace policy