Fire an error if a pref used in the UI is missing once all prefs are fetched.
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blob45f42922be33bba08a1e90f279c3cf1bf4bc0437
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_management_test_util.h"
41 #include "chrome/browser/extensions/extension_service.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/infobars/infobar_service.h"
47 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
48 #include "chrome/browser/media/media_stream_devices_controller.h"
49 #include "chrome/browser/metrics/variations/variations_service.h"
50 #include "chrome/browser/net/prediction_options.h"
51 #include "chrome/browser/net/ssl_config_service_manager.h"
52 #include "chrome/browser/net/url_request_mock_util.h"
53 #include "chrome/browser/plugins/plugin_prefs.h"
54 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
55 #include "chrome/browser/policy/profile_policy_connector.h"
56 #include "chrome/browser/policy/profile_policy_connector_factory.h"
57 #include "chrome/browser/prefs/session_startup_pref.h"
58 #include "chrome/browser/profiles/profile.h"
59 #include "chrome/browser/search/instant_service.h"
60 #include "chrome/browser/search/instant_service_factory.h"
61 #include "chrome/browser/search/search.h"
62 #include "chrome/browser/search_engines/template_url_service_factory.h"
63 #include "chrome/browser/translate/chrome_translate_client.h"
64 #include "chrome/browser/translate/cld_data_harness.h"
65 #include "chrome/browser/translate/cld_data_harness_factory.h"
66 #include "chrome/browser/translate/translate_service.h"
67 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
68 #include "chrome/browser/ui/browser.h"
69 #include "chrome/browser/ui/browser_commands.h"
70 #include "chrome/browser/ui/browser_list.h"
71 #include "chrome/browser/ui/browser_tabstrip.h"
72 #include "chrome/browser/ui/browser_window.h"
73 #include "chrome/browser/ui/host_desktop.h"
74 #include "chrome/browser/ui/location_bar/location_bar.h"
75 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
76 #include "chrome/browser/ui/omnibox/omnibox_view.h"
77 #include "chrome/browser/ui/tabs/tab_strip_model.h"
78 #include "chrome/common/chrome_paths.h"
79 #include "chrome/common/chrome_switches.h"
80 #include "chrome/common/extensions/extension_constants.h"
81 #include "chrome/common/extensions/features/feature_channel.h"
82 #include "chrome/common/pref_names.h"
83 #include "chrome/common/url_constants.h"
84 #include "chrome/grit/generated_resources.h"
85 #include "chrome/test/base/in_process_browser_test.h"
86 #include "chrome/test/base/test_switches.h"
87 #include "chrome/test/base/ui_test_utils.h"
88 #include "components/content_settings/core/common/content_settings.h"
89 #include "components/content_settings/core/common/content_settings_pattern.h"
90 #include "components/infobars/core/infobar.h"
91 #include "components/policy/core/browser/browser_policy_connector.h"
92 #include "components/policy/core/common/external_data_fetcher.h"
93 #include "components/policy/core/common/mock_configuration_policy_provider.h"
94 #include "components/policy/core/common/policy_map.h"
95 #include "components/policy/core/common/policy_pref_names.h"
96 #include "components/policy/core/common/policy_service.h"
97 #include "components/policy/core/common/policy_service_impl.h"
98 #include "components/search_engines/template_url.h"
99 #include "components/search_engines/template_url_service.h"
100 #include "components/translate/core/browser/language_state.h"
101 #include "components/translate/core/browser/translate_infobar_delegate.h"
102 #include "content/public/browser/browser_child_process_host_iterator.h"
103 #include "content/public/browser/browser_context.h"
104 #include "content/public/browser/browser_thread.h"
105 #include "content/public/browser/child_process_data.h"
106 #include "content/public/browser/download_item.h"
107 #include "content/public/browser/download_manager.h"
108 #include "content/public/browser/gpu_data_manager.h"
109 #include "content/public/browser/notification_details.h"
110 #include "content/public/browser/notification_observer.h"
111 #include "content/public/browser/notification_registrar.h"
112 #include "content/public/browser/notification_service.h"
113 #include "content/public/browser/notification_source.h"
114 #include "content/public/browser/notification_types.h"
115 #include "content/public/browser/plugin_service.h"
116 #include "content/public/browser/render_process_host.h"
117 #include "content/public/browser/render_view_host.h"
118 #include "content/public/browser/web_contents.h"
119 #include "content/public/common/content_constants.h"
120 #include "content/public/common/content_paths.h"
121 #include "content/public/common/process_type.h"
122 #include "content/public/common/result_codes.h"
123 #include "content/public/common/url_constants.h"
124 #include "content/public/common/webplugininfo.h"
125 #include "content/public/test/browser_test_utils.h"
126 #include "content/public/test/download_test_observer.h"
127 #include "content/public/test/mock_notification_observer.h"
128 #include "content/public/test/test_navigation_observer.h"
129 #include "content/public/test/test_utils.h"
130 #include "extensions/browser/extension_host.h"
131 #include "extensions/browser/extension_prefs.h"
132 #include "extensions/browser/extension_registry.h"
133 #include "extensions/browser/extension_system.h"
134 #include "extensions/browser/process_manager.h"
135 #include "extensions/browser/test_extension_registry_observer.h"
136 #include "extensions/browser/uninstall_reason.h"
137 #include "extensions/common/constants.h"
138 #include "extensions/common/extension.h"
139 #include "extensions/common/extension_set.h"
140 #include "extensions/common/manifest_handlers/shared_module_info.h"
141 #include "net/base/net_errors.h"
142 #include "net/base/net_util.h"
143 #include "net/base/url_util.h"
144 #include "net/http/http_stream_factory.h"
145 #include "net/ssl/ssl_config.h"
146 #include "net/ssl/ssl_config_service.h"
147 #include "net/test/url_request/url_request_failed_job.h"
148 #include "net/test/url_request/url_request_mock_http_job.h"
149 #include "net/url_request/url_request.h"
150 #include "net/url_request/url_request_filter.h"
151 #include "policy/policy_constants.h"
152 #include "testing/gmock/include/gmock/gmock.h"
153 #include "testing/gtest/include/gtest/gtest.h"
154 #include "third_party/WebKit/public/web/WebInputEvent.h"
155 #include "ui/base/l10n/l10n_util.h"
156 #include "ui/base/page_transition_types.h"
157 #include "ui/base/resource/resource_bundle.h"
158 #include "url/gurl.h"
160 #if defined(OS_CHROMEOS)
161 #include "ash/accelerators/accelerator_controller.h"
162 #include "ash/accelerators/accelerator_table.h"
163 #include "ash/shell.h"
164 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
165 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
166 #include "chrome/browser/profiles/profile_manager.h"
167 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
168 #include "chromeos/audio/cras_audio_handler.h"
169 #include "ui/chromeos/accessibility_types.h"
170 #include "ui/keyboard/keyboard_util.h"
171 #include "ui/snapshot/screenshot_grabber.h"
172 #endif
174 #if !defined(OS_MACOSX)
175 #include "base/basictypes.h"
176 #include "base/compiler_specific.h"
177 #include "chrome/browser/ui/extensions/app_launch_params.h"
178 #include "chrome/browser/ui/extensions/application_launch.h"
179 #include "extensions/browser/app_window/app_window.h"
180 #include "extensions/browser/app_window/app_window_registry.h"
181 #include "extensions/browser/app_window/native_app_window.h"
182 #include "ui/base/window_open_disposition.h"
183 #endif
185 using content::BrowserThread;
186 using net::URLRequestMockHTTPJob;
187 using testing::Mock;
188 using testing::Return;
189 using testing::_;
191 namespace policy {
193 namespace {
195 #if defined(OS_CHROMEOS)
196 const int kOneHourInMs = 60 * 60 * 1000;
197 const int kThreeHoursInMs = 180 * 60 * 1000;
198 #endif
200 const char kURL[] = "http://example.com";
201 const char kCookieValue[] = "converted=true";
202 // Assigned to Philip J. Fry to fix eventually.
203 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
205 const base::FilePath::CharType kTestExtensionsDir[] =
206 FILE_PATH_LITERAL("extensions");
207 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
208 const base::FilePath::CharType kAdBlockCrxName[] =
209 FILE_PATH_LITERAL("adblock.crx");
210 const base::FilePath::CharType kHostedAppCrxName[] =
211 FILE_PATH_LITERAL("hosted_app.crx");
213 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
214 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
215 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
217 const base::FilePath::CharType kGood2CrxManifestName[] =
218 FILE_PATH_LITERAL("good2_update_manifest.xml");
219 const base::FilePath::CharType kGoodV1CrxManifestName[] =
220 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
221 const base::FilePath::CharType kGoodV1CrxName[] =
222 FILE_PATH_LITERAL("good_v1.crx");
223 const base::FilePath::CharType kGoodUnpackedExt[] =
224 FILE_PATH_LITERAL("good_unpacked");
225 const base::FilePath::CharType kAppUnpackedExt[] =
226 FILE_PATH_LITERAL("app");
228 #if !defined(OS_MACOSX)
229 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
230 FILE_PATH_LITERAL("fullscreen_app");
231 #endif // !defined(OS_MACOSX)
233 // Filters requests to the hosts in |urls| and redirects them to the test data
234 // dir through URLRequestMockHTTPJobs.
235 void RedirectHostsToTestData(const char* const urls[], size_t size) {
236 // Map the given hosts to the test data dir.
237 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
238 base::FilePath base_path;
239 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
240 for (size_t i = 0; i < size; ++i) {
241 const GURL url(urls[i]);
242 EXPECT_TRUE(url.is_valid());
243 filter->AddUrlInterceptor(url,
244 URLRequestMockHTTPJob::CreateInterceptor(
245 base_path, BrowserThread::GetBlockingPool()));
249 // Remove filters for requests to the hosts in |urls|.
250 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
251 // Map the given hosts to the test data dir.
252 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
253 for (size_t i = 0; i < size; ++i) {
254 const GURL url(urls[i]);
255 EXPECT_TRUE(url.is_valid());
256 filter->RemoveUrlHandler(url);
260 // Fails requests using ERR_CONNECTION_RESET.
261 net::URLRequestJob* FailedJobFactory(
262 net::URLRequest* request,
263 net::NetworkDelegate* network_delegate,
264 const std::string& scheme) {
265 return new net::URLRequestFailedJob(
266 request, network_delegate, net::ERR_CONNECTION_RESET);
269 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
270 class MakeRequestFail {
271 public:
272 // Sets up the filter on IO thread such that requests to |host| fail.
273 explicit MakeRequestFail(const std::string& host) : host_(host) {
274 BrowserThread::PostTaskAndReply(
275 BrowserThread::IO, FROM_HERE,
276 base::Bind(MakeRequestFailOnIO, host_),
277 base::MessageLoop::QuitClosure());
278 content::RunMessageLoop();
280 ~MakeRequestFail() {
281 BrowserThread::PostTaskAndReply(
282 BrowserThread::IO, FROM_HERE,
283 base::Bind(UndoMakeRequestFailOnIO, host_),
284 base::MessageLoop::QuitClosure());
285 content::RunMessageLoop();
288 private:
289 // Filters requests to the |host| such that they fail. Run on IO thread.
290 static void MakeRequestFailOnIO(const std::string& host) {
291 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
292 filter->AddHostnameHandler("http", host, &FailedJobFactory);
293 filter->AddHostnameHandler("https", host, &FailedJobFactory);
296 // Remove filters for requests to the |host|. Run on IO thread.
297 static void UndoMakeRequestFailOnIO(const std::string& host) {
298 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
299 filter->RemoveHostnameHandler("http", host);
300 filter->RemoveHostnameHandler("https", host);
303 const std::string host_;
306 // Verifies that the given url |spec| can be opened. This assumes that |spec|
307 // points at empty.html in the test data dir.
308 void CheckCanOpenURL(Browser* browser, const char* spec) {
309 GURL url(spec);
310 ui_test_utils::NavigateToURL(browser, url);
311 content::WebContents* contents =
312 browser->tab_strip_model()->GetActiveWebContents();
313 EXPECT_EQ(url, contents->GetURL());
314 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
315 base::string16 title =
316 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
317 EXPECT_NE(title, contents->GetTitle());
320 // Verifies that access to the given url |spec| is blocked.
321 void CheckURLIsBlocked(Browser* browser, const char* spec) {
322 GURL url(spec);
323 ui_test_utils::NavigateToURL(browser, url);
324 content::WebContents* contents =
325 browser->tab_strip_model()->GetActiveWebContents();
326 EXPECT_EQ(url, contents->GetURL());
327 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
328 base::string16 title =
329 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
330 EXPECT_EQ(title, contents->GetTitle());
332 // Verify that the expected error page is being displayed.
333 bool result = false;
334 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
335 contents,
336 "var textContent = document.body.textContent;"
337 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
338 "domAutomationController.send(hasError);",
339 &result));
340 EXPECT_TRUE(result);
343 // Downloads a file named |file| and expects it to be saved to |dir|, which
344 // must be empty.
345 void DownloadAndVerifyFile(
346 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
347 content::DownloadManager* download_manager =
348 content::BrowserContext::GetDownloadManager(browser->profile());
349 content::DownloadTestObserverTerminal observer(
350 download_manager, 1,
351 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
352 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
353 base::FilePath downloaded = dir.Append(file);
354 EXPECT_FALSE(base::PathExists(downloaded));
355 ui_test_utils::NavigateToURL(browser, url);
356 observer.WaitForFinished();
357 EXPECT_EQ(
358 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
359 EXPECT_TRUE(base::PathExists(downloaded));
360 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
361 EXPECT_EQ(file, enumerator.Next().BaseName());
362 EXPECT_EQ(base::FilePath(), enumerator.Next());
365 #if defined(OS_CHROMEOS)
366 int CountScreenshots() {
367 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
368 ProfileManager::GetActiveUserProfile());
369 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
370 false, base::FileEnumerator::FILES,
371 "Screenshot*");
372 int count = 0;
373 while (!enumerator.Next().empty())
374 count++;
375 return count;
377 #endif
379 // Checks if WebGL is enabled in the given WebContents.
380 bool IsWebGLEnabled(content::WebContents* contents) {
381 bool result = false;
382 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
383 contents,
384 "var canvas = document.createElement('canvas');"
385 "var context = canvas.getContext('webgl');"
386 "domAutomationController.send(context != null);",
387 &result));
388 return result;
391 bool IsJavascriptEnabled(content::WebContents* contents) {
392 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
393 contents->GetMainFrame(), "123");
394 int result = 0;
395 if (!value->GetAsInteger(&result))
396 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
397 return result == 123;
400 bool IsNetworkPredictionEnabled(PrefService* prefs) {
401 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs);
404 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
405 const std::vector<content::WebPluginInfo>& in) {
406 *out = in;
407 base::MessageLoop::current()->QuitWhenIdle();
410 template<typename T>
411 void CopyValueAndQuit(T* out, T in) {
412 *out = in;
413 base::MessageLoop::current()->QuitWhenIdle();
416 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
417 content::PluginService* service = content::PluginService::GetInstance();
418 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
419 content::RunMessageLoop();
422 const content::WebPluginInfo* GetFlashPlugin(
423 const std::vector<content::WebPluginInfo>& plugins) {
424 const content::WebPluginInfo* flash = NULL;
425 for (size_t i = 0; i < plugins.size(); ++i) {
426 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
427 flash = &plugins[i];
428 break;
431 #if defined(OFFICIAL_BUILD)
432 // Official builds bundle Flash.
433 EXPECT_TRUE(flash);
434 #else
435 if (!flash)
436 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
437 #endif
438 return flash;
441 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
442 const content::WebPluginInfo* plugin,
443 bool enabled) {
444 bool ok = false;
445 plugin_prefs->EnablePlugin(enabled, plugin->path,
446 base::Bind(CopyValueAndQuit<bool>, &ok));
447 content::RunMessageLoop();
448 return ok;
451 int CountPluginsOnIOThread() {
452 int count = 0;
453 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
454 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
455 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
456 count++;
459 return count;
462 int CountPlugins() {
463 int count = -1;
464 BrowserThread::PostTaskAndReplyWithResult(
465 BrowserThread::IO, FROM_HERE,
466 base::Bind(CountPluginsOnIOThread),
467 base::Bind(CopyValueAndQuit<int>, &count));
468 content::RunMessageLoop();
469 EXPECT_GE(count, 0);
470 return count;
473 void FlushBlacklistPolicy() {
474 // Updates of the URLBlacklist are done on IO, after building the blacklist
475 // on the blocking pool, which is initiated from IO.
476 content::RunAllPendingInMessageLoop(BrowserThread::IO);
477 BrowserThread::GetBlockingPool()->FlushForTesting();
478 content::RunAllPendingInMessageLoop(BrowserThread::IO);
481 bool ContainsVisibleElement(content::WebContents* contents,
482 const std::string& id) {
483 bool result;
484 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
485 contents,
486 "var elem = document.getElementById('" + id + "');"
487 "domAutomationController.send(!!elem && !elem.hidden);",
488 &result));
489 return result;
492 #if defined(OS_CHROMEOS)
493 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
494 public:
495 TestAudioObserver() : output_mute_changed_count_(0) {
498 int output_mute_changed_count() const {
499 return output_mute_changed_count_;
502 ~TestAudioObserver() override {}
504 protected:
505 // chromeos::CrasAudioHandler::AudioObserver overrides.
506 void OnOutputMuteChanged() override { ++output_mute_changed_count_; }
508 private:
509 int output_mute_changed_count_;
511 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
513 #endif
515 // This class waits until either a load stops or the WebContents is destroyed.
516 class WebContentsLoadedOrDestroyedWatcher
517 : public content::WebContentsObserver {
518 public:
519 explicit WebContentsLoadedOrDestroyedWatcher(
520 content::WebContents* web_contents);
521 ~WebContentsLoadedOrDestroyedWatcher() override;
523 // Waits until the WebContents's load is done or until it is destroyed.
524 void Wait();
526 // Overridden WebContentsObserver methods.
527 void WebContentsDestroyed() override;
528 void DidStopLoading() override;
530 private:
531 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
533 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
536 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
537 content::WebContents* web_contents)
538 : content::WebContentsObserver(web_contents),
539 message_loop_runner_(new content::MessageLoopRunner) {
542 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
544 void WebContentsLoadedOrDestroyedWatcher::Wait() {
545 message_loop_runner_->Run();
548 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
549 message_loop_runner_->Quit();
552 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
553 message_loop_runner_->Quit();
556 #if !defined(OS_MACOSX)
558 // Observer used to wait for the creation of a new app window.
559 class TestAddAppWindowObserver
560 : public extensions::AppWindowRegistry::Observer {
561 public:
562 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
563 ~TestAddAppWindowObserver() override;
565 // extensions::AppWindowRegistry::Observer:
566 void OnAppWindowAdded(extensions::AppWindow* app_window) override;
568 extensions::AppWindow* WaitForAppWindow();
570 private:
571 extensions::AppWindowRegistry* registry_; // Not owned.
572 extensions::AppWindow* window_; // Not owned.
573 base::RunLoop run_loop_;
575 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
578 TestAddAppWindowObserver::TestAddAppWindowObserver(
579 extensions::AppWindowRegistry* registry)
580 : registry_(registry), window_(NULL) {
581 registry_->AddObserver(this);
584 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
585 registry_->RemoveObserver(this);
588 void TestAddAppWindowObserver::OnAppWindowAdded(
589 extensions::AppWindow* app_window) {
590 window_ = app_window;
591 run_loop_.Quit();
594 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
595 run_loop_.Run();
596 return window_;
599 #endif
601 } // namespace
603 class PolicyTest : public InProcessBrowserTest {
604 protected:
605 PolicyTest() {}
606 ~PolicyTest() override {}
608 void SetUp() override {
609 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
610 InProcessBrowserTest::SetUp();
613 void SetUpInProcessBrowserTestFixture() override {
614 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
615 EXPECT_CALL(provider_, IsInitializationComplete(_))
616 .WillRepeatedly(Return(true));
617 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
620 void SetUpOnMainThread() override {
621 BrowserThread::PostTask(
622 BrowserThread::IO, FROM_HERE,
623 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
624 if (extension_service()->updater()) {
625 extension_service()->updater()->SetExtensionCacheForTesting(
626 test_extension_cache_.get());
630 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
631 // instead of chrome::DIR_TEST_DATA.
632 void ServeContentTestData() {
633 base::FilePath root_http;
634 PathService::Get(content::DIR_TEST_DATA, &root_http);
635 BrowserThread::PostTaskAndReply(
636 BrowserThread::IO, FROM_HERE,
637 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers, root_http,
638 make_scoped_refptr(BrowserThread::GetBlockingPool())),
639 base::MessageLoop::current()->QuitWhenIdleClosure());
640 content::RunMessageLoop();
643 void SetScreenshotPolicy(bool enabled) {
644 PolicyMap policies;
645 policies.Set(key::kDisableScreenshots,
646 POLICY_LEVEL_MANDATORY,
647 POLICY_SCOPE_USER,
648 new base::FundamentalValue(!enabled),
649 NULL);
650 UpdateProviderPolicy(policies);
653 #if defined(OS_CHROMEOS)
654 class QuitMessageLoopAfterScreenshot : public ui::ScreenshotGrabberObserver {
655 public:
656 void OnScreenshotCompleted(
657 ScreenshotGrabberObserver::Result screenshot_result,
658 const base::FilePath& screenshot_path) override {
659 BrowserThread::PostTaskAndReply(BrowserThread::IO,
660 FROM_HERE,
661 base::Bind(base::DoNothing),
662 base::MessageLoop::QuitClosure());
665 ~QuitMessageLoopAfterScreenshot() override {}
668 void TestScreenshotFile(bool enabled) {
669 // AddObserver is an ash-specific method, so just replace the screenshot
670 // grabber with one we've created here.
671 scoped_ptr<ChromeScreenshotGrabber> chrome_screenshot_grabber(
672 new ChromeScreenshotGrabber);
673 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
674 // is tied to the test instead.
675 chrome_screenshot_grabber->screenshot_grabber()->AddObserver(&observer_);
676 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
677 chrome_screenshot_grabber.Pass());
679 SetScreenshotPolicy(enabled);
680 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
681 ash::TAKE_SCREENSHOT);
683 content::RunMessageLoop();
684 static_cast<ChromeScreenshotGrabber*>(ash::Shell::GetInstance()
685 ->accelerator_controller()
686 ->screenshot_delegate())
687 ->screenshot_grabber()
688 ->RemoveObserver(&observer_);
690 #endif
692 ExtensionService* extension_service() {
693 extensions::ExtensionSystem* system =
694 extensions::ExtensionSystem::Get(browser()->profile());
695 return system->extension_service();
698 const extensions::Extension* InstallExtension(
699 const base::FilePath::StringType& name) {
700 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
701 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
702 scoped_refptr<extensions::CrxInstaller> installer =
703 extensions::CrxInstaller::CreateSilent(extension_service());
704 installer->set_allow_silent_install(true);
705 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
706 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
708 content::WindowedNotificationObserver observer(
709 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
710 content::NotificationService::AllSources());
711 installer->InstallCrx(extension_path);
712 observer.Wait();
713 content::Details<const extensions::Extension> details = observer.details();
714 return details.ptr();
717 const extensions::Extension* LoadUnpackedExtension(
718 const base::FilePath::StringType& name, bool expect_success) {
719 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
720 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
721 scoped_refptr<extensions::UnpackedInstaller> installer =
722 extensions::UnpackedInstaller::Create(extension_service());
723 content::WindowedNotificationObserver observer(
724 expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
725 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
726 content::NotificationService::AllSources());
727 installer->Load(extension_path);
728 observer.Wait();
730 extensions::ExtensionRegistry* registry =
731 extensions::ExtensionRegistry::Get(browser()->profile());
732 for (const scoped_refptr<const extensions::Extension>& extension :
733 registry->enabled_extensions()) {
734 if (extension->path() == extension_path)
735 return extension.get();
737 return NULL;
740 void UninstallExtension(const std::string& id, bool expect_success) {
741 content::WindowedNotificationObserver observer(
742 expect_success
743 ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
744 : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
745 content::NotificationService::AllSources());
746 extension_service()->UninstallExtension(
748 extensions::UNINSTALL_REASON_FOR_TESTING,
749 base::Bind(&base::DoNothing),
750 NULL);
751 observer.Wait();
754 void DisableExtension(const std::string& id) {
755 content::WindowedNotificationObserver observer(
756 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
757 content::NotificationService::AllSources());
758 extension_service()->DisableExtension(id,
759 extensions::Extension::DISABLE_NONE);
760 observer.Wait();
763 void UpdateProviderPolicy(const PolicyMap& policy) {
764 provider_.UpdateChromePolicy(policy);
765 DCHECK(base::MessageLoop::current());
766 base::RunLoop loop;
767 loop.RunUntilIdle();
770 // Sends a mouse click at the given coordinates to the current renderer.
771 void PerformClick(int x, int y) {
772 content::WebContents* contents =
773 browser()->tab_strip_model()->GetActiveWebContents();
774 blink::WebMouseEvent click_event;
775 click_event.type = blink::WebInputEvent::MouseDown;
776 click_event.button = blink::WebMouseEvent::ButtonLeft;
777 click_event.clickCount = 1;
778 click_event.x = x;
779 click_event.y = y;
780 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
781 click_event.type = blink::WebInputEvent::MouseUp;
782 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
785 MockConfigurationPolicyProvider provider_;
786 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
787 #if defined(OS_CHROMEOS)
788 QuitMessageLoopAfterScreenshot observer_;
789 #endif
792 #if defined(OS_WIN)
793 // This policy only exists on Windows.
795 // Sets the locale policy before the browser is started.
796 class LocalePolicyTest : public PolicyTest {
797 public:
798 LocalePolicyTest() {}
799 virtual ~LocalePolicyTest() {}
801 virtual void SetUpInProcessBrowserTestFixture() override {
802 PolicyTest::SetUpInProcessBrowserTestFixture();
803 PolicyMap policies;
804 policies.Set(key::kApplicationLocaleValue,
805 POLICY_LEVEL_MANDATORY,
806 POLICY_SCOPE_USER,
807 new base::StringValue("fr"),
808 NULL);
809 provider_.UpdateChromePolicy(policies);
810 // The "en-US" ResourceBundle is always loaded before this step for tests,
811 // but in this test we want the browser to load the bundle as it
812 // normally would.
813 ResourceBundle::CleanupSharedInstance();
817 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
818 // Verifies that the default locale can be overridden with policy.
819 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
820 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
821 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
822 base::string16 title;
823 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
824 EXPECT_EQ(french_title, title);
826 // Make sure this is really French and differs from the English title.
827 std::string loaded =
828 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
829 EXPECT_EQ("en-US", loaded);
830 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
831 EXPECT_NE(french_title, english_title);
833 #endif
835 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
836 #if defined(OS_WIN) && defined(USE_ASH)
837 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
838 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
839 switches::kAshBrowserTests))
840 return;
841 #endif
843 // Verifies that the bookmarks bar can be forced to always or never show up.
845 // Test starts in about:blank.
846 PrefService* prefs = browser()->profile()->GetPrefs();
847 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
848 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
849 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
851 PolicyMap policies;
852 policies.Set(key::kBookmarkBarEnabled,
853 POLICY_LEVEL_MANDATORY,
854 POLICY_SCOPE_USER,
855 new base::FundamentalValue(true),
856 NULL);
857 UpdateProviderPolicy(policies);
858 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
859 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
860 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
862 // The NTP has special handling of the bookmark bar.
863 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
864 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
866 policies.Set(key::kBookmarkBarEnabled,
867 POLICY_LEVEL_MANDATORY,
868 POLICY_SCOPE_USER,
869 new base::FundamentalValue(false),
870 NULL);
871 UpdateProviderPolicy(policies);
872 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
873 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
874 // The bookmark bar is hidden in the NTP when disabled by policy.
875 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
877 policies.Clear();
878 UpdateProviderPolicy(policies);
879 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
880 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
881 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
882 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
885 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
886 // Verifies that cookies are deleted on shutdown. This test is split in 3
887 // parts because it spans 2 browser restarts.
889 Profile* profile = browser()->profile();
890 GURL url(kURL);
891 // No cookies at startup.
892 EXPECT_TRUE(content::GetCookies(profile, url).empty());
893 // Set a cookie now.
894 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
895 EXPECT_TRUE(content::SetCookie(profile, url, value));
896 // Verify it was set.
897 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
900 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
901 // Verify that the cookie persists across restarts.
902 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
903 // Now set the policy and the cookie should be gone after another restart.
904 PolicyMap policies;
905 policies.Set(key::kDefaultCookiesSetting,
906 POLICY_LEVEL_MANDATORY,
907 POLICY_SCOPE_USER,
908 new base::FundamentalValue(4),
909 NULL);
910 UpdateProviderPolicy(policies);
913 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
914 // Verify that the cookie is gone.
915 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
918 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
919 MakeRequestFail make_request_fail("search.example");
921 // Verifies that a default search is made using the provider configured via
922 // policy. Also checks that default search can be completely disabled.
923 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
924 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
925 const std::string kAlternateURL0(
926 "http://search.example/search#q={searchTerms}");
927 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
928 const std::string kSearchTermsReplacementKey("zekey");
929 const std::string kImageURL("http://test.com/searchbyimage/upload");
930 const std::string kImageURLPostParams(
931 "image_content=content,image_url=http://test.com/test.png");
932 const std::string kNewTabURL("http://search.example/newtab");
934 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
935 browser()->profile());
936 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
937 TemplateURL* default_search = service->GetDefaultSearchProvider();
938 ASSERT_TRUE(default_search);
939 EXPECT_NE(kKeyword, default_search->keyword());
940 EXPECT_NE(kSearchURL, default_search->url());
941 EXPECT_FALSE(
942 default_search->alternate_urls().size() == 2 &&
943 default_search->alternate_urls()[0] == kAlternateURL0 &&
944 default_search->alternate_urls()[1] == kAlternateURL1 &&
945 default_search->search_terms_replacement_key() ==
946 kSearchTermsReplacementKey &&
947 default_search->image_url() == kImageURL &&
948 default_search->image_url_post_params() == kImageURLPostParams &&
949 default_search->new_tab_url() == kNewTabURL);
951 // Override the default search provider using policies.
952 PolicyMap policies;
953 policies.Set(key::kDefaultSearchProviderEnabled,
954 POLICY_LEVEL_MANDATORY,
955 POLICY_SCOPE_USER,
956 new base::FundamentalValue(true),
957 NULL);
958 policies.Set(key::kDefaultSearchProviderKeyword,
959 POLICY_LEVEL_MANDATORY,
960 POLICY_SCOPE_USER,
961 new base::StringValue(kKeyword),
962 NULL);
963 policies.Set(key::kDefaultSearchProviderSearchURL,
964 POLICY_LEVEL_MANDATORY,
965 POLICY_SCOPE_USER,
966 new base::StringValue(kSearchURL),
967 NULL);
968 base::ListValue* alternate_urls = new base::ListValue();
969 alternate_urls->AppendString(kAlternateURL0);
970 alternate_urls->AppendString(kAlternateURL1);
971 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
972 POLICY_SCOPE_USER, alternate_urls, NULL);
973 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
974 POLICY_LEVEL_MANDATORY,
975 POLICY_SCOPE_USER,
976 new base::StringValue(kSearchTermsReplacementKey),
977 NULL);
978 policies.Set(key::kDefaultSearchProviderImageURL,
979 POLICY_LEVEL_MANDATORY,
980 POLICY_SCOPE_USER,
981 new base::StringValue(kImageURL),
982 NULL);
983 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
984 POLICY_LEVEL_MANDATORY,
985 POLICY_SCOPE_USER,
986 new base::StringValue(kImageURLPostParams),
987 NULL);
988 policies.Set(key::kDefaultSearchProviderNewTabURL,
989 POLICY_LEVEL_MANDATORY,
990 POLICY_SCOPE_USER,
991 new base::StringValue(kNewTabURL),
992 NULL);
993 UpdateProviderPolicy(policies);
994 default_search = service->GetDefaultSearchProvider();
995 ASSERT_TRUE(default_search);
996 EXPECT_EQ(kKeyword, default_search->keyword());
997 EXPECT_EQ(kSearchURL, default_search->url());
998 EXPECT_EQ(2U, default_search->alternate_urls().size());
999 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1000 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1001 EXPECT_EQ(kSearchTermsReplacementKey,
1002 default_search->search_terms_replacement_key());
1003 EXPECT_EQ(kImageURL, default_search->image_url());
1004 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
1005 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
1007 // Verify that searching from the omnibox uses kSearchURL.
1008 chrome::FocusLocationBar(browser());
1009 LocationBar* location_bar = browser()->window()->GetLocationBar();
1010 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1011 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1012 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1013 content::WebContents* web_contents =
1014 browser()->tab_strip_model()->GetActiveWebContents();
1015 GURL expected("http://search.example/search?q=stuff+to+search+for");
1016 EXPECT_EQ(expected, web_contents->GetURL());
1018 // Verify that searching from the omnibox can be disabled.
1019 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1020 policies.Set(key::kDefaultSearchProviderEnabled,
1021 POLICY_LEVEL_MANDATORY,
1022 POLICY_SCOPE_USER,
1023 new base::FundamentalValue(false),
1024 NULL);
1025 EXPECT_TRUE(service->GetDefaultSearchProvider());
1026 UpdateProviderPolicy(policies);
1027 EXPECT_FALSE(service->GetDefaultSearchProvider());
1028 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1029 // This means that submitting won't trigger any action.
1030 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1031 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1034 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1035 // Add an individual proxy policy value.
1036 PolicyMap policies;
1037 policies.Set(key::kProxyServerMode,
1038 POLICY_LEVEL_MANDATORY,
1039 POLICY_SCOPE_USER,
1040 new base::FundamentalValue(3),
1041 NULL);
1042 UpdateProviderPolicy(policies);
1044 // It should be removed and replaced with a dictionary.
1045 PolicyMap expected;
1046 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1047 expected_value->SetInteger(key::kProxyServerMode, 3);
1048 expected.Set(key::kProxySettings,
1049 POLICY_LEVEL_MANDATORY,
1050 POLICY_SCOPE_USER,
1051 expected_value.release(),
1052 NULL);
1054 // Check both the browser and the profile.
1055 const PolicyMap& actual_from_browser =
1056 g_browser_process->browser_policy_connector()
1057 ->GetPolicyService()
1058 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1059 EXPECT_TRUE(expected.Equals(actual_from_browser));
1060 const PolicyMap& actual_from_profile =
1061 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1062 ->policy_service()
1063 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1064 EXPECT_TRUE(expected.Equals(actual_from_profile));
1067 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1068 // Makes the requests fail since all we want to check is that the redirection
1069 // is done properly.
1070 MakeRequestFail make_request_fail("google.com");
1072 // Verifies that requests to Google Search engine with the SafeSearch
1073 // enabled set the safe=active&ssui=on parameters at the end of the query.
1074 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1075 browser()->profile());
1076 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1078 // First check that nothing happens.
1079 content::TestNavigationObserver no_safesearch_observer(
1080 browser()->tab_strip_model()->GetActiveWebContents());
1081 chrome::FocusLocationBar(browser());
1082 LocationBar* location_bar = browser()->window()->GetLocationBar();
1083 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1084 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1085 no_safesearch_observer.Wait();
1086 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1087 content::WebContents* web_contents =
1088 browser()->tab_strip_model()->GetActiveWebContents();
1089 GURL expected_without("http://google.com/");
1090 EXPECT_EQ(expected_without, web_contents->GetURL());
1092 PrefService* prefs = browser()->profile()->GetPrefs();
1093 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1094 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1096 // Override the default SafeSearch setting using policies.
1097 PolicyMap policies;
1098 policies.Set(key::kForceSafeSearch,
1099 POLICY_LEVEL_MANDATORY,
1100 POLICY_SCOPE_USER,
1101 new base::FundamentalValue(true),
1102 NULL);
1103 UpdateProviderPolicy(policies);
1105 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1106 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1108 content::TestNavigationObserver safesearch_observer(
1109 browser()->tab_strip_model()->GetActiveWebContents());
1111 // Verify that searching from google.com works.
1112 chrome::FocusLocationBar(browser());
1113 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1114 safesearch_observer.Wait();
1115 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1116 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1117 std::string expected_url("http://google.com/?");
1118 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1119 chrome::kSafeSearchSsuiParameter;
1120 GURL expected_with_parameters(expected_url);
1121 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1124 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1125 MakeRequestFail make_request_fail("search.example");
1127 chrome::EnableQueryExtractionForTesting();
1129 // Verifies that a default search is made using the provider configured via
1130 // policy. Also checks that default search can be completely disabled.
1131 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1132 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1133 const std::string kInstantURL("http://does/not/exist");
1134 const std::string kAlternateURL0(
1135 "https://www.google.com/search#q={searchTerms}");
1136 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1137 const std::string kSearchTermsReplacementKey(
1138 "{google:instantExtendedEnabledKey}");
1140 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1141 browser()->profile());
1142 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1143 TemplateURL* default_search = service->GetDefaultSearchProvider();
1144 ASSERT_TRUE(default_search);
1145 EXPECT_NE(kKeyword, default_search->keyword());
1146 EXPECT_NE(kSearchURL, default_search->url());
1147 EXPECT_NE(kInstantURL, default_search->instant_url());
1148 EXPECT_FALSE(
1149 default_search->alternate_urls().size() == 2 &&
1150 default_search->alternate_urls()[0] == kAlternateURL0 &&
1151 default_search->alternate_urls()[1] == kAlternateURL1);
1153 // Override the default search provider using policies.
1154 PolicyMap policies;
1155 policies.Set(key::kDefaultSearchProviderEnabled,
1156 POLICY_LEVEL_MANDATORY,
1157 POLICY_SCOPE_USER,
1158 new base::FundamentalValue(true),
1159 NULL);
1160 policies.Set(key::kDefaultSearchProviderKeyword,
1161 POLICY_LEVEL_MANDATORY,
1162 POLICY_SCOPE_USER,
1163 new base::StringValue(kKeyword),
1164 NULL);
1165 policies.Set(key::kDefaultSearchProviderSearchURL,
1166 POLICY_LEVEL_MANDATORY,
1167 POLICY_SCOPE_USER,
1168 new base::StringValue(kSearchURL),
1169 NULL);
1170 policies.Set(key::kDefaultSearchProviderInstantURL,
1171 POLICY_LEVEL_MANDATORY,
1172 POLICY_SCOPE_USER,
1173 new base::StringValue(kInstantURL),
1174 NULL);
1175 base::ListValue* alternate_urls = new base::ListValue();
1176 alternate_urls->AppendString(kAlternateURL0);
1177 alternate_urls->AppendString(kAlternateURL1);
1178 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1179 POLICY_SCOPE_USER, alternate_urls, NULL);
1180 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1181 POLICY_LEVEL_MANDATORY,
1182 POLICY_SCOPE_USER,
1183 new base::StringValue(kSearchTermsReplacementKey),
1184 NULL);
1185 UpdateProviderPolicy(policies);
1186 default_search = service->GetDefaultSearchProvider();
1187 ASSERT_TRUE(default_search);
1188 EXPECT_EQ(kKeyword, default_search->keyword());
1189 EXPECT_EQ(kSearchURL, default_search->url());
1190 EXPECT_EQ(kInstantURL, default_search->instant_url());
1191 EXPECT_EQ(2U, default_search->alternate_urls().size());
1192 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1193 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1195 // Query terms replacement requires that the renderer process be a recognized
1196 // Instant renderer. Fake it.
1197 InstantService* instant_service =
1198 InstantServiceFactory::GetForProfile(browser()->profile());
1199 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1200 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1202 // Verify that searching from the omnibox does search term replacement with
1203 // first URL pattern.
1204 chrome::FocusLocationBar(browser());
1205 LocationBar* location_bar = browser()->window()->GetLocationBar();
1206 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1207 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1208 "https://www.google.com/?espv=1#q=foobar");
1209 EXPECT_TRUE(
1210 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1211 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1213 // Verify that not using espv=1 does not do search term replacement.
1214 chrome::FocusLocationBar(browser());
1215 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1216 "https://www.google.com/?q=foobar");
1217 EXPECT_FALSE(
1218 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1219 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1220 omnibox_view->GetText());
1222 // Verify that searching from the omnibox does search term replacement with
1223 // second URL pattern.
1224 chrome::FocusLocationBar(browser());
1225 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1226 "https://www.google.com/search?espv=1#q=banana");
1227 EXPECT_TRUE(
1228 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1229 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1231 // Verify that searching from the omnibox does search term replacement with
1232 // standard search URL pattern.
1233 chrome::FocusLocationBar(browser());
1234 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1235 "https://www.google.com/search?q=tractor+parts&espv=1");
1236 EXPECT_TRUE(
1237 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1238 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1240 // Verify that searching from the omnibox prioritizes hash over query.
1241 chrome::FocusLocationBar(browser());
1242 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1243 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1244 EXPECT_TRUE(
1245 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1246 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1249 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1250 // This test assumes Gpu access.
1251 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1252 return;
1254 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1255 // WebGL is enabled by default.
1256 content::WebContents* contents =
1257 browser()->tab_strip_model()->GetActiveWebContents();
1258 EXPECT_TRUE(IsWebGLEnabled(contents));
1259 // Disable with a policy.
1260 PolicyMap policies;
1261 policies.Set(key::kDisable3DAPIs,
1262 POLICY_LEVEL_MANDATORY,
1263 POLICY_SCOPE_USER,
1264 new base::FundamentalValue(true),
1265 NULL);
1266 UpdateProviderPolicy(policies);
1267 // Crash and reload the tab to get a new renderer.
1268 content::CrashTab(contents);
1269 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1270 EXPECT_FALSE(IsWebGLEnabled(contents));
1271 // Enable with a policy.
1272 policies.Set(key::kDisable3DAPIs,
1273 POLICY_LEVEL_MANDATORY,
1274 POLICY_SCOPE_USER,
1275 new base::FundamentalValue(false),
1276 NULL);
1277 UpdateProviderPolicy(policies);
1278 content::CrashTab(contents);
1279 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1280 EXPECT_TRUE(IsWebGLEnabled(contents));
1283 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1284 // Verifies that SPDY can be disable by policy.
1285 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1286 PolicyMap policies;
1287 policies.Set(key::kDisableSpdy,
1288 POLICY_LEVEL_MANDATORY,
1289 POLICY_SCOPE_USER,
1290 new base::FundamentalValue(true),
1291 NULL);
1292 UpdateProviderPolicy(policies);
1293 content::RunAllPendingInMessageLoop();
1294 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1295 // Verify that it can be force-enabled too.
1296 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1297 policies.Set(key::kDisableSpdy,
1298 POLICY_LEVEL_MANDATORY,
1299 POLICY_SCOPE_USER,
1300 new base::FundamentalValue(false),
1301 NULL);
1302 UpdateProviderPolicy(policies);
1303 content::RunAllPendingInMessageLoop();
1304 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1307 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1308 // Verifies that plugins can be forced to be disabled by policy.
1310 // Verify that the Flash plugin exists and that it can be enabled and disabled
1311 // by the user.
1312 std::vector<content::WebPluginInfo> plugins;
1313 GetPluginList(&plugins);
1314 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1315 if (!flash)
1316 return;
1317 PluginPrefs* plugin_prefs =
1318 PluginPrefs::GetForProfile(browser()->profile()).get();
1319 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1320 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1321 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1322 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1323 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1325 // Now disable it with a policy.
1326 base::ListValue disabled_plugins;
1327 disabled_plugins.Append(new base::StringValue("*Flash*"));
1328 PolicyMap policies;
1329 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1330 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1331 UpdateProviderPolicy(policies);
1332 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1333 // The user shouldn't be able to enable it.
1334 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1335 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1338 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1339 // Verifies that plugins with an exception in the blacklist can be enabled.
1341 // Verify that the Flash plugin exists and that it can be enabled and disabled
1342 // by the user.
1343 std::vector<content::WebPluginInfo> plugins;
1344 GetPluginList(&plugins);
1345 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1346 if (!flash)
1347 return;
1348 PluginPrefs* plugin_prefs =
1349 PluginPrefs::GetForProfile(browser()->profile()).get();
1350 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1352 // Disable all plugins.
1353 base::ListValue disabled_plugins;
1354 disabled_plugins.Append(new base::StringValue("*"));
1355 PolicyMap policies;
1356 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1357 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1358 UpdateProviderPolicy(policies);
1359 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1360 // The user shouldn't be able to enable it.
1361 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1362 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1364 // Now open an exception for flash.
1365 base::ListValue disabled_plugins_exceptions;
1366 disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1367 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1368 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1369 UpdateProviderPolicy(policies);
1370 // It should revert to the user's preference automatically.
1371 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1372 // And the user should be able to disable and enable again.
1373 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1374 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1375 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1376 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1379 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1380 // Verifies that a plugin can be force-installed with a policy.
1381 std::vector<content::WebPluginInfo> plugins;
1382 GetPluginList(&plugins);
1383 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1384 if (!flash)
1385 return;
1386 PluginPrefs* plugin_prefs =
1387 PluginPrefs::GetForProfile(browser()->profile()).get();
1388 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1390 // The user disables it and then a policy forces it to be enabled.
1391 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1392 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1393 base::ListValue plugin_list;
1394 plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1395 PolicyMap policies;
1396 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1397 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1398 UpdateProviderPolicy(policies);
1399 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1400 // The user can't disable it anymore.
1401 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1402 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1404 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1405 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1406 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1407 UpdateProviderPolicy(policies);
1408 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1411 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1412 // Verifies that dangerous plugins can be always authorized to run with
1413 // a policy.
1415 // Verify that the test page exists. It is only present in checkouts with
1416 // src-internal.
1417 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1418 base::FilePath(FILE_PATH_LITERAL("plugin")),
1419 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1420 LOG(INFO) <<
1421 "Test skipped because plugin/quicktime.html test file wasn't found.";
1422 return;
1425 ServeContentTestData();
1426 // No plugins at startup.
1427 EXPECT_EQ(0, CountPlugins());
1429 content::WebContents* contents =
1430 browser()->tab_strip_model()->GetActiveWebContents();
1431 ASSERT_TRUE(contents);
1432 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1433 ASSERT_TRUE(infobar_service);
1434 EXPECT_EQ(0u, infobar_service->infobar_count());
1436 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1437 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1438 ui_test_utils::NavigateToURL(browser(), url);
1439 // This should have triggered the dangerous plugin infobar.
1440 ASSERT_EQ(1u, infobar_service->infobar_count());
1441 EXPECT_TRUE(
1442 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1443 // And the plugin isn't running.
1444 EXPECT_EQ(0, CountPlugins());
1446 // Now set a policy to always authorize this.
1447 PolicyMap policies;
1448 policies.Set(key::kAlwaysAuthorizePlugins,
1449 POLICY_LEVEL_MANDATORY,
1450 POLICY_SCOPE_USER,
1451 new base::FundamentalValue(true),
1452 NULL);
1453 UpdateProviderPolicy(policies);
1454 // Reloading the page shouldn't trigger the infobar this time.
1455 ui_test_utils::NavigateToURL(browser(), url);
1456 EXPECT_EQ(0u, infobar_service->infobar_count());
1457 // And the plugin started automatically.
1458 EXPECT_EQ(1, CountPlugins());
1461 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1462 // Verifies that access to the developer tools can be disabled.
1464 // Open devtools.
1465 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1466 content::WebContents* contents =
1467 browser()->tab_strip_model()->GetActiveWebContents();
1468 DevToolsWindow* devtools_window =
1469 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1470 EXPECT_TRUE(devtools_window);
1472 // Disable devtools via policy.
1473 PolicyMap policies;
1474 policies.Set(key::kDeveloperToolsDisabled,
1475 POLICY_LEVEL_MANDATORY,
1476 POLICY_SCOPE_USER,
1477 new base::FundamentalValue(true),
1478 NULL);
1479 content::WindowedNotificationObserver close_observer(
1480 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1481 content::Source<content::WebContents>(
1482 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1483 UpdateProviderPolicy(policies);
1484 // wait for devtools close
1485 close_observer.Wait();
1486 // The existing devtools window should have closed.
1487 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1488 // And it's not possible to open it again.
1489 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1490 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1493 // TODO(samarth): remove along with rest of NTP4 code.
1494 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1495 #if defined(OS_WIN) && defined(USE_ASH)
1496 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1497 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1498 switches::kAshBrowserTests))
1499 return;
1500 #endif
1502 // Verifies that the web store icons can be hidden from the new tab page.
1504 // Open new tab page and look for the web store icons.
1505 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1506 content::WebContents* contents =
1507 browser()->tab_strip_model()->GetActiveWebContents();
1509 #if !defined(OS_CHROMEOS)
1510 // Look for web store's app ID in the apps page.
1511 EXPECT_TRUE(ContainsVisibleElement(contents,
1512 "ahfgeienlihckogmohjhadlkjgocpleb"));
1513 #endif
1515 // The next NTP has no footer.
1516 if (ContainsVisibleElement(contents, "footer"))
1517 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1519 // Turn off the web store icons.
1520 PolicyMap policies;
1521 policies.Set(key::kHideWebStoreIcon,
1522 POLICY_LEVEL_MANDATORY,
1523 POLICY_SCOPE_USER,
1524 new base::FundamentalValue(true),
1525 NULL);
1526 UpdateProviderPolicy(policies);
1528 // The web store icons should now be hidden.
1529 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1530 EXPECT_FALSE(ContainsVisibleElement(contents,
1531 "ahfgeienlihckogmohjhadlkjgocpleb"));
1532 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1535 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1536 // Verifies that the download directory can be forced by policy.
1538 // Set the initial download directory.
1539 base::ScopedTempDir initial_dir;
1540 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1541 browser()->profile()->GetPrefs()->SetFilePath(
1542 prefs::kDownloadDefaultDirectory, initial_dir.path());
1543 // Don't prompt for the download location during this test.
1544 browser()->profile()->GetPrefs()->SetBoolean(
1545 prefs::kPromptForDownload, false);
1547 // Verify that downloads end up on the default directory.
1548 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1549 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1550 base::DieFileDie(initial_dir.path().Append(file), false);
1552 // Override the download directory with the policy and verify a download.
1553 base::ScopedTempDir forced_dir;
1554 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1555 PolicyMap policies;
1556 policies.Set(key::kDownloadDirectory,
1557 POLICY_LEVEL_MANDATORY,
1558 POLICY_SCOPE_USER,
1559 new base::StringValue(forced_dir.path().value()),
1560 NULL);
1561 UpdateProviderPolicy(policies);
1562 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1563 // Verify that the first download location wasn't affected.
1564 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1567 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1568 // Verifies that blacklisted extensions can't be installed.
1569 ExtensionService* service = extension_service();
1570 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1571 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1572 base::ListValue blacklist;
1573 blacklist.Append(new base::StringValue(kGoodCrxId));
1574 PolicyMap policies;
1575 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1576 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1577 UpdateProviderPolicy(policies);
1579 // "good.crx" is blacklisted.
1580 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1581 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1583 // "adblock.crx" is not.
1584 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1585 ASSERT_TRUE(adblock);
1586 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1587 EXPECT_EQ(adblock,
1588 service->GetExtensionById(kAdBlockCrxId, true));
1591 // Flaky on windows; http://crbug.com/307994.
1592 #if defined(OS_WIN)
1593 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1594 #else
1595 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1596 #endif
1597 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1598 // Verify that a wildcard blacklist takes effect.
1599 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1600 ExtensionService* service = extension_service();
1601 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1602 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1603 base::ListValue blacklist;
1604 blacklist.Append(new base::StringValue("*"));
1605 PolicyMap policies;
1606 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1607 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1608 UpdateProviderPolicy(policies);
1610 // AdBlock was automatically removed.
1611 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1613 // And can't be installed again, nor can good.crx.
1614 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1615 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1616 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1617 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1620 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
1621 // Verifies that shared_modules are not affected by the blacklist.
1623 const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
1624 const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
1626 // Make sure that "import" and "export" are available to these extension IDs
1627 // by mocking the release channel.
1628 extensions::ScopedCurrentChannel channel(chrome::VersionInfo::CHANNEL_DEV);
1630 // Verify that the extensions are not installed initially.
1631 ExtensionService* service = extension_service();
1632 ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
1633 ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
1635 // Mock the webstore update URL. This is where the shared module extension
1636 // will be installed from.
1637 base::FilePath update_xml_path = base::FilePath(kTestExtensionsDir)
1638 .AppendASCII("policy_shared_module")
1639 .AppendASCII("update.xml");
1640 GURL update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path));
1641 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1642 switches::kAppsGalleryUpdateURL, update_xml_url.spec());
1643 ui_test_utils::NavigateToURL(browser(), update_xml_url);
1645 // Blacklist "*" but force-install the importer extension. The shared module
1646 // should be automatically installed too.
1647 base::ListValue blacklist;
1648 blacklist.AppendString("*");
1649 base::ListValue forcelist;
1650 forcelist.AppendString(
1651 base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
1652 PolicyMap policies;
1653 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1654 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1655 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1656 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1658 extensions::ExtensionRegistry* registry =
1659 extensions::ExtensionRegistry::Get(browser()->profile());
1660 extensions::TestExtensionRegistryObserver observe_importer(
1661 registry, kImporterId);
1662 extensions::TestExtensionRegistryObserver observe_shared_module(
1663 registry, kSharedModuleId);
1664 UpdateProviderPolicy(policies);
1665 observe_importer.WaitForExtensionLoaded();
1666 observe_shared_module.WaitForExtensionLoaded();
1668 // Verify that both extensions got installed.
1669 const extensions::Extension* importer =
1670 service->GetExtensionById(kImporterId, true);
1671 ASSERT_TRUE(importer);
1672 EXPECT_EQ(kImporterId, importer->id());
1673 const extensions::Extension* shared_module =
1674 service->GetExtensionById(kSharedModuleId, true);
1675 ASSERT_TRUE(shared_module);
1676 EXPECT_EQ(kSharedModuleId, shared_module->id());
1677 EXPECT_TRUE(shared_module->is_shared_module());
1679 // Verify the dependency.
1680 scoped_ptr<extensions::ExtensionSet> set =
1681 service->shared_module_service()->GetDependentExtensions(shared_module);
1682 ASSERT_TRUE(set);
1683 EXPECT_EQ(1u, set->size());
1684 EXPECT_TRUE(set->Contains(importer->id()));
1686 std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
1687 extensions::SharedModuleInfo::GetImports(importer);
1688 ASSERT_EQ(1u, imports.size());
1689 EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
1692 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1693 // Verifies that the whitelist can open exceptions to the blacklist.
1694 ExtensionService* service = extension_service();
1695 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1696 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1697 base::ListValue blacklist;
1698 blacklist.Append(new base::StringValue("*"));
1699 base::ListValue whitelist;
1700 whitelist.Append(new base::StringValue(kGoodCrxId));
1701 PolicyMap policies;
1702 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1703 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1704 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1705 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1706 UpdateProviderPolicy(policies);
1707 // "adblock.crx" is blacklisted.
1708 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1709 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1710 // "good.crx" has a whitelist exception.
1711 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1712 ASSERT_TRUE(good);
1713 EXPECT_EQ(kGoodCrxId, good->id());
1714 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1715 // The user can also remove this extension.
1716 UninstallExtension(kGoodCrxId, true);
1719 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1720 // Verifies that extensions that are force-installed by policies are
1721 // installed and can't be uninstalled.
1722 ExtensionService* service = extension_service();
1723 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1725 // Extensions that are force-installed come from an update URL, which defaults
1726 // to the webstore. Use a mock URL for this test with an update manifest
1727 // that includes "good_v1.crx".
1728 base::FilePath path =
1729 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1730 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1732 // Setting the forcelist extension should install "good_v1.crx".
1733 base::ListValue forcelist;
1734 forcelist.Append(new base::StringValue(
1735 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1736 PolicyMap policies;
1737 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1738 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1739 content::WindowedNotificationObserver observer(
1740 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1741 content::NotificationService::AllSources());
1742 UpdateProviderPolicy(policies);
1743 observer.Wait();
1744 // Note: Cannot check that the notification details match the expected
1745 // exception, since the details object has already been freed prior to
1746 // the completion of observer.Wait().
1748 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1750 // The user is not allowed to uninstall force-installed extensions.
1751 UninstallExtension(kGoodCrxId, false);
1753 // The user is not allowed to load an unpacked extension with the
1754 // same ID as a force-installed extension.
1755 LoadUnpackedExtension(kGoodUnpackedExt, false);
1757 // Loading other unpacked extensions are not blocked.
1758 LoadUnpackedExtension(kAppUnpackedExt, true);
1760 const std::string old_version_number =
1761 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1763 base::FilePath test_path;
1764 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1766 TestRequestInterceptor interceptor(
1767 "update.extension",
1768 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1769 interceptor.PushJobCallback(
1770 TestRequestInterceptor::FileJob(
1771 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1773 // Updating the force-installed extension.
1774 extensions::ExtensionUpdater* updater = service->updater();
1775 extensions::ExtensionUpdater::CheckParams params;
1776 params.install_immediately = true;
1777 content::WindowedNotificationObserver update_observer(
1778 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1779 content::NotificationService::AllSources());
1780 updater->CheckNow(params);
1781 update_observer.Wait();
1783 const base::Version* new_version =
1784 service->GetExtensionById(kGoodCrxId, true)->version();
1785 ASSERT_TRUE(new_version->IsValid());
1786 base::Version old_version(old_version_number);
1787 ASSERT_TRUE(old_version.IsValid());
1789 EXPECT_EQ(1, new_version->CompareTo(old_version));
1791 EXPECT_EQ(0u, interceptor.GetPendingSize());
1793 // Wait until any background pages belonging to force-installed extensions
1794 // have been loaded.
1795 extensions::ProcessManager* manager =
1796 extensions::ProcessManager::Get(browser()->profile());
1797 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1798 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1799 all_views.begin();
1800 iter != all_views.end();) {
1801 if (!(*iter)->IsLoading()) {
1802 ++iter;
1803 } else {
1804 content::WebContents* web_contents =
1805 content::WebContents::FromRenderViewHost(*iter);
1806 ASSERT_TRUE(web_contents);
1807 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1809 // Test activity may have modified the set of extension processes during
1810 // message processing, so re-start the iteration to catch added/removed
1811 // processes.
1812 all_views = manager->GetAllViews();
1813 iter = all_views.begin();
1817 // Test policy-installed extensions are reloaded when killed.
1818 BackgroundContentsService::
1819 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1820 content::WindowedNotificationObserver extension_crashed_observer(
1821 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1822 content::NotificationService::AllSources());
1823 content::WindowedNotificationObserver extension_loaded_observer(
1824 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1825 content::NotificationService::AllSources());
1826 extensions::ExtensionHost* extension_host =
1827 extensions::ProcessManager::Get(browser()->profile())
1828 ->GetBackgroundHostForExtension(kGoodCrxId);
1829 extension_host->render_process_host()->Shutdown(content::RESULT_CODE_KILLED,
1830 false);
1831 extension_crashed_observer.Wait();
1832 extension_loaded_observer.Wait();
1835 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1836 // Verifies that extensions that are recommended-installed by policies are
1837 // installed, can be disabled but not uninstalled.
1838 ExtensionService* service = extension_service();
1839 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1841 base::FilePath path =
1842 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1843 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1845 // Setting the forcelist extension should install "good_v1.crx".
1846 base::DictionaryValue dict_value;
1847 dict_value.SetString(std::string(kGoodCrxId) + "." +
1848 extensions::schema_constants::kInstallationMode,
1849 extensions::schema_constants::kNormalInstalled);
1850 dict_value.SetString(
1851 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1852 url.spec());
1853 PolicyMap policies;
1854 policies.Set(key::kExtensionSettings,
1855 POLICY_LEVEL_MANDATORY,
1856 POLICY_SCOPE_USER,
1857 dict_value.DeepCopy(),
1858 NULL);
1859 content::WindowedNotificationObserver observer(
1860 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1861 content::NotificationService::AllSources());
1862 UpdateProviderPolicy(policies);
1863 observer.Wait();
1865 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1867 // The user is not allowed to uninstall recommended-installed extensions.
1868 UninstallExtension(kGoodCrxId, false);
1870 // Explictly re-enables the extension.
1871 service->EnableExtension(kGoodCrxId);
1873 // But the user is allowed to disable them.
1874 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1875 DisableExtension(kGoodCrxId);
1876 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1879 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1880 // Verifies that extensions are blocked if policy specifies an allowed types
1881 // list and the extension's type is not on that list.
1882 ExtensionService* service = extension_service();
1883 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1884 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1886 base::ListValue allowed_types;
1887 allowed_types.AppendString("hosted_app");
1888 PolicyMap policies;
1889 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1890 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1891 UpdateProviderPolicy(policies);
1893 // "good.crx" is blocked.
1894 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1895 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1897 // "hosted_app.crx" is of a whitelisted type.
1898 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1899 ASSERT_TRUE(hosted_app);
1900 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1901 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1903 // The user can remove the extension.
1904 UninstallExtension(kHostedAppCrxId, true);
1907 // Checks that a click on an extension CRX download triggers the extension
1908 // installation prompt without further user interaction when the source is
1909 // whitelisted by policy.
1910 // Flaky on windows; http://crbug.com/295729 .
1911 #if defined(OS_WIN)
1912 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1913 #else
1914 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1915 #endif
1916 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1917 ExtensionInstallPrompt::g_auto_confirm_for_tests =
1918 ExtensionInstallPrompt::ACCEPT;
1920 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1921 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1922 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1923 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1925 base::ScopedTempDir download_directory;
1926 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1927 DownloadPrefs* download_prefs =
1928 DownloadPrefs::FromBrowserContext(browser()->profile());
1929 download_prefs->SetDownloadPath(download_directory.path());
1931 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1932 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1933 ui_test_utils::NavigateToURL(browser(), download_page_url);
1935 // As long as the policy is not present, extensions are considered dangerous.
1936 content::DownloadTestObserverTerminal download_observer(
1937 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1938 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1939 PerformClick(0, 0);
1940 download_observer.WaitForFinished();
1942 // Install the policy and trigger another download.
1943 base::ListValue install_sources;
1944 install_sources.AppendString(install_source_url.spec());
1945 install_sources.AppendString(referrer_url.spec());
1946 PolicyMap policies;
1947 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1948 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1949 UpdateProviderPolicy(policies);
1951 content::WindowedNotificationObserver observer(
1952 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1953 content::NotificationService::AllSources());
1954 PerformClick(1, 0);
1955 observer.Wait();
1956 // Note: Cannot check that the notification details match the expected
1957 // exception, since the details object has already been freed prior to
1958 // the completion of observer.Wait().
1960 // The first extension shouldn't be present, the second should be there.
1961 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1962 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1965 // Verifies that extensions with version older than the minimum version required
1966 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
1967 // policy changes as well as regular auto-updater scheduled updates.
1968 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequired) {
1969 ExtensionService* service = extension_service();
1970 extensions::ExtensionRegistry* registry =
1971 extensions::ExtensionRegistry::Get(browser()->profile());
1972 extensions::ExtensionPrefs* extension_prefs =
1973 extensions::ExtensionPrefs::Get(browser()->profile());
1975 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
1976 service->updater()->StopTimerForTesting();
1978 // Setup interceptor for extension updates.
1979 base::FilePath test_path;
1980 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1981 TestRequestInterceptor interceptor(
1982 "update.extension",
1983 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1984 interceptor.PushJobCallback(TestRequestInterceptor::BadRequestJob());
1985 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
1986 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1988 // Install the extension.
1989 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
1990 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
1992 // Update policy to set a minimum version of 1.0.0.0, the extension (with
1993 // version 1.0.0.0) should still be enabled.
1995 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
1996 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.0");
1998 base::RunLoop().RunUntilIdle();
2000 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2002 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2003 // version 1.0.0.0) should now be disabled.
2004 EXPECT_EQ(2u, interceptor.GetPendingSize());
2005 base::RunLoop service_request_run_loop;
2006 interceptor.AddRequestServicedCallback(
2007 service_request_run_loop.QuitClosure());
2009 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2010 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2012 service_request_run_loop.Run();
2013 EXPECT_EQ(1u, interceptor.GetPendingSize());
2015 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2016 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2017 extension_prefs->GetDisableReasons(kGoodCrxId));
2019 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2020 // via the update URL in the manifest of the older version.
2021 EXPECT_EQ(1u, interceptor.GetPendingSize());
2023 content::WindowedNotificationObserver update_observer(
2024 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2025 content::NotificationService::AllSources());
2026 service->updater()->CheckSoon();
2027 update_observer.Wait();
2029 EXPECT_EQ(0u, interceptor.GetPendingSize());
2031 // The extension should be auto-updated to newer version and re-enabled.
2032 EXPECT_EQ("1.0.0.1",
2033 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2034 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2037 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2038 // and orders.
2039 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequiredAlt) {
2040 ExtensionService* service = extension_service();
2041 extensions::ExtensionRegistry* registry =
2042 extensions::ExtensionRegistry::Get(browser()->profile());
2043 extensions::ExtensionPrefs* extension_prefs =
2044 extensions::ExtensionPrefs::Get(browser()->profile());
2046 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2047 service->updater()->StopTimerForTesting();
2049 // Setup interceptor for extension updates.
2050 base::FilePath test_path;
2051 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
2052 TestRequestInterceptor interceptor(
2053 "update.extension",
2054 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
2055 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
2056 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
2058 // Set the policy to require an even higher minimum version this time.
2060 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2061 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.2");
2063 base::RunLoop().RunUntilIdle();
2065 // Install the 1.0.0.0 version, it should be installed but disabled.
2066 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2067 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2068 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2069 extension_prefs->GetDisableReasons(kGoodCrxId));
2070 EXPECT_EQ("1.0.0.0",
2071 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2073 // An extension management policy update should trigger an update as well.
2074 EXPECT_EQ(1u, interceptor.GetPendingSize());
2076 content::WindowedNotificationObserver update_observer(
2077 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2078 content::NotificationService::AllSources());
2080 // Set a higher minimum version, just intend to trigger a policy update.
2081 extensions::ExtensionManagementPolicyUpdater management_policy(
2082 &provider_);
2083 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.3");
2085 base::RunLoop().RunUntilIdle();
2086 update_observer.Wait();
2088 EXPECT_EQ(0u, interceptor.GetPendingSize());
2090 // It should be updated to 1.0.0.1 but remain disabled.
2091 EXPECT_EQ("1.0.0.1",
2092 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2093 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2094 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2095 extension_prefs->GetDisableReasons(kGoodCrxId));
2097 // Remove the minimum version requirement. The extension should be re-enabled.
2099 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2100 management_policy.UnsetMinimumVersionRequired(kGoodCrxId);
2102 base::RunLoop().RunUntilIdle();
2104 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2105 EXPECT_FALSE(extension_prefs->HasDisableReason(
2106 kGoodCrxId, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY));
2109 // Verifies that a force-installed extension which does not meet a subsequently
2110 // set minimum version requirement is handled well.
2111 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionForceInstalled) {
2112 extensions::ExtensionRegistry* registry =
2113 extensions::ExtensionRegistry::Get(browser()->profile());
2114 extensions::ExtensionPrefs* extension_prefs =
2115 extensions::ExtensionPrefs::Get(browser()->profile());
2117 // Prepare the update URL for force installing.
2118 const base::FilePath path =
2119 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
2120 const GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
2122 // Set policy to force-install the extension, it should be installed and
2123 // enabled.
2124 content::WindowedNotificationObserver install_observer(
2125 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2126 content::NotificationService::AllSources());
2127 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2129 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2130 management_policy.SetIndividualExtensionAutoInstalled(kGoodCrxId,
2131 url.spec(), true);
2133 base::RunLoop().RunUntilIdle();
2134 install_observer.Wait();
2136 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2138 // Set policy a minimum version of "1.0.0.1", the extension now should be
2139 // disabled.
2141 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2142 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2144 base::RunLoop().RunUntilIdle();
2145 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2146 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2147 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2148 extension_prefs->GetDisableReasons(kGoodCrxId));
2151 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
2152 #if defined(OS_WIN) && defined(USE_ASH)
2153 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2154 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2155 switches::kAshBrowserTests))
2156 return;
2157 #endif
2159 // Verifies that the homepage can be configured with policies.
2160 // Set a default, and check that the home button navigates there.
2161 browser()->profile()->GetPrefs()->SetString(
2162 prefs::kHomePage, chrome::kChromeUIPolicyURL);
2163 browser()->profile()->GetPrefs()->SetBoolean(
2164 prefs::kHomePageIsNewTabPage, false);
2165 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
2166 browser()->profile()->GetHomePage());
2167 content::WebContents* contents =
2168 browser()->tab_strip_model()->GetActiveWebContents();
2169 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
2170 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2171 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
2173 // Now override with policy.
2174 PolicyMap policies;
2175 policies.Set(key::kHomepageLocation,
2176 POLICY_LEVEL_MANDATORY,
2177 POLICY_SCOPE_USER,
2178 new base::StringValue(chrome::kChromeUICreditsURL),
2179 NULL);
2180 UpdateProviderPolicy(policies);
2181 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2182 content::WaitForLoadStop(contents);
2183 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
2185 policies.Set(key::kHomepageIsNewTabPage,
2186 POLICY_LEVEL_MANDATORY,
2187 POLICY_SCOPE_USER,
2188 new base::FundamentalValue(true),
2189 NULL);
2190 UpdateProviderPolicy(policies);
2191 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2192 content::WaitForLoadStop(contents);
2193 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
2196 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
2197 // Verifies that incognito windows can't be opened when disabled by policy.
2199 const BrowserList* active_browser_list =
2200 BrowserList::GetInstance(chrome::GetActiveDesktop());
2202 // Disable incognito via policy and verify that incognito windows can't be
2203 // opened.
2204 EXPECT_EQ(1u, active_browser_list->size());
2205 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2206 PolicyMap policies;
2207 policies.Set(key::kIncognitoEnabled,
2208 POLICY_LEVEL_MANDATORY,
2209 POLICY_SCOPE_USER,
2210 new base::FundamentalValue(false),
2211 NULL);
2212 UpdateProviderPolicy(policies);
2213 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2214 EXPECT_EQ(1u, active_browser_list->size());
2215 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2217 // Enable via policy and verify that incognito windows can be opened.
2218 policies.Set(key::kIncognitoEnabled,
2219 POLICY_LEVEL_MANDATORY,
2220 POLICY_SCOPE_USER,
2221 new base::FundamentalValue(true),
2222 NULL);
2223 UpdateProviderPolicy(policies);
2224 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2225 EXPECT_EQ(2u, active_browser_list->size());
2226 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2229 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
2230 // Verifies that Javascript can be disabled.
2231 content::WebContents* contents =
2232 browser()->tab_strip_model()->GetActiveWebContents();
2233 EXPECT_TRUE(IsJavascriptEnabled(contents));
2234 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2235 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2236 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2238 // Disable Javascript via policy.
2239 PolicyMap policies;
2240 policies.Set(key::kJavascriptEnabled,
2241 POLICY_LEVEL_MANDATORY,
2242 POLICY_SCOPE_USER,
2243 new base::FundamentalValue(false),
2244 NULL);
2245 UpdateProviderPolicy(policies);
2246 // Reload the page.
2247 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2248 EXPECT_FALSE(IsJavascriptEnabled(contents));
2249 // Developer tools still work when javascript is disabled.
2250 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2251 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2252 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2253 // Javascript is always enabled for the internal pages.
2254 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
2255 EXPECT_TRUE(IsJavascriptEnabled(contents));
2257 // The javascript content setting policy overrides the javascript policy.
2258 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2259 EXPECT_FALSE(IsJavascriptEnabled(contents));
2260 policies.Set(key::kDefaultJavaScriptSetting,
2261 POLICY_LEVEL_MANDATORY,
2262 POLICY_SCOPE_USER,
2263 new base::FundamentalValue(CONTENT_SETTING_ALLOW),
2264 NULL);
2265 UpdateProviderPolicy(policies);
2266 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2267 EXPECT_TRUE(IsJavascriptEnabled(contents));
2270 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2271 PrefService* prefs = browser()->profile()->GetPrefs();
2273 // Enabled by default.
2274 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2276 // Disable by old, deprecated policy.
2277 PolicyMap policies;
2278 policies.Set(key::kDnsPrefetchingEnabled,
2279 POLICY_LEVEL_MANDATORY,
2280 POLICY_SCOPE_USER,
2281 new base::FundamentalValue(false),
2282 NULL);
2283 UpdateProviderPolicy(policies);
2285 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2287 // Enabled by new policy, this should override old one.
2288 policies.Set(
2289 key::kNetworkPredictionOptions,
2290 POLICY_LEVEL_MANDATORY,
2291 POLICY_SCOPE_USER,
2292 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2293 NULL);
2294 UpdateProviderPolicy(policies);
2296 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2299 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2300 // Verifies that browsing history is not saved.
2301 PolicyMap policies;
2302 policies.Set(key::kSavingBrowserHistoryDisabled,
2303 POLICY_LEVEL_MANDATORY,
2304 POLICY_SCOPE_USER,
2305 new base::FundamentalValue(true),
2306 NULL);
2307 UpdateProviderPolicy(policies);
2308 GURL url = ui_test_utils::GetTestUrl(
2309 base::FilePath(base::FilePath::kCurrentDirectory),
2310 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2311 ui_test_utils::NavigateToURL(browser(), url);
2312 // Verify that the navigation wasn't saved in the history.
2313 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2314 EXPECT_EQ(0u, enumerator1.urls().size());
2316 // Now flip the policy and try again.
2317 policies.Set(key::kSavingBrowserHistoryDisabled,
2318 POLICY_LEVEL_MANDATORY,
2319 POLICY_SCOPE_USER,
2320 new base::FundamentalValue(false),
2321 NULL);
2322 UpdateProviderPolicy(policies);
2323 ui_test_utils::NavigateToURL(browser(), url);
2324 // Verify that the navigation was saved in the history.
2325 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2326 ASSERT_EQ(1u, enumerator2.urls().size());
2327 EXPECT_EQ(url, enumerator2.urls()[0]);
2330 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2331 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2332 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2333 if (TranslateService::IsTranslateBubbleEnabled())
2334 return;
2336 scoped_ptr<test::CldDataHarness> cld_data_scope =
2337 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2338 ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2340 // Verifies that translate can be forced enabled or disabled by policy.
2342 // Get the InfoBarService, and verify that there are no infobars on startup.
2343 content::WebContents* contents =
2344 browser()->tab_strip_model()->GetActiveWebContents();
2345 ASSERT_TRUE(contents);
2346 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2347 ASSERT_TRUE(infobar_service);
2348 EXPECT_EQ(0u, infobar_service->infobar_count());
2350 // Force enable the translate feature.
2351 PolicyMap policies;
2352 policies.Set(key::kTranslateEnabled,
2353 POLICY_LEVEL_MANDATORY,
2354 POLICY_SCOPE_USER,
2355 new base::FundamentalValue(true),
2356 NULL);
2357 UpdateProviderPolicy(policies);
2358 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2359 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2360 // TranslateManager observes. This allows checking that an infobar is NOT
2361 // shown below, without polling for infobars for some indeterminate amount
2362 // of time.
2363 GURL url = ui_test_utils::GetTestUrl(
2364 base::FilePath(),
2365 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2366 content::WindowedNotificationObserver language_observer1(
2367 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2368 content::NotificationService::AllSources());
2369 ui_test_utils::NavigateToURL(browser(), url);
2370 language_observer1.Wait();
2372 // Verify the translation detected for this tab.
2373 ChromeTranslateClient* chrome_translate_client =
2374 ChromeTranslateClient::FromWebContents(contents);
2375 ASSERT_TRUE(chrome_translate_client);
2376 translate::LanguageState& language_state =
2377 chrome_translate_client->GetLanguageState();
2378 EXPECT_EQ("fr", language_state.original_language());
2379 EXPECT_TRUE(language_state.page_needs_translation());
2380 EXPECT_FALSE(language_state.translation_pending());
2381 EXPECT_FALSE(language_state.translation_declined());
2382 EXPECT_FALSE(language_state.IsPageTranslated());
2384 // Verify that the translate infobar showed up.
2385 ASSERT_EQ(1u, infobar_service->infobar_count());
2386 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2387 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2388 infobar->delegate()->AsTranslateInfoBarDelegate();
2389 ASSERT_TRUE(translate_infobar_delegate);
2390 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2391 translate_infobar_delegate->translate_step());
2392 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2394 // Now force disable translate.
2395 infobar_service->RemoveInfoBar(infobar);
2396 EXPECT_EQ(0u, infobar_service->infobar_count());
2397 policies.Set(key::kTranslateEnabled,
2398 POLICY_LEVEL_MANDATORY,
2399 POLICY_SCOPE_USER,
2400 new base::FundamentalValue(false),
2401 NULL);
2402 UpdateProviderPolicy(policies);
2403 // Navigating to the same URL now doesn't trigger an infobar.
2404 content::WindowedNotificationObserver language_observer2(
2405 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2406 content::NotificationService::AllSources());
2407 ui_test_utils::NavigateToURL(browser(), url);
2408 language_observer2.Wait();
2409 EXPECT_EQ(0u, infobar_service->infobar_count());
2412 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2413 // Checks that URLs can be blacklisted, and that exceptions can be made to
2414 // the blacklist.
2416 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2417 // as URLRequestMockHTTPJobs.
2418 const char* kURLS[] = {
2419 "http://aaa.com/empty.html",
2420 "http://bbb.com/empty.html",
2421 "http://sub.bbb.com/empty.html",
2422 "http://bbb.com/policy/blank.html",
2425 base::RunLoop loop;
2426 BrowserThread::PostTaskAndReply(
2427 BrowserThread::IO, FROM_HERE,
2428 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2429 loop.QuitClosure());
2430 loop.Run();
2433 // Verify that "bbb.com" opens before applying the blacklist.
2434 CheckCanOpenURL(browser(), kURLS[1]);
2436 // Set a blacklist.
2437 base::ListValue blacklist;
2438 blacklist.Append(new base::StringValue("bbb.com"));
2439 PolicyMap policies;
2440 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2441 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2442 UpdateProviderPolicy(policies);
2443 FlushBlacklistPolicy();
2444 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2445 CheckCanOpenURL(browser(), kURLS[0]);
2446 for (size_t i = 1; i < arraysize(kURLS); ++i)
2447 CheckURLIsBlocked(browser(), kURLS[i]);
2449 // Whitelist some sites of bbb.com.
2450 base::ListValue whitelist;
2451 whitelist.Append(new base::StringValue("sub.bbb.com"));
2452 whitelist.Append(new base::StringValue("bbb.com/policy"));
2453 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2454 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2455 UpdateProviderPolicy(policies);
2456 FlushBlacklistPolicy();
2457 CheckURLIsBlocked(browser(), kURLS[1]);
2458 CheckCanOpenURL(browser(), kURLS[2]);
2459 CheckCanOpenURL(browser(), kURLS[3]);
2462 base::RunLoop loop;
2463 BrowserThread::PostTaskAndReply(
2464 BrowserThread::IO, FROM_HERE,
2465 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2466 loop.QuitClosure());
2467 loop.Run();
2471 #if defined(OS_MACOSX)
2472 // http://crbug.com/339240
2473 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2474 #else
2475 #define MAYBE_FileURLBlacklist FileURLBlacklist
2476 #endif
2477 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2478 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2479 // with URLblacklisting and URLwhitelisting.
2481 base::FilePath test_path;
2482 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2483 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2484 const std::string folder_path = base_path + "apptest/";
2485 const std::string file_path1 = base_path + "title1.html";
2486 const std::string file_path2 = folder_path + "basic.html";
2488 CheckCanOpenURL(browser(), file_path1.c_str());
2489 CheckCanOpenURL(browser(), file_path2.c_str());
2491 // Set a blacklist for all the files.
2492 base::ListValue blacklist;
2493 blacklist.Append(new base::StringValue("file://*"));
2494 PolicyMap policies;
2495 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2496 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2497 UpdateProviderPolicy(policies);
2498 FlushBlacklistPolicy();
2500 CheckURLIsBlocked(browser(), file_path1.c_str());
2501 CheckURLIsBlocked(browser(), file_path2.c_str());
2503 // Replace the URLblacklist with disabling the file scheme.
2504 blacklist.Remove(base::StringValue("file://*"), NULL);
2505 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2506 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2507 UpdateProviderPolicy(policies);
2508 FlushBlacklistPolicy();
2510 PrefService* prefs = browser()->profile()->GetPrefs();
2511 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2512 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2513 list_url->end());
2515 base::ListValue disabledscheme;
2516 disabledscheme.Append(new base::StringValue("file"));
2517 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2518 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2519 UpdateProviderPolicy(policies);
2520 FlushBlacklistPolicy();
2522 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2523 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2524 list_url->end());
2526 // Whitelist one folder and blacklist an another just inside.
2527 base::ListValue whitelist;
2528 whitelist.Append(new base::StringValue(base_path));
2529 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2530 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2531 blacklist.Append(new base::StringValue(folder_path));
2532 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2533 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2534 UpdateProviderPolicy(policies);
2535 FlushBlacklistPolicy();
2537 CheckCanOpenURL(browser(), file_path1.c_str());
2538 CheckURLIsBlocked(browser(), file_path2.c_str());
2541 static bool IsMinSSLVersionTLS12(Profile* profile) {
2542 scoped_refptr<net::SSLConfigService> config_service(
2543 profile->GetSSLConfigService());
2544 net::SSLConfig config;
2545 config_service->GetSSLConfig(&config);
2546 return config.version_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2549 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionMin) {
2550 PrefService* prefs = g_browser_process->local_state();
2552 const std::string new_value("tls1.2");
2553 const std::string default_value(prefs->GetString(prefs::kSSLVersionMin));
2555 EXPECT_NE(default_value, new_value);
2556 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2558 PolicyMap policies;
2559 policies.Set(key::kSSLVersionMin,
2560 POLICY_LEVEL_MANDATORY,
2561 POLICY_SCOPE_USER,
2562 new base::StringValue(new_value),
2563 NULL);
2564 UpdateProviderPolicy(policies);
2566 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2569 static bool IsMinSSLFallbackVersionTLS12(Profile* profile) {
2570 scoped_refptr<net::SSLConfigService> config_service(
2571 profile->GetSSLConfigService());
2572 net::SSLConfig config;
2573 config_service->GetSSLConfig(&config);
2574 return config.version_fallback_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2577 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2578 PrefService* prefs = g_browser_process->local_state();
2580 const std::string new_value("tls1.2");
2581 const std::string default_value(
2582 prefs->GetString(prefs::kSSLVersionFallbackMin));
2584 EXPECT_NE(default_value, new_value);
2585 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2587 PolicyMap policies;
2588 policies.Set(key::kSSLVersionFallbackMin,
2589 POLICY_LEVEL_MANDATORY,
2590 POLICY_SCOPE_USER,
2591 new base::StringValue(new_value),
2592 NULL);
2593 UpdateProviderPolicy(policies);
2595 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2598 #if !defined(OS_MACOSX)
2599 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2600 PolicyMap policies;
2601 policies.Set(key::kFullscreenAllowed,
2602 POLICY_LEVEL_MANDATORY,
2603 POLICY_SCOPE_USER,
2604 new base::FundamentalValue(false),
2605 NULL);
2606 UpdateProviderPolicy(policies);
2608 BrowserWindow* browser_window = browser()->window();
2609 ASSERT_TRUE(browser_window);
2611 EXPECT_FALSE(browser_window->IsFullscreen());
2612 chrome::ToggleFullscreenMode(browser());
2613 EXPECT_FALSE(browser_window->IsFullscreen());
2616 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2617 PolicyMap policies;
2618 policies.Set(key::kFullscreenAllowed,
2619 POLICY_LEVEL_MANDATORY,
2620 POLICY_SCOPE_USER,
2621 new base::FundamentalValue(false),
2622 NULL);
2623 UpdateProviderPolicy(policies);
2625 const extensions::Extension* extension =
2626 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2627 ASSERT_TRUE(extension);
2629 // Launch an app that tries to open a fullscreen window.
2630 TestAddAppWindowObserver add_window_observer(
2631 extensions::AppWindowRegistry::Get(browser()->profile()));
2632 OpenApplication(AppLaunchParams(browser()->profile(), extension,
2633 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW,
2634 extensions::SOURCE_TEST));
2635 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2636 ASSERT_TRUE(window);
2638 // Verify that the window is not in fullscreen mode.
2639 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2641 // Verify that the window cannot be toggled into fullscreen mode via apps
2642 // APIs.
2643 EXPECT_TRUE(content::ExecuteScript(
2644 window->web_contents(),
2645 "chrome.app.window.current().fullscreen();"));
2646 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2648 // Verify that the window cannot be toggled into fullscreen mode from within
2649 // Chrome (e.g., using keyboard accelerators).
2650 window->Fullscreen();
2651 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2653 #endif
2655 #if defined(OS_CHROMEOS)
2656 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2657 int screenshot_count = CountScreenshots();
2659 // Make sure screenshots are counted correctly.
2660 TestScreenshotFile(true);
2661 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2663 // Check if trying to take a screenshot fails when disabled by policy.
2664 TestScreenshotFile(false);
2665 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2668 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2669 // Set up the mock observer.
2670 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2671 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2672 audio_handler->AddAudioObserver(test_observer.get());
2674 bool prior_state = audio_handler->IsOutputMuted();
2675 // Make sure the audio is not muted and then toggle the policy and observe
2676 // if the output mute changed event is fired.
2677 audio_handler->SetOutputMute(false);
2678 EXPECT_FALSE(audio_handler->IsOutputMuted());
2679 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2680 PolicyMap policies;
2681 policies.Set(key::kAudioOutputAllowed,
2682 POLICY_LEVEL_MANDATORY,
2683 POLICY_SCOPE_USER,
2684 new base::FundamentalValue(false),
2685 NULL);
2686 UpdateProviderPolicy(policies);
2687 EXPECT_TRUE(audio_handler->IsOutputMuted());
2688 // This should not change the state now and should not trigger output mute
2689 // changed event.
2690 audio_handler->SetOutputMute(false);
2691 EXPECT_TRUE(audio_handler->IsOutputMuted());
2692 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2694 // Toggle back and observe if the output mute changed event is fired.
2695 policies.Set(key::kAudioOutputAllowed,
2696 POLICY_LEVEL_MANDATORY,
2697 POLICY_SCOPE_USER,
2698 new base::FundamentalValue(true),
2699 NULL);
2700 UpdateProviderPolicy(policies);
2701 EXPECT_FALSE(audio_handler->IsOutputMuted());
2702 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2703 audio_handler->SetOutputMute(true);
2704 EXPECT_TRUE(audio_handler->IsOutputMuted());
2705 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2706 // Revert the prior state.
2707 audio_handler->SetOutputMute(prior_state);
2708 audio_handler->RemoveAudioObserver(test_observer.get());
2711 // Disabled, see http://crbug.com/315308.
2712 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2713 // Indicate that the session started 2 hours ago and no user activity has
2714 // occurred yet.
2715 g_browser_process->local_state()->SetInt64(
2716 prefs::kSessionStartTime,
2717 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2718 .ToInternalValue());
2721 // Disabled, see http://crbug.com/315308.
2722 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2723 content::MockNotificationObserver observer;
2724 content::NotificationRegistrar registrar;
2725 registrar.Add(&observer,
2726 chrome::NOTIFICATION_APP_TERMINATING,
2727 content::NotificationService::AllSources());
2729 // Set the session length limit to 3 hours. Verify that the session is not
2730 // terminated.
2731 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2732 .Times(0);
2733 PolicyMap policies;
2734 policies.Set(key::kSessionLengthLimit,
2735 POLICY_LEVEL_MANDATORY,
2736 POLICY_SCOPE_USER,
2737 new base::FundamentalValue(kThreeHoursInMs),
2738 NULL);
2739 UpdateProviderPolicy(policies);
2740 base::RunLoop().RunUntilIdle();
2741 Mock::VerifyAndClearExpectations(&observer);
2743 // Decrease the session length limit to 1 hour. Verify that the session is
2744 // terminated immediately.
2745 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2746 policies.Set(key::kSessionLengthLimit,
2747 POLICY_LEVEL_MANDATORY,
2748 POLICY_SCOPE_USER,
2749 new base::FundamentalValue(kOneHourInMs),
2750 NULL);
2751 UpdateProviderPolicy(policies);
2752 base::RunLoop().RunUntilIdle();
2753 Mock::VerifyAndClearExpectations(&observer);
2756 // Disabled, see http://crbug.com/315308.
2757 IN_PROC_BROWSER_TEST_F(PolicyTest,
2758 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2759 // Indicate that the session started 2 hours ago and no user activity has
2760 // occurred yet.
2761 g_browser_process->local_state()->SetInt64(
2762 prefs::kSessionStartTime,
2763 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2764 .ToInternalValue());
2767 // Disabled, see http://crbug.com/315308.
2768 IN_PROC_BROWSER_TEST_F(PolicyTest,
2769 DISABLED_WaitForInitialUserActivityUsatisfied) {
2770 content::MockNotificationObserver observer;
2771 content::NotificationRegistrar registrar;
2772 registrar.Add(&observer,
2773 chrome::NOTIFICATION_APP_TERMINATING,
2774 content::NotificationService::AllSources());
2776 // Require initial user activity.
2777 PolicyMap policies;
2778 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2779 POLICY_SCOPE_USER,
2780 new base::FundamentalValue(true),
2781 NULL);
2782 UpdateProviderPolicy(policies);
2783 base::RunLoop().RunUntilIdle();
2785 // Set the session length limit to 1 hour. Verify that the session is not
2786 // terminated.
2787 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2788 .Times(0);
2789 policies.Set(key::kSessionLengthLimit,
2790 POLICY_LEVEL_MANDATORY,
2791 POLICY_SCOPE_USER,
2792 new base::FundamentalValue(kOneHourInMs),
2793 NULL);
2794 UpdateProviderPolicy(policies);
2795 base::RunLoop().RunUntilIdle();
2796 Mock::VerifyAndClearExpectations(&observer);
2799 // Disabled, see http://crbug.com/315308.
2800 IN_PROC_BROWSER_TEST_F(PolicyTest,
2801 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2802 // Indicate that initial user activity in this session occurred 2 hours ago.
2803 g_browser_process->local_state()->SetInt64(
2804 prefs::kSessionStartTime,
2805 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2806 .ToInternalValue());
2807 g_browser_process->local_state()->SetBoolean(
2808 prefs::kSessionUserActivitySeen,
2809 true);
2812 // Disabled, see http://crbug.com/315308.
2813 IN_PROC_BROWSER_TEST_F(PolicyTest,
2814 DISABLED_WaitForInitialUserActivitySatisfied) {
2815 content::MockNotificationObserver observer;
2816 content::NotificationRegistrar registrar;
2817 registrar.Add(&observer,
2818 chrome::NOTIFICATION_APP_TERMINATING,
2819 content::NotificationService::AllSources());
2821 // Require initial user activity and set the session length limit to 3 hours.
2822 // Verify that the session is not terminated.
2823 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2824 .Times(0);
2825 PolicyMap policies;
2826 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2827 POLICY_SCOPE_USER,
2828 new base::FundamentalValue(true),
2829 NULL);
2830 policies.Set(key::kSessionLengthLimit,
2831 POLICY_LEVEL_MANDATORY,
2832 POLICY_SCOPE_USER,
2833 new base::FundamentalValue(kThreeHoursInMs),
2834 NULL);
2835 UpdateProviderPolicy(policies);
2836 base::RunLoop().RunUntilIdle();
2837 Mock::VerifyAndClearExpectations(&observer);
2839 // Decrease the session length limit to 1 hour. Verify that the session is
2840 // terminated immediately.
2841 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2842 policies.Set(key::kSessionLengthLimit,
2843 POLICY_LEVEL_MANDATORY,
2844 POLICY_SCOPE_USER,
2845 new base::FundamentalValue(kOneHourInMs),
2846 NULL);
2847 UpdateProviderPolicy(policies);
2848 base::RunLoop().RunUntilIdle();
2849 Mock::VerifyAndClearExpectations(&observer);
2852 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2853 // Verifies that the large cursor accessibility feature can be controlled
2854 // through policy.
2855 chromeos::AccessibilityManager* accessibility_manager =
2856 chromeos::AccessibilityManager::Get();
2858 // Manually enable the large cursor.
2859 accessibility_manager->EnableLargeCursor(true);
2860 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2862 // Verify that policy overrides the manual setting.
2863 PolicyMap policies;
2864 policies.Set(key::kLargeCursorEnabled,
2865 POLICY_LEVEL_MANDATORY,
2866 POLICY_SCOPE_USER,
2867 new base::FundamentalValue(false),
2868 NULL);
2869 UpdateProviderPolicy(policies);
2870 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2872 // Verify that the large cursor cannot be enabled manually anymore.
2873 accessibility_manager->EnableLargeCursor(true);
2874 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2877 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2878 // Verifies that the spoken feedback accessibility feature can be controlled
2879 // through policy.
2880 chromeos::AccessibilityManager* accessibility_manager =
2881 chromeos::AccessibilityManager::Get();
2883 // Manually enable spoken feedback.
2884 accessibility_manager->EnableSpokenFeedback(
2885 true, ui::A11Y_NOTIFICATION_NONE);
2886 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2888 // Verify that policy overrides the manual setting.
2889 PolicyMap policies;
2890 policies.Set(key::kSpokenFeedbackEnabled,
2891 POLICY_LEVEL_MANDATORY,
2892 POLICY_SCOPE_USER,
2893 new base::FundamentalValue(false),
2894 NULL);
2895 UpdateProviderPolicy(policies);
2896 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2898 // Verify that spoken feedback cannot be enabled manually anymore.
2899 accessibility_manager->EnableSpokenFeedback(
2900 true, ui::A11Y_NOTIFICATION_NONE);
2901 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2904 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2905 // Verifies that the high contrast mode accessibility feature can be
2906 // controlled through policy.
2907 chromeos::AccessibilityManager* accessibility_manager =
2908 chromeos::AccessibilityManager::Get();
2910 // Manually enable high contrast mode.
2911 accessibility_manager->EnableHighContrast(true);
2912 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2914 // Verify that policy overrides the manual setting.
2915 PolicyMap policies;
2916 policies.Set(key::kHighContrastEnabled,
2917 POLICY_LEVEL_MANDATORY,
2918 POLICY_SCOPE_USER,
2919 new base::FundamentalValue(false),
2920 NULL);
2921 UpdateProviderPolicy(policies);
2922 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2924 // Verify that high contrast mode cannot be enabled manually anymore.
2925 accessibility_manager->EnableHighContrast(true);
2926 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2929 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2930 // Verifies that the screen magnifier can be disabled through policy.
2931 chromeos::MagnificationManager* magnification_manager =
2932 chromeos::MagnificationManager::Get();
2934 // Manually enable the full-screen magnifier.
2935 magnification_manager->SetMagnifierType(ui::MAGNIFIER_FULL);
2936 magnification_manager->SetMagnifierEnabled(true);
2937 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2938 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2940 // Verify that policy overrides the manual setting.
2941 PolicyMap policies;
2942 policies.Set(key::kScreenMagnifierType,
2943 POLICY_LEVEL_MANDATORY,
2944 POLICY_SCOPE_USER,
2945 new base::FundamentalValue(0),
2946 NULL);
2947 UpdateProviderPolicy(policies);
2948 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2950 // Verify that the screen magnifier cannot be enabled manually anymore.
2951 magnification_manager->SetMagnifierEnabled(true);
2952 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2955 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2956 // Verifies that the full-screen magnifier can be enabled through policy.
2957 chromeos::MagnificationManager* magnification_manager =
2958 chromeos::MagnificationManager::Get();
2960 // Verify that the screen magnifier is initially disabled.
2961 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2963 // Verify that policy can enable the full-screen magnifier.
2964 PolicyMap policies;
2965 policies.Set(key::kScreenMagnifierType,
2966 POLICY_LEVEL_MANDATORY,
2967 POLICY_SCOPE_USER,
2968 new base::FundamentalValue(ui::MAGNIFIER_FULL),
2969 NULL);
2970 UpdateProviderPolicy(policies);
2971 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2972 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2974 // Verify that the screen magnifier cannot be disabled manually anymore.
2975 magnification_manager->SetMagnifierEnabled(false);
2976 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2979 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
2980 // Verifies that the on-screen keyboard accessibility feature can be
2981 // controlled through policy.
2982 chromeos::AccessibilityManager* accessibility_manager =
2983 chromeos::AccessibilityManager::Get();
2985 // Manually enable the on-screen keyboard.
2986 accessibility_manager->EnableVirtualKeyboard(true);
2987 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2989 // Verify that policy overrides the manual setting.
2990 PolicyMap policies;
2991 policies.Set(key::kVirtualKeyboardEnabled,
2992 POLICY_LEVEL_MANDATORY,
2993 POLICY_SCOPE_USER,
2994 new base::FundamentalValue(false),
2995 NULL);
2996 UpdateProviderPolicy(policies);
2997 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2999 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3000 accessibility_manager->EnableVirtualKeyboard(true);
3001 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3004 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
3005 // Verify keyboard disabled by default.
3006 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3007 // Verify keyboard can be toggled by default.
3008 keyboard::SetTouchKeyboardEnabled(true);
3009 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3010 keyboard::SetTouchKeyboardEnabled(false);
3011 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3013 // Verify enabling the policy takes effect immediately and that that user
3014 // cannot disable the keyboard..
3015 PolicyMap policies;
3016 policies.Set(key::kTouchVirtualKeyboardEnabled,
3017 POLICY_LEVEL_MANDATORY,
3018 POLICY_SCOPE_USER,
3019 new base::FundamentalValue(true),
3020 NULL);
3021 UpdateProviderPolicy(policies);
3022 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3023 keyboard::SetTouchKeyboardEnabled(false);
3024 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3026 // Verify that disabling the policy takes effect immediately and that the user
3027 // cannot enable the keyboard.
3028 policies.Set(key::kTouchVirtualKeyboardEnabled,
3029 POLICY_LEVEL_MANDATORY,
3030 POLICY_SCOPE_USER,
3031 new base::FundamentalValue(false),
3032 NULL);
3033 UpdateProviderPolicy(policies);
3034 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3035 keyboard::SetTouchKeyboardEnabled(true);
3036 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3039 #endif
3041 namespace {
3043 static const char* kRestoredURLs[] = {
3044 "http://aaa.com/empty.html",
3045 "http://bbb.com/empty.html",
3048 bool IsNonSwitchArgument(const base::CommandLine::StringType& s) {
3049 return s.empty() || s[0] != '-';
3052 } // namespace
3054 // Similar to PolicyTest but allows setting policies before the browser is
3055 // created. Each test parameter is a method that sets up the early policies
3056 // and stores the expected startup URLs in |expected_urls_|.
3057 class RestoreOnStartupPolicyTest
3058 : public PolicyTest,
3059 public testing::WithParamInterface<
3060 void (RestoreOnStartupPolicyTest::*)(void)> {
3061 public:
3062 RestoreOnStartupPolicyTest() {}
3063 virtual ~RestoreOnStartupPolicyTest() {}
3065 #if defined(OS_CHROMEOS)
3066 void SetUpCommandLine(base::CommandLine* command_line) override {
3067 // TODO(nkostylev): Investigate if we can remove this switch.
3068 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
3069 PolicyTest::SetUpCommandLine(command_line);
3071 #endif
3073 void SetUpInProcessBrowserTestFixture() override {
3074 PolicyTest::SetUpInProcessBrowserTestFixture();
3075 // Set early policies now, before the browser is created.
3076 (this->*(GetParam()))();
3078 // Remove the non-switch arguments, so that session restore kicks in for
3079 // these tests.
3080 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
3081 base::CommandLine::StringVector argv = command_line->argv();
3082 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
3083 argv.end());
3084 command_line->InitFromArgv(argv);
3085 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
3086 command_line->argv().begin()));
3089 void SetUpOnMainThread() override {
3090 BrowserThread::PostTask(
3091 BrowserThread::IO,
3092 FROM_HERE,
3093 base::Bind(
3094 RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
3097 void HomepageIsNotNTP() {
3098 // Verifies that policy can set the startup pages to the homepage, when
3099 // the homepage is not the NTP.
3100 PolicyMap policies;
3101 policies.Set(
3102 key::kRestoreOnStartup,
3103 POLICY_LEVEL_MANDATORY,
3104 POLICY_SCOPE_USER,
3105 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3106 NULL);
3107 policies.Set(key::kHomepageIsNewTabPage,
3108 POLICY_LEVEL_MANDATORY,
3109 POLICY_SCOPE_USER,
3110 new base::FundamentalValue(false),
3111 NULL);
3112 policies.Set(key::kHomepageLocation,
3113 POLICY_LEVEL_MANDATORY,
3114 POLICY_SCOPE_USER,
3115 new base::StringValue(kRestoredURLs[1]),
3116 NULL);
3117 provider_.UpdateChromePolicy(policies);
3119 expected_urls_.push_back(GURL(kRestoredURLs[1]));
3122 void HomepageIsNTP() {
3123 // Verifies that policy can set the startup pages to the homepage, when
3124 // the homepage is the NTP.
3125 PolicyMap policies;
3126 policies.Set(
3127 key::kRestoreOnStartup,
3128 POLICY_LEVEL_MANDATORY,
3129 POLICY_SCOPE_USER,
3130 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3131 NULL);
3132 policies.Set(key::kHomepageIsNewTabPage,
3133 POLICY_LEVEL_MANDATORY,
3134 POLICY_SCOPE_USER,
3135 new base::FundamentalValue(true),
3136 NULL);
3137 provider_.UpdateChromePolicy(policies);
3139 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3142 void ListOfURLs() {
3143 // Verifies that policy can set the startup pages to a list of URLs.
3144 base::ListValue urls;
3145 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
3146 urls.Append(new base::StringValue(kRestoredURLs[i]));
3147 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3149 PolicyMap policies;
3150 policies.Set(key::kRestoreOnStartup,
3151 POLICY_LEVEL_MANDATORY,
3152 POLICY_SCOPE_USER,
3153 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
3154 NULL);
3155 policies.Set(
3156 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3157 urls.DeepCopy(), NULL);
3158 provider_.UpdateChromePolicy(policies);
3161 void NTP() {
3162 // Verifies that policy can set the startup page to the NTP.
3163 PolicyMap policies;
3164 policies.Set(
3165 key::kRestoreOnStartup,
3166 POLICY_LEVEL_MANDATORY,
3167 POLICY_SCOPE_USER,
3168 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
3169 NULL);
3170 provider_.UpdateChromePolicy(policies);
3171 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3174 void Last() {
3175 // Verifies that policy can set the startup pages to the last session.
3176 PolicyMap policies;
3177 policies.Set(key::kRestoreOnStartup,
3178 POLICY_LEVEL_MANDATORY,
3179 POLICY_SCOPE_USER,
3180 new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
3181 NULL);
3182 provider_.UpdateChromePolicy(policies);
3183 // This should restore the tabs opened at PRE_RunTest below.
3184 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
3185 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3188 std::vector<GURL> expected_urls_;
3191 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
3192 // Open some tabs to verify if they are restored after the browser restarts.
3193 // Most policy settings override this, except kPrefValueLast which enforces
3194 // a restore.
3195 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
3196 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
3197 content::WindowedNotificationObserver observer(
3198 content::NOTIFICATION_LOAD_STOP,
3199 content::NotificationService::AllSources());
3200 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
3201 ui::PAGE_TRANSITION_LINK);
3202 observer.Wait();
3206 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
3207 #if defined(OS_WIN) && defined(USE_ASH)
3208 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3209 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3210 switches::kAshBrowserTests))
3211 return;
3212 #endif
3214 TabStripModel* model = browser()->tab_strip_model();
3215 int size = static_cast<int>(expected_urls_.size());
3216 EXPECT_EQ(size, model->count());
3217 for (int i = 0; i < size && i < model->count(); ++i) {
3218 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
3222 INSTANTIATE_TEST_CASE_P(
3223 RestoreOnStartupPolicyTestInstance,
3224 RestoreOnStartupPolicyTest,
3225 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
3226 &RestoreOnStartupPolicyTest::HomepageIsNTP,
3227 &RestoreOnStartupPolicyTest::ListOfURLs,
3228 &RestoreOnStartupPolicyTest::NTP,
3229 &RestoreOnStartupPolicyTest::Last));
3231 // Similar to PolicyTest but sets a couple of policies before the browser is
3232 // started.
3233 class PolicyStatisticsCollectorTest : public PolicyTest {
3234 public:
3235 PolicyStatisticsCollectorTest() {}
3236 ~PolicyStatisticsCollectorTest() override {}
3238 void SetUpInProcessBrowserTestFixture() override {
3239 PolicyTest::SetUpInProcessBrowserTestFixture();
3240 PolicyMap policies;
3241 policies.Set(key::kShowHomeButton,
3242 POLICY_LEVEL_MANDATORY,
3243 POLICY_SCOPE_USER,
3244 new base::FundamentalValue(true),
3245 NULL);
3246 policies.Set(key::kBookmarkBarEnabled,
3247 POLICY_LEVEL_MANDATORY,
3248 POLICY_SCOPE_USER,
3249 new base::FundamentalValue(false),
3250 NULL);
3251 policies.Set(key::kHomepageLocation,
3252 POLICY_LEVEL_MANDATORY,
3253 POLICY_SCOPE_USER,
3254 new base::StringValue("http://chromium.org"),
3255 NULL);
3256 provider_.UpdateChromePolicy(policies);
3260 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
3261 // Verifies that policy usage histograms are collected at startup.
3263 // BrowserPolicyConnector::Init() has already been called. Make sure the
3264 // CompleteInitialization() task has executed as well.
3265 content::RunAllPendingInMessageLoop();
3267 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
3268 std::string(url::kStandardSchemeSeparator) +
3269 std::string(content::kChromeUIHistogramHost));
3270 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3271 content::WebContents* contents =
3272 browser()->tab_strip_model()->GetActiveWebContents();
3273 std::string text;
3274 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3275 contents,
3276 "var nodes = document.querySelectorAll('body > pre');"
3277 "var result = '';"
3278 "for (var i = 0; i < nodes.length; ++i) {"
3279 " var text = nodes[i].innerHTML;"
3280 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3281 " result = text;"
3282 " break;"
3283 " }"
3285 "domAutomationController.send(result);",
3286 &text));
3287 ASSERT_FALSE(text.empty());
3288 const std::string kExpectedLabel =
3289 "Histogram: Enterprise.Policies recorded 3 samples";
3290 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3291 // HomepageLocation has policy ID 1.
3292 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
3293 // ShowHomeButton has policy ID 35.
3294 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
3295 // BookmarkBarEnabled has policy ID 82.
3296 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
3299 class MediaStreamDevicesControllerBrowserTest
3300 : public PolicyTest,
3301 public testing::WithParamInterface<bool> {
3302 public:
3303 MediaStreamDevicesControllerBrowserTest()
3304 : request_url_allowed_via_whitelist_(false) {
3305 policy_value_ = GetParam();
3307 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3309 // Configure a given policy map.
3310 // The |policy_name| is the name of either the audio or video capture allow
3311 // policy and must never be NULL.
3312 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3313 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3314 // and the whitelist policy is set to contain either the |allow_rule| (if
3315 // non-NULL) or an "allow all" wildcard.
3316 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3317 const char* whitelist_policy,
3318 const char* allow_rule) {
3319 policies->Set(policy_name,
3320 POLICY_LEVEL_MANDATORY,
3321 POLICY_SCOPE_USER,
3322 new base::FundamentalValue(policy_value_),
3323 NULL);
3325 if (whitelist_policy) {
3326 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3327 // in the media exceptions UI.
3328 // See discussion here: https://codereview.chromium.org/15738004/
3329 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3330 switches::kKioskMode);
3332 // Add an entry to the whitelist that allows the specified URL regardless
3333 // of the setting of kAudioCapturedAllowed.
3334 request_url_ = GURL("http://www.example.com/foo");
3335 base::ListValue* list = new base::ListValue();
3336 if (allow_rule) {
3337 list->AppendString(allow_rule);
3338 request_url_allowed_via_whitelist_ = true;
3339 } else {
3340 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3341 // We should ignore all wildcard entries in the whitelist, so even
3342 // though we've added an entry, it should be ignored and our expectation
3343 // is that the request has not been allowed via the whitelist.
3344 request_url_allowed_via_whitelist_ = false;
3346 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3347 POLICY_SCOPE_USER, list, NULL);
3351 void Accept(const content::MediaStreamDevices& devices,
3352 content::MediaStreamRequestResult result,
3353 scoped_ptr<content::MediaStreamUI> ui) {
3354 if (policy_value_ || request_url_allowed_via_whitelist_) {
3355 ASSERT_EQ(1U, devices.size());
3356 ASSERT_EQ("fake_dev", devices[0].id);
3357 } else {
3358 ASSERT_EQ(0U, devices.size());
3362 void FinishAudioTest() {
3363 content::MediaStreamRequest request(0, 0, 0,
3364 request_url_.GetOrigin(), false,
3365 content::MEDIA_DEVICE_ACCESS,
3366 std::string(), std::string(),
3367 content::MEDIA_DEVICE_AUDIO_CAPTURE,
3368 content::MEDIA_NO_SERVICE);
3369 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3370 // and microphone permissions at the same time.
3371 MediaStreamDevicesController controller(
3372 browser()->tab_strip_model()->GetActiveWebContents(), request,
3373 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3374 controller.Accept(false);
3376 base::MessageLoop::current()->QuitWhenIdle();
3379 void FinishVideoTest() {
3380 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3381 // and microphone permissions at the same time.
3382 content::MediaStreamRequest request(0, 0, 0,
3383 request_url_.GetOrigin(), false,
3384 content::MEDIA_DEVICE_ACCESS,
3385 std::string(),
3386 std::string(),
3387 content::MEDIA_NO_SERVICE,
3388 content::MEDIA_DEVICE_VIDEO_CAPTURE);
3389 MediaStreamDevicesController controller(
3390 browser()->tab_strip_model()->GetActiveWebContents(), request,
3391 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3392 controller.Accept(false);
3394 base::MessageLoop::current()->QuitWhenIdle();
3397 bool policy_value_;
3398 bool request_url_allowed_via_whitelist_;
3399 GURL request_url_;
3400 static const char kExampleRequestPattern[];
3403 // static
3404 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3405 "http://[*.]example.com/";
3407 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3408 AudioCaptureAllowed) {
3409 content::MediaStreamDevices audio_devices;
3410 content::MediaStreamDevice fake_audio_device(
3411 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3412 audio_devices.push_back(fake_audio_device);
3414 PolicyMap policies;
3415 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3416 UpdateProviderPolicy(policies);
3418 content::BrowserThread::PostTaskAndReply(
3419 content::BrowserThread::IO, FROM_HERE,
3420 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3421 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3422 audio_devices),
3423 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3424 this));
3426 base::MessageLoop::current()->Run();
3429 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3430 AudioCaptureAllowedUrls) {
3431 content::MediaStreamDevices audio_devices;
3432 content::MediaStreamDevice fake_audio_device(
3433 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3434 audio_devices.push_back(fake_audio_device);
3436 const char* allow_pattern[] = {
3437 kExampleRequestPattern,
3438 // This will set an allow-all policy whitelist. Since we do not allow
3439 // setting an allow-all entry in the whitelist, this entry should be ignored
3440 // and therefore the request should be denied.
3441 NULL,
3444 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3445 PolicyMap policies;
3446 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3447 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3448 UpdateProviderPolicy(policies);
3450 content::BrowserThread::PostTaskAndReply(
3451 content::BrowserThread::IO, FROM_HERE,
3452 base::Bind(
3453 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3454 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3455 audio_devices),
3456 base::Bind(
3457 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3458 this));
3460 base::MessageLoop::current()->Run();
3464 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3465 VideoCaptureAllowed) {
3466 content::MediaStreamDevices video_devices;
3467 content::MediaStreamDevice fake_video_device(
3468 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3469 video_devices.push_back(fake_video_device);
3471 PolicyMap policies;
3472 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3473 UpdateProviderPolicy(policies);
3475 content::BrowserThread::PostTaskAndReply(
3476 content::BrowserThread::IO, FROM_HERE,
3477 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3478 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3479 video_devices),
3480 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3481 this));
3483 base::MessageLoop::current()->Run();
3486 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3487 VideoCaptureAllowedUrls) {
3488 content::MediaStreamDevices video_devices;
3489 content::MediaStreamDevice fake_video_device(
3490 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3491 video_devices.push_back(fake_video_device);
3493 const char* allow_pattern[] = {
3494 kExampleRequestPattern,
3495 // This will set an allow-all policy whitelist. Since we do not allow
3496 // setting an allow-all entry in the whitelist, this entry should be ignored
3497 // and therefore the request should be denied.
3498 NULL,
3501 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3502 PolicyMap policies;
3503 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3504 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3505 UpdateProviderPolicy(policies);
3507 content::BrowserThread::PostTaskAndReply(
3508 content::BrowserThread::IO, FROM_HERE,
3509 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3510 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3511 video_devices),
3512 base::Bind(
3513 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3514 this));
3516 base::MessageLoop::current()->Run();
3520 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3521 MediaStreamDevicesControllerBrowserTest,
3522 testing::Bool());
3524 #if !defined(OS_CHROMEOS)
3525 // Similar to PolicyTest but sets the proper policy before the browser is
3526 // started.
3527 class PolicyVariationsServiceTest : public PolicyTest {
3528 public:
3529 void SetUpInProcessBrowserTestFixture() override {
3530 PolicyTest::SetUpInProcessBrowserTestFixture();
3531 PolicyMap policies;
3532 policies.Set(key::kVariationsRestrictParameter,
3533 POLICY_LEVEL_MANDATORY,
3534 POLICY_SCOPE_USER,
3535 new base::StringValue("restricted"),
3536 NULL);
3537 provider_.UpdateChromePolicy(policies);
3541 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3542 const std::string default_variations_url =
3543 chrome_variations::VariationsService::
3544 GetDefaultVariationsServerURLForTesting();
3546 const GURL url =
3547 chrome_variations::VariationsService::GetVariationsServerURL(
3548 g_browser_process->local_state(), std::string());
3549 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
3550 std::string value;
3551 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3552 EXPECT_EQ("restricted", value);
3555 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3556 base::ListValue blacklist;
3557 blacklist.Append(new base::StringValue("host.name"));
3558 PolicyMap policies;
3559 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3560 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3561 UpdateProviderPolicy(policies);
3563 PrefService* prefs = browser()->profile()->GetPrefs();
3564 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3565 prefs, "host.name"));
3566 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3567 prefs, "other.host.name"));
3570 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3571 base::ListValue blacklist;
3572 blacklist.Append(new base::StringValue("*"));
3573 PolicyMap policies;
3574 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3575 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3576 UpdateProviderPolicy(policies);
3578 PrefService* prefs = browser()->profile()->GetPrefs();
3579 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3580 prefs, "host.name"));
3581 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3582 prefs, "other.host.name"));
3585 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3586 base::ListValue blacklist;
3587 blacklist.Append(new base::StringValue("*"));
3588 base::ListValue whitelist;
3589 whitelist.Append(new base::StringValue("host.name"));
3590 PolicyMap policies;
3591 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3592 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3593 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3594 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3595 UpdateProviderPolicy(policies);
3597 PrefService* prefs = browser()->profile()->GetPrefs();
3598 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3599 prefs, "host.name"));
3600 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3601 prefs, "other.host.name"));
3604 #endif // !defined(CHROME_OS)
3606 } // namespace policy