Re-land: C++ readability review
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blob05c06949227b5175202e6d092405f75cb6db8c78
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(bool /* mute_on */) override {
507 ++output_mute_changed_count_;
510 private:
511 int output_mute_changed_count_;
513 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
515 #endif
517 // This class waits until either a load stops or the WebContents is destroyed.
518 class WebContentsLoadedOrDestroyedWatcher
519 : public content::WebContentsObserver {
520 public:
521 explicit WebContentsLoadedOrDestroyedWatcher(
522 content::WebContents* web_contents);
523 ~WebContentsLoadedOrDestroyedWatcher() override;
525 // Waits until the WebContents's load is done or until it is destroyed.
526 void Wait();
528 // Overridden WebContentsObserver methods.
529 void WebContentsDestroyed() override;
530 void DidStopLoading() override;
532 private:
533 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
535 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
538 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
539 content::WebContents* web_contents)
540 : content::WebContentsObserver(web_contents),
541 message_loop_runner_(new content::MessageLoopRunner) {
544 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
546 void WebContentsLoadedOrDestroyedWatcher::Wait() {
547 message_loop_runner_->Run();
550 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
551 message_loop_runner_->Quit();
554 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
555 message_loop_runner_->Quit();
558 #if !defined(OS_MACOSX)
560 // Observer used to wait for the creation of a new app window.
561 class TestAddAppWindowObserver
562 : public extensions::AppWindowRegistry::Observer {
563 public:
564 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
565 ~TestAddAppWindowObserver() override;
567 // extensions::AppWindowRegistry::Observer:
568 void OnAppWindowAdded(extensions::AppWindow* app_window) override;
570 extensions::AppWindow* WaitForAppWindow();
572 private:
573 extensions::AppWindowRegistry* registry_; // Not owned.
574 extensions::AppWindow* window_; // Not owned.
575 base::RunLoop run_loop_;
577 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
580 TestAddAppWindowObserver::TestAddAppWindowObserver(
581 extensions::AppWindowRegistry* registry)
582 : registry_(registry), window_(NULL) {
583 registry_->AddObserver(this);
586 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
587 registry_->RemoveObserver(this);
590 void TestAddAppWindowObserver::OnAppWindowAdded(
591 extensions::AppWindow* app_window) {
592 window_ = app_window;
593 run_loop_.Quit();
596 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
597 run_loop_.Run();
598 return window_;
601 #endif
603 } // namespace
605 class PolicyTest : public InProcessBrowserTest {
606 protected:
607 PolicyTest() {}
608 ~PolicyTest() override {}
610 void SetUp() override {
611 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
612 InProcessBrowserTest::SetUp();
615 void SetUpInProcessBrowserTestFixture() override {
616 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
617 EXPECT_CALL(provider_, IsInitializationComplete(_))
618 .WillRepeatedly(Return(true));
619 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
622 void SetUpOnMainThread() override {
623 BrowserThread::PostTask(
624 BrowserThread::IO, FROM_HERE,
625 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
626 if (extension_service()->updater()) {
627 extension_service()->updater()->SetExtensionCacheForTesting(
628 test_extension_cache_.get());
632 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
633 // instead of chrome::DIR_TEST_DATA.
634 void ServeContentTestData() {
635 base::FilePath root_http;
636 PathService::Get(content::DIR_TEST_DATA, &root_http);
637 BrowserThread::PostTaskAndReply(
638 BrowserThread::IO, FROM_HERE,
639 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers, root_http,
640 make_scoped_refptr(BrowserThread::GetBlockingPool())),
641 base::MessageLoop::current()->QuitWhenIdleClosure());
642 content::RunMessageLoop();
645 void SetScreenshotPolicy(bool enabled) {
646 PolicyMap policies;
647 policies.Set(key::kDisableScreenshots,
648 POLICY_LEVEL_MANDATORY,
649 POLICY_SCOPE_USER,
650 new base::FundamentalValue(!enabled),
651 NULL);
652 UpdateProviderPolicy(policies);
655 #if defined(OS_CHROMEOS)
656 class QuitMessageLoopAfterScreenshot : public ui::ScreenshotGrabberObserver {
657 public:
658 void OnScreenshotCompleted(
659 ScreenshotGrabberObserver::Result screenshot_result,
660 const base::FilePath& screenshot_path) override {
661 BrowserThread::PostTaskAndReply(BrowserThread::IO,
662 FROM_HERE,
663 base::Bind(base::DoNothing),
664 base::MessageLoop::QuitClosure());
667 ~QuitMessageLoopAfterScreenshot() override {}
670 void TestScreenshotFile(bool enabled) {
671 // AddObserver is an ash-specific method, so just replace the screenshot
672 // grabber with one we've created here.
673 scoped_ptr<ChromeScreenshotGrabber> chrome_screenshot_grabber(
674 new ChromeScreenshotGrabber);
675 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
676 // is tied to the test instead.
677 chrome_screenshot_grabber->screenshot_grabber()->AddObserver(&observer_);
678 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
679 chrome_screenshot_grabber.Pass());
681 SetScreenshotPolicy(enabled);
682 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
683 ash::TAKE_SCREENSHOT);
685 content::RunMessageLoop();
686 static_cast<ChromeScreenshotGrabber*>(ash::Shell::GetInstance()
687 ->accelerator_controller()
688 ->screenshot_delegate())
689 ->screenshot_grabber()
690 ->RemoveObserver(&observer_);
692 #endif
694 ExtensionService* extension_service() {
695 extensions::ExtensionSystem* system =
696 extensions::ExtensionSystem::Get(browser()->profile());
697 return system->extension_service();
700 const extensions::Extension* InstallExtension(
701 const base::FilePath::StringType& name) {
702 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
703 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
704 scoped_refptr<extensions::CrxInstaller> installer =
705 extensions::CrxInstaller::CreateSilent(extension_service());
706 installer->set_allow_silent_install(true);
707 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
708 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
710 content::WindowedNotificationObserver observer(
711 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
712 content::NotificationService::AllSources());
713 installer->InstallCrx(extension_path);
714 observer.Wait();
715 content::Details<const extensions::Extension> details = observer.details();
716 return details.ptr();
719 const extensions::Extension* LoadUnpackedExtension(
720 const base::FilePath::StringType& name, bool expect_success) {
721 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
722 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
723 scoped_refptr<extensions::UnpackedInstaller> installer =
724 extensions::UnpackedInstaller::Create(extension_service());
725 content::WindowedNotificationObserver observer(
726 expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
727 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
728 content::NotificationService::AllSources());
729 installer->Load(extension_path);
730 observer.Wait();
732 extensions::ExtensionRegistry* registry =
733 extensions::ExtensionRegistry::Get(browser()->profile());
734 for (const scoped_refptr<const extensions::Extension>& extension :
735 registry->enabled_extensions()) {
736 if (extension->path() == extension_path)
737 return extension.get();
739 return NULL;
742 void UninstallExtension(const std::string& id, bool expect_success) {
743 if (expect_success) {
744 extensions::TestExtensionRegistryObserver observer(
745 extensions::ExtensionRegistry::Get(browser()->profile()));
746 extension_service()->UninstallExtension(
747 id, extensions::UNINSTALL_REASON_FOR_TESTING,
748 base::Bind(&base::DoNothing), NULL);
749 observer.WaitForExtensionUninstalled();
750 } else {
751 content::WindowedNotificationObserver observer(
752 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
753 content::NotificationService::AllSources());
754 extension_service()->UninstallExtension(
756 extensions::UNINSTALL_REASON_FOR_TESTING,
757 base::Bind(&base::DoNothing),
758 NULL);
759 observer.Wait();
763 void DisableExtension(const std::string& id) {
764 extensions::TestExtensionRegistryObserver observer(
765 extensions::ExtensionRegistry::Get(browser()->profile()));
766 extension_service()->DisableExtension(id,
767 extensions::Extension::DISABLE_NONE);
768 observer.WaitForExtensionUnloaded();
771 void UpdateProviderPolicy(const PolicyMap& policy) {
772 provider_.UpdateChromePolicy(policy);
773 DCHECK(base::MessageLoop::current());
774 base::RunLoop loop;
775 loop.RunUntilIdle();
778 // Sends a mouse click at the given coordinates to the current renderer.
779 void PerformClick(int x, int y) {
780 content::WebContents* contents =
781 browser()->tab_strip_model()->GetActiveWebContents();
782 blink::WebMouseEvent click_event;
783 click_event.type = blink::WebInputEvent::MouseDown;
784 click_event.button = blink::WebMouseEvent::ButtonLeft;
785 click_event.clickCount = 1;
786 click_event.x = x;
787 click_event.y = y;
788 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
789 click_event.type = blink::WebInputEvent::MouseUp;
790 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
793 MockConfigurationPolicyProvider provider_;
794 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
795 #if defined(OS_CHROMEOS)
796 QuitMessageLoopAfterScreenshot observer_;
797 #endif
800 #if defined(OS_WIN)
801 // This policy only exists on Windows.
803 // Sets the locale policy before the browser is started.
804 class LocalePolicyTest : public PolicyTest {
805 public:
806 LocalePolicyTest() {}
807 virtual ~LocalePolicyTest() {}
809 virtual void SetUpInProcessBrowserTestFixture() override {
810 PolicyTest::SetUpInProcessBrowserTestFixture();
811 PolicyMap policies;
812 policies.Set(key::kApplicationLocaleValue,
813 POLICY_LEVEL_MANDATORY,
814 POLICY_SCOPE_USER,
815 new base::StringValue("fr"),
816 NULL);
817 provider_.UpdateChromePolicy(policies);
818 // The "en-US" ResourceBundle is always loaded before this step for tests,
819 // but in this test we want the browser to load the bundle as it
820 // normally would.
821 ResourceBundle::CleanupSharedInstance();
825 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
826 // Verifies that the default locale can be overridden with policy.
827 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
828 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
829 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
830 base::string16 title;
831 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
832 EXPECT_EQ(french_title, title);
834 // Make sure this is really French and differs from the English title.
835 std::string loaded =
836 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
837 EXPECT_EQ("en-US", loaded);
838 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
839 EXPECT_NE(french_title, english_title);
841 #endif
843 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
844 #if defined(OS_WIN) && defined(USE_ASH)
845 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
846 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
847 switches::kAshBrowserTests))
848 return;
849 #endif
851 // Verifies that the bookmarks bar can be forced to always or never show up.
853 // Test starts in about:blank.
854 PrefService* prefs = browser()->profile()->GetPrefs();
855 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
856 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
857 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
859 PolicyMap policies;
860 policies.Set(key::kBookmarkBarEnabled,
861 POLICY_LEVEL_MANDATORY,
862 POLICY_SCOPE_USER,
863 new base::FundamentalValue(true),
864 NULL);
865 UpdateProviderPolicy(policies);
866 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
867 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
868 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
870 // The NTP has special handling of the bookmark bar.
871 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
872 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
874 policies.Set(key::kBookmarkBarEnabled,
875 POLICY_LEVEL_MANDATORY,
876 POLICY_SCOPE_USER,
877 new base::FundamentalValue(false),
878 NULL);
879 UpdateProviderPolicy(policies);
880 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
881 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
882 // The bookmark bar is hidden in the NTP when disabled by policy.
883 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
885 policies.Clear();
886 UpdateProviderPolicy(policies);
887 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
888 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
889 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
890 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
893 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
894 // Verifies that cookies are deleted on shutdown. This test is split in 3
895 // parts because it spans 2 browser restarts.
897 Profile* profile = browser()->profile();
898 GURL url(kURL);
899 // No cookies at startup.
900 EXPECT_TRUE(content::GetCookies(profile, url).empty());
901 // Set a cookie now.
902 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
903 EXPECT_TRUE(content::SetCookie(profile, url, value));
904 // Verify it was set.
905 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
908 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
909 // Verify that the cookie persists across restarts.
910 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
911 // Now set the policy and the cookie should be gone after another restart.
912 PolicyMap policies;
913 policies.Set(key::kDefaultCookiesSetting,
914 POLICY_LEVEL_MANDATORY,
915 POLICY_SCOPE_USER,
916 new base::FundamentalValue(4),
917 NULL);
918 UpdateProviderPolicy(policies);
921 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
922 // Verify that the cookie is gone.
923 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
926 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
927 MakeRequestFail make_request_fail("search.example");
929 // Verifies that a default search is made using the provider configured via
930 // policy. Also checks that default search can be completely disabled.
931 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
932 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
933 const std::string kAlternateURL0(
934 "http://search.example/search#q={searchTerms}");
935 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
936 const std::string kSearchTermsReplacementKey("zekey");
937 const std::string kImageURL("http://test.com/searchbyimage/upload");
938 const std::string kImageURLPostParams(
939 "image_content=content,image_url=http://test.com/test.png");
940 const std::string kNewTabURL("http://search.example/newtab");
942 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
943 browser()->profile());
944 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
945 TemplateURL* default_search = service->GetDefaultSearchProvider();
946 ASSERT_TRUE(default_search);
947 EXPECT_NE(kKeyword, default_search->keyword());
948 EXPECT_NE(kSearchURL, default_search->url());
949 EXPECT_FALSE(
950 default_search->alternate_urls().size() == 2 &&
951 default_search->alternate_urls()[0] == kAlternateURL0 &&
952 default_search->alternate_urls()[1] == kAlternateURL1 &&
953 default_search->search_terms_replacement_key() ==
954 kSearchTermsReplacementKey &&
955 default_search->image_url() == kImageURL &&
956 default_search->image_url_post_params() == kImageURLPostParams &&
957 default_search->new_tab_url() == kNewTabURL);
959 // Override the default search provider using policies.
960 PolicyMap policies;
961 policies.Set(key::kDefaultSearchProviderEnabled,
962 POLICY_LEVEL_MANDATORY,
963 POLICY_SCOPE_USER,
964 new base::FundamentalValue(true),
965 NULL);
966 policies.Set(key::kDefaultSearchProviderKeyword,
967 POLICY_LEVEL_MANDATORY,
968 POLICY_SCOPE_USER,
969 new base::StringValue(kKeyword),
970 NULL);
971 policies.Set(key::kDefaultSearchProviderSearchURL,
972 POLICY_LEVEL_MANDATORY,
973 POLICY_SCOPE_USER,
974 new base::StringValue(kSearchURL),
975 NULL);
976 base::ListValue* alternate_urls = new base::ListValue();
977 alternate_urls->AppendString(kAlternateURL0);
978 alternate_urls->AppendString(kAlternateURL1);
979 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
980 POLICY_SCOPE_USER, alternate_urls, NULL);
981 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
982 POLICY_LEVEL_MANDATORY,
983 POLICY_SCOPE_USER,
984 new base::StringValue(kSearchTermsReplacementKey),
985 NULL);
986 policies.Set(key::kDefaultSearchProviderImageURL,
987 POLICY_LEVEL_MANDATORY,
988 POLICY_SCOPE_USER,
989 new base::StringValue(kImageURL),
990 NULL);
991 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
992 POLICY_LEVEL_MANDATORY,
993 POLICY_SCOPE_USER,
994 new base::StringValue(kImageURLPostParams),
995 NULL);
996 policies.Set(key::kDefaultSearchProviderNewTabURL,
997 POLICY_LEVEL_MANDATORY,
998 POLICY_SCOPE_USER,
999 new base::StringValue(kNewTabURL),
1000 NULL);
1001 UpdateProviderPolicy(policies);
1002 default_search = service->GetDefaultSearchProvider();
1003 ASSERT_TRUE(default_search);
1004 EXPECT_EQ(kKeyword, default_search->keyword());
1005 EXPECT_EQ(kSearchURL, default_search->url());
1006 EXPECT_EQ(2U, default_search->alternate_urls().size());
1007 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1008 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1009 EXPECT_EQ(kSearchTermsReplacementKey,
1010 default_search->search_terms_replacement_key());
1011 EXPECT_EQ(kImageURL, default_search->image_url());
1012 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
1013 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
1015 // Verify that searching from the omnibox uses kSearchURL.
1016 chrome::FocusLocationBar(browser());
1017 LocationBar* location_bar = browser()->window()->GetLocationBar();
1018 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1019 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1020 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1021 content::WebContents* web_contents =
1022 browser()->tab_strip_model()->GetActiveWebContents();
1023 GURL expected("http://search.example/search?q=stuff+to+search+for");
1024 EXPECT_EQ(expected, web_contents->GetURL());
1026 // Verify that searching from the omnibox can be disabled.
1027 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1028 policies.Set(key::kDefaultSearchProviderEnabled,
1029 POLICY_LEVEL_MANDATORY,
1030 POLICY_SCOPE_USER,
1031 new base::FundamentalValue(false),
1032 NULL);
1033 EXPECT_TRUE(service->GetDefaultSearchProvider());
1034 UpdateProviderPolicy(policies);
1035 EXPECT_FALSE(service->GetDefaultSearchProvider());
1036 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1037 // This means that submitting won't trigger any action.
1038 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1039 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1042 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1043 // Add an individual proxy policy value.
1044 PolicyMap policies;
1045 policies.Set(key::kProxyServerMode,
1046 POLICY_LEVEL_MANDATORY,
1047 POLICY_SCOPE_USER,
1048 new base::FundamentalValue(3),
1049 NULL);
1050 UpdateProviderPolicy(policies);
1052 // It should be removed and replaced with a dictionary.
1053 PolicyMap expected;
1054 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1055 expected_value->SetInteger(key::kProxyServerMode, 3);
1056 expected.Set(key::kProxySettings,
1057 POLICY_LEVEL_MANDATORY,
1058 POLICY_SCOPE_USER,
1059 expected_value.release(),
1060 NULL);
1062 // Check both the browser and the profile.
1063 const PolicyMap& actual_from_browser =
1064 g_browser_process->browser_policy_connector()
1065 ->GetPolicyService()
1066 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1067 EXPECT_TRUE(expected.Equals(actual_from_browser));
1068 const PolicyMap& actual_from_profile =
1069 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1070 ->policy_service()
1071 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1072 EXPECT_TRUE(expected.Equals(actual_from_profile));
1075 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1076 // Makes the requests fail since all we want to check is that the redirection
1077 // is done properly.
1078 MakeRequestFail make_request_fail("google.com");
1080 // Verifies that requests to Google Search engine with the SafeSearch
1081 // enabled set the safe=active&ssui=on parameters at the end of the query.
1082 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1083 browser()->profile());
1084 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1086 // First check that nothing happens.
1087 content::TestNavigationObserver no_safesearch_observer(
1088 browser()->tab_strip_model()->GetActiveWebContents());
1089 chrome::FocusLocationBar(browser());
1090 LocationBar* location_bar = browser()->window()->GetLocationBar();
1091 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1092 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1093 no_safesearch_observer.Wait();
1094 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1095 content::WebContents* web_contents =
1096 browser()->tab_strip_model()->GetActiveWebContents();
1097 GURL expected_without("http://google.com/");
1098 EXPECT_EQ(expected_without, web_contents->GetURL());
1100 PrefService* prefs = browser()->profile()->GetPrefs();
1101 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1102 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1104 // Override the default SafeSearch setting using policies.
1105 PolicyMap policies;
1106 policies.Set(key::kForceSafeSearch,
1107 POLICY_LEVEL_MANDATORY,
1108 POLICY_SCOPE_USER,
1109 new base::FundamentalValue(true),
1110 NULL);
1111 UpdateProviderPolicy(policies);
1113 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1114 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1116 content::TestNavigationObserver safesearch_observer(
1117 browser()->tab_strip_model()->GetActiveWebContents());
1119 // Verify that searching from google.com works.
1120 chrome::FocusLocationBar(browser());
1121 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1122 safesearch_observer.Wait();
1123 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1124 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1125 std::string expected_url("http://google.com/?");
1126 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1127 chrome::kSafeSearchSsuiParameter;
1128 GURL expected_with_parameters(expected_url);
1129 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1132 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1133 MakeRequestFail make_request_fail("search.example");
1135 chrome::EnableQueryExtractionForTesting();
1137 // Verifies that a default search is made using the provider configured via
1138 // policy. Also checks that default search can be completely disabled.
1139 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1140 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1141 const std::string kInstantURL("http://does/not/exist");
1142 const std::string kAlternateURL0(
1143 "https://www.google.com/search#q={searchTerms}");
1144 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1145 const std::string kSearchTermsReplacementKey(
1146 "{google:instantExtendedEnabledKey}");
1148 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1149 browser()->profile());
1150 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1151 TemplateURL* default_search = service->GetDefaultSearchProvider();
1152 ASSERT_TRUE(default_search);
1153 EXPECT_NE(kKeyword, default_search->keyword());
1154 EXPECT_NE(kSearchURL, default_search->url());
1155 EXPECT_NE(kInstantURL, default_search->instant_url());
1156 EXPECT_FALSE(
1157 default_search->alternate_urls().size() == 2 &&
1158 default_search->alternate_urls()[0] == kAlternateURL0 &&
1159 default_search->alternate_urls()[1] == kAlternateURL1);
1161 // Override the default search provider using policies.
1162 PolicyMap policies;
1163 policies.Set(key::kDefaultSearchProviderEnabled,
1164 POLICY_LEVEL_MANDATORY,
1165 POLICY_SCOPE_USER,
1166 new base::FundamentalValue(true),
1167 NULL);
1168 policies.Set(key::kDefaultSearchProviderKeyword,
1169 POLICY_LEVEL_MANDATORY,
1170 POLICY_SCOPE_USER,
1171 new base::StringValue(kKeyword),
1172 NULL);
1173 policies.Set(key::kDefaultSearchProviderSearchURL,
1174 POLICY_LEVEL_MANDATORY,
1175 POLICY_SCOPE_USER,
1176 new base::StringValue(kSearchURL),
1177 NULL);
1178 policies.Set(key::kDefaultSearchProviderInstantURL,
1179 POLICY_LEVEL_MANDATORY,
1180 POLICY_SCOPE_USER,
1181 new base::StringValue(kInstantURL),
1182 NULL);
1183 base::ListValue* alternate_urls = new base::ListValue();
1184 alternate_urls->AppendString(kAlternateURL0);
1185 alternate_urls->AppendString(kAlternateURL1);
1186 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1187 POLICY_SCOPE_USER, alternate_urls, NULL);
1188 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1189 POLICY_LEVEL_MANDATORY,
1190 POLICY_SCOPE_USER,
1191 new base::StringValue(kSearchTermsReplacementKey),
1192 NULL);
1193 UpdateProviderPolicy(policies);
1194 default_search = service->GetDefaultSearchProvider();
1195 ASSERT_TRUE(default_search);
1196 EXPECT_EQ(kKeyword, default_search->keyword());
1197 EXPECT_EQ(kSearchURL, default_search->url());
1198 EXPECT_EQ(kInstantURL, default_search->instant_url());
1199 EXPECT_EQ(2U, default_search->alternate_urls().size());
1200 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1201 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1203 // Query terms replacement requires that the renderer process be a recognized
1204 // Instant renderer. Fake it.
1205 InstantService* instant_service =
1206 InstantServiceFactory::GetForProfile(browser()->profile());
1207 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1208 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1210 // Verify that searching from the omnibox does search term replacement with
1211 // first URL pattern.
1212 chrome::FocusLocationBar(browser());
1213 LocationBar* location_bar = browser()->window()->GetLocationBar();
1214 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1215 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1216 "https://www.google.com/?espv=1#q=foobar");
1217 EXPECT_TRUE(
1218 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1219 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1221 // Verify that not using espv=1 does not do search term replacement.
1222 chrome::FocusLocationBar(browser());
1223 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1224 "https://www.google.com/?q=foobar");
1225 EXPECT_FALSE(
1226 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1227 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1228 omnibox_view->GetText());
1230 // Verify that searching from the omnibox does search term replacement with
1231 // second URL pattern.
1232 chrome::FocusLocationBar(browser());
1233 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1234 "https://www.google.com/search?espv=1#q=banana");
1235 EXPECT_TRUE(
1236 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1237 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1239 // Verify that searching from the omnibox does search term replacement with
1240 // standard search URL pattern.
1241 chrome::FocusLocationBar(browser());
1242 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1243 "https://www.google.com/search?q=tractor+parts&espv=1");
1244 EXPECT_TRUE(
1245 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1246 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1248 // Verify that searching from the omnibox prioritizes hash over query.
1249 chrome::FocusLocationBar(browser());
1250 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1251 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1252 EXPECT_TRUE(
1253 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1254 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1257 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1258 // This test assumes Gpu access.
1259 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1260 return;
1262 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1263 // WebGL is enabled by default.
1264 content::WebContents* contents =
1265 browser()->tab_strip_model()->GetActiveWebContents();
1266 EXPECT_TRUE(IsWebGLEnabled(contents));
1267 // Disable with a policy.
1268 PolicyMap policies;
1269 policies.Set(key::kDisable3DAPIs,
1270 POLICY_LEVEL_MANDATORY,
1271 POLICY_SCOPE_USER,
1272 new base::FundamentalValue(true),
1273 NULL);
1274 UpdateProviderPolicy(policies);
1275 // Crash and reload the tab to get a new renderer.
1276 content::CrashTab(contents);
1277 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1278 EXPECT_FALSE(IsWebGLEnabled(contents));
1279 // Enable with a policy.
1280 policies.Set(key::kDisable3DAPIs,
1281 POLICY_LEVEL_MANDATORY,
1282 POLICY_SCOPE_USER,
1283 new base::FundamentalValue(false),
1284 NULL);
1285 UpdateProviderPolicy(policies);
1286 content::CrashTab(contents);
1287 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1288 EXPECT_TRUE(IsWebGLEnabled(contents));
1291 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1292 // Verifies that SPDY can be disable by policy.
1293 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1294 PolicyMap policies;
1295 policies.Set(key::kDisableSpdy,
1296 POLICY_LEVEL_MANDATORY,
1297 POLICY_SCOPE_USER,
1298 new base::FundamentalValue(true),
1299 NULL);
1300 UpdateProviderPolicy(policies);
1301 content::RunAllPendingInMessageLoop();
1302 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1303 // Verify that it can be force-enabled too.
1304 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1305 policies.Set(key::kDisableSpdy,
1306 POLICY_LEVEL_MANDATORY,
1307 POLICY_SCOPE_USER,
1308 new base::FundamentalValue(false),
1309 NULL);
1310 UpdateProviderPolicy(policies);
1311 content::RunAllPendingInMessageLoop();
1312 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1315 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1316 // Verifies that plugins can be forced to be disabled by policy.
1318 // Verify that the Flash plugin exists and that it can be enabled and disabled
1319 // by the user.
1320 std::vector<content::WebPluginInfo> plugins;
1321 GetPluginList(&plugins);
1322 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1323 if (!flash)
1324 return;
1325 PluginPrefs* plugin_prefs =
1326 PluginPrefs::GetForProfile(browser()->profile()).get();
1327 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1328 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1329 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1330 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1331 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1333 // Now disable it with a policy.
1334 base::ListValue disabled_plugins;
1335 disabled_plugins.Append(new base::StringValue("*Flash*"));
1336 PolicyMap policies;
1337 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1338 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1339 UpdateProviderPolicy(policies);
1340 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1341 // The user shouldn't be able to enable it.
1342 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1343 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1346 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1347 // Verifies that plugins with an exception in the blacklist can be enabled.
1349 // Verify that the Flash plugin exists and that it can be enabled and disabled
1350 // by the user.
1351 std::vector<content::WebPluginInfo> plugins;
1352 GetPluginList(&plugins);
1353 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1354 if (!flash)
1355 return;
1356 PluginPrefs* plugin_prefs =
1357 PluginPrefs::GetForProfile(browser()->profile()).get();
1358 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1360 // Disable all plugins.
1361 base::ListValue disabled_plugins;
1362 disabled_plugins.Append(new base::StringValue("*"));
1363 PolicyMap policies;
1364 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1365 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1366 UpdateProviderPolicy(policies);
1367 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1368 // The user shouldn't be able to enable it.
1369 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1370 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1372 // Now open an exception for flash.
1373 base::ListValue disabled_plugins_exceptions;
1374 disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1375 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1376 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1377 UpdateProviderPolicy(policies);
1378 // It should revert to the user's preference automatically.
1379 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1380 // And the user should be able to disable and enable again.
1381 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1382 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1383 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1384 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1387 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1388 // Verifies that a plugin can be force-installed with a policy.
1389 std::vector<content::WebPluginInfo> plugins;
1390 GetPluginList(&plugins);
1391 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1392 if (!flash)
1393 return;
1394 PluginPrefs* plugin_prefs =
1395 PluginPrefs::GetForProfile(browser()->profile()).get();
1396 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1398 // The user disables it and then a policy forces it to be enabled.
1399 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1400 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1401 base::ListValue plugin_list;
1402 plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1403 PolicyMap policies;
1404 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1405 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1406 UpdateProviderPolicy(policies);
1407 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1408 // The user can't disable it anymore.
1409 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1410 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1412 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1413 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1414 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1415 UpdateProviderPolicy(policies);
1416 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1419 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1420 // Verifies that dangerous plugins can be always authorized to run with
1421 // a policy.
1423 // Verify that the test page exists. It is only present in checkouts with
1424 // src-internal.
1425 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1426 base::FilePath(FILE_PATH_LITERAL("plugin")),
1427 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1428 LOG(INFO) <<
1429 "Test skipped because plugin/quicktime.html test file wasn't found.";
1430 return;
1433 ServeContentTestData();
1434 // No plugins at startup.
1435 EXPECT_EQ(0, CountPlugins());
1437 content::WebContents* contents =
1438 browser()->tab_strip_model()->GetActiveWebContents();
1439 ASSERT_TRUE(contents);
1440 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1441 ASSERT_TRUE(infobar_service);
1442 EXPECT_EQ(0u, infobar_service->infobar_count());
1444 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1445 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1446 ui_test_utils::NavigateToURL(browser(), url);
1447 // This should have triggered the dangerous plugin infobar.
1448 ASSERT_EQ(1u, infobar_service->infobar_count());
1449 EXPECT_TRUE(
1450 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1451 // And the plugin isn't running.
1452 EXPECT_EQ(0, CountPlugins());
1454 // Now set a policy to always authorize this.
1455 PolicyMap policies;
1456 policies.Set(key::kAlwaysAuthorizePlugins,
1457 POLICY_LEVEL_MANDATORY,
1458 POLICY_SCOPE_USER,
1459 new base::FundamentalValue(true),
1460 NULL);
1461 UpdateProviderPolicy(policies);
1462 // Reloading the page shouldn't trigger the infobar this time.
1463 ui_test_utils::NavigateToURL(browser(), url);
1464 EXPECT_EQ(0u, infobar_service->infobar_count());
1465 // And the plugin started automatically.
1466 EXPECT_EQ(1, CountPlugins());
1469 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1470 // Verifies that access to the developer tools can be disabled.
1472 // Open devtools.
1473 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1474 content::WebContents* contents =
1475 browser()->tab_strip_model()->GetActiveWebContents();
1476 DevToolsWindow* devtools_window =
1477 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1478 EXPECT_TRUE(devtools_window);
1480 // Disable devtools via policy.
1481 PolicyMap policies;
1482 policies.Set(key::kDeveloperToolsDisabled,
1483 POLICY_LEVEL_MANDATORY,
1484 POLICY_SCOPE_USER,
1485 new base::FundamentalValue(true),
1486 NULL);
1487 content::WindowedNotificationObserver close_observer(
1488 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1489 content::Source<content::WebContents>(
1490 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1491 UpdateProviderPolicy(policies);
1492 // wait for devtools close
1493 close_observer.Wait();
1494 // The existing devtools window should have closed.
1495 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1496 // And it's not possible to open it again.
1497 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1498 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1501 // TODO(samarth): remove along with rest of NTP4 code.
1502 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1503 #if defined(OS_WIN) && defined(USE_ASH)
1504 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1505 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1506 switches::kAshBrowserTests))
1507 return;
1508 #endif
1510 // Verifies that the web store icons can be hidden from the new tab page.
1512 // Open new tab page and look for the web store icons.
1513 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1514 content::WebContents* contents =
1515 browser()->tab_strip_model()->GetActiveWebContents();
1517 #if !defined(OS_CHROMEOS)
1518 // Look for web store's app ID in the apps page.
1519 EXPECT_TRUE(ContainsVisibleElement(contents,
1520 "ahfgeienlihckogmohjhadlkjgocpleb"));
1521 #endif
1523 // The next NTP has no footer.
1524 if (ContainsVisibleElement(contents, "footer"))
1525 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1527 // Turn off the web store icons.
1528 PolicyMap policies;
1529 policies.Set(key::kHideWebStoreIcon,
1530 POLICY_LEVEL_MANDATORY,
1531 POLICY_SCOPE_USER,
1532 new base::FundamentalValue(true),
1533 NULL);
1534 UpdateProviderPolicy(policies);
1536 // The web store icons should now be hidden.
1537 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1538 EXPECT_FALSE(ContainsVisibleElement(contents,
1539 "ahfgeienlihckogmohjhadlkjgocpleb"));
1540 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1543 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1544 // Verifies that the download directory can be forced by policy.
1546 // Set the initial download directory.
1547 base::ScopedTempDir initial_dir;
1548 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1549 browser()->profile()->GetPrefs()->SetFilePath(
1550 prefs::kDownloadDefaultDirectory, initial_dir.path());
1551 // Don't prompt for the download location during this test.
1552 browser()->profile()->GetPrefs()->SetBoolean(
1553 prefs::kPromptForDownload, false);
1555 // Verify that downloads end up on the default directory.
1556 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1557 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1558 base::DieFileDie(initial_dir.path().Append(file), false);
1560 // Override the download directory with the policy and verify a download.
1561 base::ScopedTempDir forced_dir;
1562 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1563 PolicyMap policies;
1564 policies.Set(key::kDownloadDirectory,
1565 POLICY_LEVEL_MANDATORY,
1566 POLICY_SCOPE_USER,
1567 new base::StringValue(forced_dir.path().value()),
1568 NULL);
1569 UpdateProviderPolicy(policies);
1570 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1571 // Verify that the first download location wasn't affected.
1572 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1575 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1576 // Verifies that blacklisted extensions can't be installed.
1577 ExtensionService* service = extension_service();
1578 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1579 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1580 base::ListValue blacklist;
1581 blacklist.Append(new base::StringValue(kGoodCrxId));
1582 PolicyMap policies;
1583 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1584 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1585 UpdateProviderPolicy(policies);
1587 // "good.crx" is blacklisted.
1588 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1589 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1591 // "adblock.crx" is not.
1592 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1593 ASSERT_TRUE(adblock);
1594 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1595 EXPECT_EQ(adblock,
1596 service->GetExtensionById(kAdBlockCrxId, true));
1599 // Flaky on windows; http://crbug.com/307994.
1600 #if defined(OS_WIN)
1601 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1602 #else
1603 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1604 #endif
1605 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1606 // Verify that a wildcard blacklist takes effect.
1607 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1608 ExtensionService* service = extension_service();
1609 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1610 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1611 base::ListValue blacklist;
1612 blacklist.Append(new base::StringValue("*"));
1613 PolicyMap policies;
1614 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1615 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1616 UpdateProviderPolicy(policies);
1618 // AdBlock was automatically removed.
1619 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1621 // And can't be installed again, nor can good.crx.
1622 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1623 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1624 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1625 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1628 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
1629 // Verifies that shared_modules are not affected by the blacklist.
1631 const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
1632 const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
1634 // Make sure that "import" and "export" are available to these extension IDs
1635 // by mocking the release channel.
1636 extensions::ScopedCurrentChannel channel(chrome::VersionInfo::CHANNEL_DEV);
1638 // Verify that the extensions are not installed initially.
1639 ExtensionService* service = extension_service();
1640 ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
1641 ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
1643 // Mock the webstore update URL. This is where the shared module extension
1644 // will be installed from.
1645 base::FilePath update_xml_path = base::FilePath(kTestExtensionsDir)
1646 .AppendASCII("policy_shared_module")
1647 .AppendASCII("update.xml");
1648 GURL update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path));
1649 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1650 switches::kAppsGalleryUpdateURL, update_xml_url.spec());
1651 ui_test_utils::NavigateToURL(browser(), update_xml_url);
1653 // Blacklist "*" but force-install the importer extension. The shared module
1654 // should be automatically installed too.
1655 base::ListValue blacklist;
1656 blacklist.AppendString("*");
1657 base::ListValue forcelist;
1658 forcelist.AppendString(
1659 base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
1660 PolicyMap policies;
1661 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1662 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1663 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1664 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1666 extensions::ExtensionRegistry* registry =
1667 extensions::ExtensionRegistry::Get(browser()->profile());
1668 extensions::TestExtensionRegistryObserver observe_importer(
1669 registry, kImporterId);
1670 extensions::TestExtensionRegistryObserver observe_shared_module(
1671 registry, kSharedModuleId);
1672 UpdateProviderPolicy(policies);
1673 observe_importer.WaitForExtensionLoaded();
1674 observe_shared_module.WaitForExtensionLoaded();
1676 // Verify that both extensions got installed.
1677 const extensions::Extension* importer =
1678 service->GetExtensionById(kImporterId, true);
1679 ASSERT_TRUE(importer);
1680 EXPECT_EQ(kImporterId, importer->id());
1681 const extensions::Extension* shared_module =
1682 service->GetExtensionById(kSharedModuleId, true);
1683 ASSERT_TRUE(shared_module);
1684 EXPECT_EQ(kSharedModuleId, shared_module->id());
1685 EXPECT_TRUE(shared_module->is_shared_module());
1687 // Verify the dependency.
1688 scoped_ptr<extensions::ExtensionSet> set =
1689 service->shared_module_service()->GetDependentExtensions(shared_module);
1690 ASSERT_TRUE(set);
1691 EXPECT_EQ(1u, set->size());
1692 EXPECT_TRUE(set->Contains(importer->id()));
1694 std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
1695 extensions::SharedModuleInfo::GetImports(importer);
1696 ASSERT_EQ(1u, imports.size());
1697 EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
1700 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1701 // Verifies that the whitelist can open exceptions to the blacklist.
1702 ExtensionService* service = extension_service();
1703 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1704 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1705 base::ListValue blacklist;
1706 blacklist.Append(new base::StringValue("*"));
1707 base::ListValue whitelist;
1708 whitelist.Append(new base::StringValue(kGoodCrxId));
1709 PolicyMap policies;
1710 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1711 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1712 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1713 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1714 UpdateProviderPolicy(policies);
1715 // "adblock.crx" is blacklisted.
1716 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1717 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1718 // "good.crx" has a whitelist exception.
1719 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1720 ASSERT_TRUE(good);
1721 EXPECT_EQ(kGoodCrxId, good->id());
1722 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1723 // The user can also remove this extension.
1724 UninstallExtension(kGoodCrxId, true);
1727 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1728 // Verifies that extensions that are force-installed by policies are
1729 // installed and can't be uninstalled.
1730 ExtensionService* service = extension_service();
1731 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1733 // Extensions that are force-installed come from an update URL, which defaults
1734 // to the webstore. Use a mock URL for this test with an update manifest
1735 // that includes "good_v1.crx".
1736 base::FilePath path =
1737 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1738 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1740 // Setting the forcelist extension should install "good_v1.crx".
1741 base::ListValue forcelist;
1742 forcelist.Append(new base::StringValue(
1743 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1744 PolicyMap policies;
1745 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1746 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1747 content::WindowedNotificationObserver observer(
1748 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1749 content::NotificationService::AllSources());
1750 UpdateProviderPolicy(policies);
1751 observer.Wait();
1752 // Note: Cannot check that the notification details match the expected
1753 // exception, since the details object has already been freed prior to
1754 // the completion of observer.Wait().
1756 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1758 // The user is not allowed to uninstall force-installed extensions.
1759 UninstallExtension(kGoodCrxId, false);
1761 // The user is not allowed to load an unpacked extension with the
1762 // same ID as a force-installed extension.
1763 LoadUnpackedExtension(kGoodUnpackedExt, false);
1765 // Loading other unpacked extensions are not blocked.
1766 LoadUnpackedExtension(kAppUnpackedExt, true);
1768 const std::string old_version_number =
1769 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1771 base::FilePath test_path;
1772 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1774 TestRequestInterceptor interceptor(
1775 "update.extension",
1776 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1777 interceptor.PushJobCallback(
1778 TestRequestInterceptor::FileJob(
1779 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1781 // Updating the force-installed extension.
1782 extensions::ExtensionUpdater* updater = service->updater();
1783 extensions::ExtensionUpdater::CheckParams params;
1784 params.install_immediately = true;
1785 content::WindowedNotificationObserver update_observer(
1786 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1787 content::NotificationService::AllSources());
1788 updater->CheckNow(params);
1789 update_observer.Wait();
1791 const base::Version* new_version =
1792 service->GetExtensionById(kGoodCrxId, true)->version();
1793 ASSERT_TRUE(new_version->IsValid());
1794 base::Version old_version(old_version_number);
1795 ASSERT_TRUE(old_version.IsValid());
1797 EXPECT_EQ(1, new_version->CompareTo(old_version));
1799 EXPECT_EQ(0u, interceptor.GetPendingSize());
1801 // Wait until any background pages belonging to force-installed extensions
1802 // have been loaded.
1803 extensions::ProcessManager* manager =
1804 extensions::ProcessManager::Get(browser()->profile());
1805 extensions::ProcessManager::FrameSet all_frames = manager->GetAllFrames();
1806 for (extensions::ProcessManager::FrameSet::const_iterator iter =
1807 all_frames.begin();
1808 iter != all_frames.end();) {
1809 content::WebContents* web_contents =
1810 content::WebContents::FromRenderFrameHost(*iter);
1811 ASSERT_TRUE(web_contents);
1812 if (!web_contents->IsLoading()) {
1813 ++iter;
1814 } else {
1815 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1817 // Test activity may have modified the set of extension processes during
1818 // message processing, so re-start the iteration to catch added/removed
1819 // processes.
1820 all_frames = manager->GetAllFrames();
1821 iter = all_frames.begin();
1825 // Test policy-installed extensions are reloaded when killed.
1826 BackgroundContentsService::
1827 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1828 content::WindowedNotificationObserver extension_crashed_observer(
1829 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1830 content::NotificationService::AllSources());
1831 content::WindowedNotificationObserver extension_loaded_observer(
1832 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1833 content::NotificationService::AllSources());
1834 extensions::ExtensionHost* extension_host =
1835 extensions::ProcessManager::Get(browser()->profile())
1836 ->GetBackgroundHostForExtension(kGoodCrxId);
1837 extension_host->render_process_host()->Shutdown(content::RESULT_CODE_KILLED,
1838 false);
1839 extension_crashed_observer.Wait();
1840 extension_loaded_observer.Wait();
1843 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1844 // Verifies that extensions that are recommended-installed by policies are
1845 // installed, can be disabled but not uninstalled.
1846 ExtensionService* service = extension_service();
1847 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1849 base::FilePath path =
1850 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1851 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1853 // Setting the forcelist extension should install "good_v1.crx".
1854 base::DictionaryValue dict_value;
1855 dict_value.SetString(std::string(kGoodCrxId) + "." +
1856 extensions::schema_constants::kInstallationMode,
1857 extensions::schema_constants::kNormalInstalled);
1858 dict_value.SetString(
1859 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1860 url.spec());
1861 PolicyMap policies;
1862 policies.Set(key::kExtensionSettings,
1863 POLICY_LEVEL_MANDATORY,
1864 POLICY_SCOPE_USER,
1865 dict_value.DeepCopy(),
1866 NULL);
1867 content::WindowedNotificationObserver observer(
1868 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1869 content::NotificationService::AllSources());
1870 UpdateProviderPolicy(policies);
1871 observer.Wait();
1873 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1875 // The user is not allowed to uninstall recommended-installed extensions.
1876 UninstallExtension(kGoodCrxId, false);
1878 // Explictly re-enables the extension.
1879 service->EnableExtension(kGoodCrxId);
1881 // But the user is allowed to disable them.
1882 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1883 DisableExtension(kGoodCrxId);
1884 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1887 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1888 // Verifies that extensions are blocked if policy specifies an allowed types
1889 // list and the extension's type is not on that list.
1890 ExtensionService* service = extension_service();
1891 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1892 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1894 base::ListValue allowed_types;
1895 allowed_types.AppendString("hosted_app");
1896 PolicyMap policies;
1897 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1898 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1899 UpdateProviderPolicy(policies);
1901 // "good.crx" is blocked.
1902 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1903 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1905 // "hosted_app.crx" is of a whitelisted type.
1906 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1907 ASSERT_TRUE(hosted_app);
1908 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1909 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1911 // The user can remove the extension.
1912 UninstallExtension(kHostedAppCrxId, true);
1915 // Checks that a click on an extension CRX download triggers the extension
1916 // installation prompt without further user interaction when the source is
1917 // whitelisted by policy.
1918 // Flaky on windows; http://crbug.com/295729 .
1919 #if defined(OS_WIN)
1920 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1921 #else
1922 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1923 #endif
1924 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1925 ExtensionInstallPrompt::g_auto_confirm_for_tests =
1926 ExtensionInstallPrompt::ACCEPT;
1928 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1929 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1930 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1931 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1933 base::ScopedTempDir download_directory;
1934 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1935 DownloadPrefs* download_prefs =
1936 DownloadPrefs::FromBrowserContext(browser()->profile());
1937 download_prefs->SetDownloadPath(download_directory.path());
1939 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1940 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1941 ui_test_utils::NavigateToURL(browser(), download_page_url);
1943 // As long as the policy is not present, extensions are considered dangerous.
1944 content::DownloadTestObserverTerminal download_observer(
1945 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1946 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1947 PerformClick(0, 0);
1948 download_observer.WaitForFinished();
1950 // Install the policy and trigger another download.
1951 base::ListValue install_sources;
1952 install_sources.AppendString(install_source_url.spec());
1953 install_sources.AppendString(referrer_url.spec());
1954 PolicyMap policies;
1955 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1956 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1957 UpdateProviderPolicy(policies);
1959 content::WindowedNotificationObserver observer(
1960 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1961 content::NotificationService::AllSources());
1962 PerformClick(1, 0);
1963 observer.Wait();
1964 // Note: Cannot check that the notification details match the expected
1965 // exception, since the details object has already been freed prior to
1966 // the completion of observer.Wait().
1968 // The first extension shouldn't be present, the second should be there.
1969 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1970 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1973 // Verifies that extensions with version older than the minimum version required
1974 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
1975 // policy changes as well as regular auto-updater scheduled updates.
1976 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequired) {
1977 ExtensionService* service = extension_service();
1978 extensions::ExtensionRegistry* registry =
1979 extensions::ExtensionRegistry::Get(browser()->profile());
1980 extensions::ExtensionPrefs* extension_prefs =
1981 extensions::ExtensionPrefs::Get(browser()->profile());
1983 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
1984 service->updater()->StopTimerForTesting();
1986 // Setup interceptor for extension updates.
1987 base::FilePath test_path;
1988 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1989 TestRequestInterceptor interceptor(
1990 "update.extension",
1991 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1992 interceptor.PushJobCallback(TestRequestInterceptor::BadRequestJob());
1993 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
1994 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1996 // Install the extension.
1997 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
1998 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2000 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2001 // version 1.0.0.0) should still be enabled.
2003 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2004 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.0");
2006 base::RunLoop().RunUntilIdle();
2008 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2010 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2011 // version 1.0.0.0) should now be disabled.
2012 EXPECT_EQ(2u, interceptor.GetPendingSize());
2013 base::RunLoop service_request_run_loop;
2014 interceptor.AddRequestServicedCallback(
2015 service_request_run_loop.QuitClosure());
2017 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2018 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2020 service_request_run_loop.Run();
2021 EXPECT_EQ(1u, interceptor.GetPendingSize());
2023 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2024 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2025 extension_prefs->GetDisableReasons(kGoodCrxId));
2027 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2028 // via the update URL in the manifest of the older version.
2029 EXPECT_EQ(1u, interceptor.GetPendingSize());
2031 content::WindowedNotificationObserver update_observer(
2032 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2033 content::NotificationService::AllSources());
2034 service->updater()->CheckSoon();
2035 update_observer.Wait();
2037 EXPECT_EQ(0u, interceptor.GetPendingSize());
2039 // The extension should be auto-updated to newer version and re-enabled.
2040 EXPECT_EQ("1.0.0.1",
2041 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2042 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2045 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2046 // and orders.
2047 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequiredAlt) {
2048 ExtensionService* service = extension_service();
2049 extensions::ExtensionRegistry* registry =
2050 extensions::ExtensionRegistry::Get(browser()->profile());
2051 extensions::ExtensionPrefs* extension_prefs =
2052 extensions::ExtensionPrefs::Get(browser()->profile());
2054 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2055 service->updater()->StopTimerForTesting();
2057 // Setup interceptor for extension updates.
2058 base::FilePath test_path;
2059 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
2060 TestRequestInterceptor interceptor(
2061 "update.extension",
2062 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
2063 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
2064 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
2066 // Set the policy to require an even higher minimum version this time.
2068 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2069 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.2");
2071 base::RunLoop().RunUntilIdle();
2073 // Install the 1.0.0.0 version, it should be installed but disabled.
2074 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2075 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2076 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2077 extension_prefs->GetDisableReasons(kGoodCrxId));
2078 EXPECT_EQ("1.0.0.0",
2079 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2081 // An extension management policy update should trigger an update as well.
2082 EXPECT_EQ(1u, interceptor.GetPendingSize());
2084 content::WindowedNotificationObserver update_observer(
2085 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2086 content::NotificationService::AllSources());
2088 // Set a higher minimum version, just intend to trigger a policy update.
2089 extensions::ExtensionManagementPolicyUpdater management_policy(
2090 &provider_);
2091 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.3");
2093 base::RunLoop().RunUntilIdle();
2094 update_observer.Wait();
2096 EXPECT_EQ(0u, interceptor.GetPendingSize());
2098 // It should be updated to 1.0.0.1 but remain disabled.
2099 EXPECT_EQ("1.0.0.1",
2100 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2101 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2102 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2103 extension_prefs->GetDisableReasons(kGoodCrxId));
2105 // Remove the minimum version requirement. The extension should be re-enabled.
2107 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2108 management_policy.UnsetMinimumVersionRequired(kGoodCrxId);
2110 base::RunLoop().RunUntilIdle();
2112 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2113 EXPECT_FALSE(extension_prefs->HasDisableReason(
2114 kGoodCrxId, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY));
2117 // Verifies that a force-installed extension which does not meet a subsequently
2118 // set minimum version requirement is handled well.
2119 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionForceInstalled) {
2120 extensions::ExtensionRegistry* registry =
2121 extensions::ExtensionRegistry::Get(browser()->profile());
2122 extensions::ExtensionPrefs* extension_prefs =
2123 extensions::ExtensionPrefs::Get(browser()->profile());
2125 // Prepare the update URL for force installing.
2126 const base::FilePath path =
2127 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
2128 const GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
2130 // Set policy to force-install the extension, it should be installed and
2131 // enabled.
2132 content::WindowedNotificationObserver install_observer(
2133 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2134 content::NotificationService::AllSources());
2135 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2137 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2138 management_policy.SetIndividualExtensionAutoInstalled(kGoodCrxId,
2139 url.spec(), true);
2141 base::RunLoop().RunUntilIdle();
2142 install_observer.Wait();
2144 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2146 // Set policy a minimum version of "1.0.0.1", the extension now should be
2147 // disabled.
2149 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2150 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2152 base::RunLoop().RunUntilIdle();
2153 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2154 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2155 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2156 extension_prefs->GetDisableReasons(kGoodCrxId));
2159 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
2160 #if defined(OS_WIN) && defined(USE_ASH)
2161 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2162 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2163 switches::kAshBrowserTests))
2164 return;
2165 #endif
2167 // Verifies that the homepage can be configured with policies.
2168 // Set a default, and check that the home button navigates there.
2169 browser()->profile()->GetPrefs()->SetString(
2170 prefs::kHomePage, chrome::kChromeUIPolicyURL);
2171 browser()->profile()->GetPrefs()->SetBoolean(
2172 prefs::kHomePageIsNewTabPage, false);
2173 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
2174 browser()->profile()->GetHomePage());
2175 content::WebContents* contents =
2176 browser()->tab_strip_model()->GetActiveWebContents();
2177 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
2178 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2179 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
2181 // Now override with policy.
2182 PolicyMap policies;
2183 policies.Set(key::kHomepageLocation,
2184 POLICY_LEVEL_MANDATORY,
2185 POLICY_SCOPE_USER,
2186 new base::StringValue(chrome::kChromeUICreditsURL),
2187 NULL);
2188 UpdateProviderPolicy(policies);
2189 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2190 content::WaitForLoadStop(contents);
2191 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
2193 policies.Set(key::kHomepageIsNewTabPage,
2194 POLICY_LEVEL_MANDATORY,
2195 POLICY_SCOPE_USER,
2196 new base::FundamentalValue(true),
2197 NULL);
2198 UpdateProviderPolicy(policies);
2199 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2200 content::WaitForLoadStop(contents);
2201 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
2204 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
2205 // Verifies that incognito windows can't be opened when disabled by policy.
2207 const BrowserList* active_browser_list =
2208 BrowserList::GetInstance(chrome::GetActiveDesktop());
2210 // Disable incognito via policy and verify that incognito windows can't be
2211 // opened.
2212 EXPECT_EQ(1u, active_browser_list->size());
2213 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2214 PolicyMap policies;
2215 policies.Set(key::kIncognitoEnabled,
2216 POLICY_LEVEL_MANDATORY,
2217 POLICY_SCOPE_USER,
2218 new base::FundamentalValue(false),
2219 NULL);
2220 UpdateProviderPolicy(policies);
2221 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2222 EXPECT_EQ(1u, active_browser_list->size());
2223 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2225 // Enable via policy and verify that incognito windows can be opened.
2226 policies.Set(key::kIncognitoEnabled,
2227 POLICY_LEVEL_MANDATORY,
2228 POLICY_SCOPE_USER,
2229 new base::FundamentalValue(true),
2230 NULL);
2231 UpdateProviderPolicy(policies);
2232 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2233 EXPECT_EQ(2u, active_browser_list->size());
2234 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2237 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
2238 // Verifies that Javascript can be disabled.
2239 content::WebContents* contents =
2240 browser()->tab_strip_model()->GetActiveWebContents();
2241 EXPECT_TRUE(IsJavascriptEnabled(contents));
2242 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2243 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2244 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2246 // Disable Javascript via policy.
2247 PolicyMap policies;
2248 policies.Set(key::kJavascriptEnabled,
2249 POLICY_LEVEL_MANDATORY,
2250 POLICY_SCOPE_USER,
2251 new base::FundamentalValue(false),
2252 NULL);
2253 UpdateProviderPolicy(policies);
2254 // Reload the page.
2255 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2256 EXPECT_FALSE(IsJavascriptEnabled(contents));
2257 // Developer tools still work when javascript is disabled.
2258 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2259 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2260 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2261 // Javascript is always enabled for the internal pages.
2262 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
2263 EXPECT_TRUE(IsJavascriptEnabled(contents));
2265 // The javascript content setting policy overrides the javascript policy.
2266 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2267 EXPECT_FALSE(IsJavascriptEnabled(contents));
2268 policies.Set(key::kDefaultJavaScriptSetting,
2269 POLICY_LEVEL_MANDATORY,
2270 POLICY_SCOPE_USER,
2271 new base::FundamentalValue(CONTENT_SETTING_ALLOW),
2272 NULL);
2273 UpdateProviderPolicy(policies);
2274 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2275 EXPECT_TRUE(IsJavascriptEnabled(contents));
2278 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2279 PrefService* prefs = browser()->profile()->GetPrefs();
2281 // Enabled by default.
2282 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2284 // Disable by old, deprecated policy.
2285 PolicyMap policies;
2286 policies.Set(key::kDnsPrefetchingEnabled,
2287 POLICY_LEVEL_MANDATORY,
2288 POLICY_SCOPE_USER,
2289 new base::FundamentalValue(false),
2290 NULL);
2291 UpdateProviderPolicy(policies);
2293 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2295 // Enabled by new policy, this should override old one.
2296 policies.Set(
2297 key::kNetworkPredictionOptions,
2298 POLICY_LEVEL_MANDATORY,
2299 POLICY_SCOPE_USER,
2300 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2301 NULL);
2302 UpdateProviderPolicy(policies);
2304 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2307 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2308 // Verifies that browsing history is not saved.
2309 PolicyMap policies;
2310 policies.Set(key::kSavingBrowserHistoryDisabled,
2311 POLICY_LEVEL_MANDATORY,
2312 POLICY_SCOPE_USER,
2313 new base::FundamentalValue(true),
2314 NULL);
2315 UpdateProviderPolicy(policies);
2316 GURL url = ui_test_utils::GetTestUrl(
2317 base::FilePath(base::FilePath::kCurrentDirectory),
2318 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2319 ui_test_utils::NavigateToURL(browser(), url);
2320 // Verify that the navigation wasn't saved in the history.
2321 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2322 EXPECT_EQ(0u, enumerator1.urls().size());
2324 // Now flip the policy and try again.
2325 policies.Set(key::kSavingBrowserHistoryDisabled,
2326 POLICY_LEVEL_MANDATORY,
2327 POLICY_SCOPE_USER,
2328 new base::FundamentalValue(false),
2329 NULL);
2330 UpdateProviderPolicy(policies);
2331 ui_test_utils::NavigateToURL(browser(), url);
2332 // Verify that the navigation was saved in the history.
2333 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2334 ASSERT_EQ(1u, enumerator2.urls().size());
2335 EXPECT_EQ(url, enumerator2.urls()[0]);
2338 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2339 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2340 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2341 if (TranslateService::IsTranslateBubbleEnabled())
2342 return;
2344 scoped_ptr<test::CldDataHarness> cld_data_scope =
2345 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2346 ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2348 // Verifies that translate can be forced enabled or disabled by policy.
2350 // Get the InfoBarService, and verify that there are no infobars on startup.
2351 content::WebContents* contents =
2352 browser()->tab_strip_model()->GetActiveWebContents();
2353 ASSERT_TRUE(contents);
2354 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2355 ASSERT_TRUE(infobar_service);
2356 EXPECT_EQ(0u, infobar_service->infobar_count());
2358 // Force enable the translate feature.
2359 PolicyMap policies;
2360 policies.Set(key::kTranslateEnabled,
2361 POLICY_LEVEL_MANDATORY,
2362 POLICY_SCOPE_USER,
2363 new base::FundamentalValue(true),
2364 NULL);
2365 UpdateProviderPolicy(policies);
2366 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2367 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2368 // TranslateManager observes. This allows checking that an infobar is NOT
2369 // shown below, without polling for infobars for some indeterminate amount
2370 // of time.
2371 GURL url = ui_test_utils::GetTestUrl(
2372 base::FilePath(),
2373 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2374 content::WindowedNotificationObserver language_observer1(
2375 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2376 content::NotificationService::AllSources());
2377 ui_test_utils::NavigateToURL(browser(), url);
2378 language_observer1.Wait();
2380 // Verify the translation detected for this tab.
2381 ChromeTranslateClient* chrome_translate_client =
2382 ChromeTranslateClient::FromWebContents(contents);
2383 ASSERT_TRUE(chrome_translate_client);
2384 translate::LanguageState& language_state =
2385 chrome_translate_client->GetLanguageState();
2386 EXPECT_EQ("fr", language_state.original_language());
2387 EXPECT_TRUE(language_state.page_needs_translation());
2388 EXPECT_FALSE(language_state.translation_pending());
2389 EXPECT_FALSE(language_state.translation_declined());
2390 EXPECT_FALSE(language_state.IsPageTranslated());
2392 // Verify that the translate infobar showed up.
2393 ASSERT_EQ(1u, infobar_service->infobar_count());
2394 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2395 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2396 infobar->delegate()->AsTranslateInfoBarDelegate();
2397 ASSERT_TRUE(translate_infobar_delegate);
2398 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2399 translate_infobar_delegate->translate_step());
2400 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2402 // Now force disable translate.
2403 infobar_service->RemoveInfoBar(infobar);
2404 EXPECT_EQ(0u, infobar_service->infobar_count());
2405 policies.Set(key::kTranslateEnabled,
2406 POLICY_LEVEL_MANDATORY,
2407 POLICY_SCOPE_USER,
2408 new base::FundamentalValue(false),
2409 NULL);
2410 UpdateProviderPolicy(policies);
2411 // Navigating to the same URL now doesn't trigger an infobar.
2412 content::WindowedNotificationObserver language_observer2(
2413 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2414 content::NotificationService::AllSources());
2415 ui_test_utils::NavigateToURL(browser(), url);
2416 language_observer2.Wait();
2417 EXPECT_EQ(0u, infobar_service->infobar_count());
2420 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2421 // Checks that URLs can be blacklisted, and that exceptions can be made to
2422 // the blacklist.
2424 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2425 // as URLRequestMockHTTPJobs.
2426 const char* kURLS[] = {
2427 "http://aaa.com/empty.html",
2428 "http://bbb.com/empty.html",
2429 "http://sub.bbb.com/empty.html",
2430 "http://bbb.com/policy/blank.html",
2433 base::RunLoop loop;
2434 BrowserThread::PostTaskAndReply(
2435 BrowserThread::IO, FROM_HERE,
2436 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2437 loop.QuitClosure());
2438 loop.Run();
2441 // Verify that "bbb.com" opens before applying the blacklist.
2442 CheckCanOpenURL(browser(), kURLS[1]);
2444 // Set a blacklist.
2445 base::ListValue blacklist;
2446 blacklist.Append(new base::StringValue("bbb.com"));
2447 PolicyMap policies;
2448 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2449 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2450 UpdateProviderPolicy(policies);
2451 FlushBlacklistPolicy();
2452 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2453 CheckCanOpenURL(browser(), kURLS[0]);
2454 for (size_t i = 1; i < arraysize(kURLS); ++i)
2455 CheckURLIsBlocked(browser(), kURLS[i]);
2457 // Whitelist some sites of bbb.com.
2458 base::ListValue whitelist;
2459 whitelist.Append(new base::StringValue("sub.bbb.com"));
2460 whitelist.Append(new base::StringValue("bbb.com/policy"));
2461 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2462 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2463 UpdateProviderPolicy(policies);
2464 FlushBlacklistPolicy();
2465 CheckURLIsBlocked(browser(), kURLS[1]);
2466 CheckCanOpenURL(browser(), kURLS[2]);
2467 CheckCanOpenURL(browser(), kURLS[3]);
2470 base::RunLoop loop;
2471 BrowserThread::PostTaskAndReply(
2472 BrowserThread::IO, FROM_HERE,
2473 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2474 loop.QuitClosure());
2475 loop.Run();
2479 #if defined(OS_MACOSX)
2480 // http://crbug.com/339240
2481 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2482 #else
2483 #define MAYBE_FileURLBlacklist FileURLBlacklist
2484 #endif
2485 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2486 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2487 // with URLblacklisting and URLwhitelisting.
2489 base::FilePath test_path;
2490 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2491 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2492 const std::string folder_path = base_path + "apptest/";
2493 const std::string file_path1 = base_path + "title1.html";
2494 const std::string file_path2 = folder_path + "basic.html";
2496 CheckCanOpenURL(browser(), file_path1.c_str());
2497 CheckCanOpenURL(browser(), file_path2.c_str());
2499 // Set a blacklist for all the files.
2500 base::ListValue blacklist;
2501 blacklist.Append(new base::StringValue("file://*"));
2502 PolicyMap policies;
2503 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2504 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2505 UpdateProviderPolicy(policies);
2506 FlushBlacklistPolicy();
2508 CheckURLIsBlocked(browser(), file_path1.c_str());
2509 CheckURLIsBlocked(browser(), file_path2.c_str());
2511 // Replace the URLblacklist with disabling the file scheme.
2512 blacklist.Remove(base::StringValue("file://*"), NULL);
2513 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2514 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2515 UpdateProviderPolicy(policies);
2516 FlushBlacklistPolicy();
2518 PrefService* prefs = browser()->profile()->GetPrefs();
2519 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2520 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2521 list_url->end());
2523 base::ListValue disabledscheme;
2524 disabledscheme.Append(new base::StringValue("file"));
2525 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2526 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2527 UpdateProviderPolicy(policies);
2528 FlushBlacklistPolicy();
2530 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2531 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2532 list_url->end());
2534 // Whitelist one folder and blacklist an another just inside.
2535 base::ListValue whitelist;
2536 whitelist.Append(new base::StringValue(base_path));
2537 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2538 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2539 blacklist.Append(new base::StringValue(folder_path));
2540 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2541 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2542 UpdateProviderPolicy(policies);
2543 FlushBlacklistPolicy();
2545 CheckCanOpenURL(browser(), file_path1.c_str());
2546 CheckURLIsBlocked(browser(), file_path2.c_str());
2549 static bool IsMinSSLVersionTLS12(Profile* profile) {
2550 scoped_refptr<net::SSLConfigService> config_service(
2551 profile->GetSSLConfigService());
2552 net::SSLConfig config;
2553 config_service->GetSSLConfig(&config);
2554 return config.version_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2557 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionMin) {
2558 PrefService* prefs = g_browser_process->local_state();
2560 const std::string new_value("tls1.2");
2561 const std::string default_value(prefs->GetString(prefs::kSSLVersionMin));
2563 EXPECT_NE(default_value, new_value);
2564 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2566 PolicyMap policies;
2567 policies.Set(key::kSSLVersionMin,
2568 POLICY_LEVEL_MANDATORY,
2569 POLICY_SCOPE_USER,
2570 new base::StringValue(new_value),
2571 NULL);
2572 UpdateProviderPolicy(policies);
2574 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2577 static bool IsMinSSLFallbackVersionTLS12(Profile* profile) {
2578 scoped_refptr<net::SSLConfigService> config_service(
2579 profile->GetSSLConfigService());
2580 net::SSLConfig config;
2581 config_service->GetSSLConfig(&config);
2582 return config.version_fallback_min == net::SSL_PROTOCOL_VERSION_TLS1_2;
2585 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2586 PrefService* prefs = g_browser_process->local_state();
2588 const std::string new_value("tls1.2");
2589 const std::string default_value(
2590 prefs->GetString(prefs::kSSLVersionFallbackMin));
2592 EXPECT_NE(default_value, new_value);
2593 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2595 PolicyMap policies;
2596 policies.Set(key::kSSLVersionFallbackMin,
2597 POLICY_LEVEL_MANDATORY,
2598 POLICY_SCOPE_USER,
2599 new base::StringValue(new_value),
2600 NULL);
2601 UpdateProviderPolicy(policies);
2603 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2606 #if !defined(OS_MACOSX)
2607 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2608 PolicyMap policies;
2609 policies.Set(key::kFullscreenAllowed,
2610 POLICY_LEVEL_MANDATORY,
2611 POLICY_SCOPE_USER,
2612 new base::FundamentalValue(false),
2613 NULL);
2614 UpdateProviderPolicy(policies);
2616 BrowserWindow* browser_window = browser()->window();
2617 ASSERT_TRUE(browser_window);
2619 EXPECT_FALSE(browser_window->IsFullscreen());
2620 chrome::ToggleFullscreenMode(browser());
2621 EXPECT_FALSE(browser_window->IsFullscreen());
2624 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2625 PolicyMap policies;
2626 policies.Set(key::kFullscreenAllowed,
2627 POLICY_LEVEL_MANDATORY,
2628 POLICY_SCOPE_USER,
2629 new base::FundamentalValue(false),
2630 NULL);
2631 UpdateProviderPolicy(policies);
2633 const extensions::Extension* extension =
2634 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2635 ASSERT_TRUE(extension);
2637 // Launch an app that tries to open a fullscreen window.
2638 TestAddAppWindowObserver add_window_observer(
2639 extensions::AppWindowRegistry::Get(browser()->profile()));
2640 OpenApplication(AppLaunchParams(browser()->profile(), extension,
2641 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW,
2642 extensions::SOURCE_TEST));
2643 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2644 ASSERT_TRUE(window);
2646 // Verify that the window is not in fullscreen mode.
2647 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2649 // Verify that the window cannot be toggled into fullscreen mode via apps
2650 // APIs.
2651 EXPECT_TRUE(content::ExecuteScript(
2652 window->web_contents(),
2653 "chrome.app.window.current().fullscreen();"));
2654 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2656 // Verify that the window cannot be toggled into fullscreen mode from within
2657 // Chrome (e.g., using keyboard accelerators).
2658 window->Fullscreen();
2659 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2661 #endif
2663 #if defined(OS_CHROMEOS)
2664 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2665 int screenshot_count = CountScreenshots();
2667 // Make sure screenshots are counted correctly.
2668 TestScreenshotFile(true);
2669 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2671 // Check if trying to take a screenshot fails when disabled by policy.
2672 TestScreenshotFile(false);
2673 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2676 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2677 // Set up the mock observer.
2678 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2679 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2680 audio_handler->AddAudioObserver(test_observer.get());
2682 bool prior_state = audio_handler->IsOutputMuted();
2683 // Make sure the audio is not muted and then toggle the policy and observe
2684 // if the output mute changed event is fired.
2685 audio_handler->SetOutputMute(false);
2686 EXPECT_FALSE(audio_handler->IsOutputMuted());
2687 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2688 PolicyMap policies;
2689 policies.Set(key::kAudioOutputAllowed,
2690 POLICY_LEVEL_MANDATORY,
2691 POLICY_SCOPE_USER,
2692 new base::FundamentalValue(false),
2693 NULL);
2694 UpdateProviderPolicy(policies);
2695 EXPECT_TRUE(audio_handler->IsOutputMuted());
2696 // This should not change the state now and should not trigger output mute
2697 // changed event.
2698 audio_handler->SetOutputMute(false);
2699 EXPECT_TRUE(audio_handler->IsOutputMuted());
2700 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2702 // Toggle back and observe if the output mute changed event is fired.
2703 policies.Set(key::kAudioOutputAllowed,
2704 POLICY_LEVEL_MANDATORY,
2705 POLICY_SCOPE_USER,
2706 new base::FundamentalValue(true),
2707 NULL);
2708 UpdateProviderPolicy(policies);
2709 EXPECT_FALSE(audio_handler->IsOutputMuted());
2710 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2711 audio_handler->SetOutputMute(true);
2712 EXPECT_TRUE(audio_handler->IsOutputMuted());
2713 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2714 // Revert the prior state.
2715 audio_handler->SetOutputMute(prior_state);
2716 audio_handler->RemoveAudioObserver(test_observer.get());
2719 // Disabled, see http://crbug.com/315308.
2720 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2721 // Indicate that the session started 2 hours ago and no user activity has
2722 // occurred yet.
2723 g_browser_process->local_state()->SetInt64(
2724 prefs::kSessionStartTime,
2725 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2726 .ToInternalValue());
2729 // Disabled, see http://crbug.com/315308.
2730 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2731 content::MockNotificationObserver observer;
2732 content::NotificationRegistrar registrar;
2733 registrar.Add(&observer,
2734 chrome::NOTIFICATION_APP_TERMINATING,
2735 content::NotificationService::AllSources());
2737 // Set the session length limit to 3 hours. Verify that the session is not
2738 // terminated.
2739 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2740 .Times(0);
2741 PolicyMap policies;
2742 policies.Set(key::kSessionLengthLimit,
2743 POLICY_LEVEL_MANDATORY,
2744 POLICY_SCOPE_USER,
2745 new base::FundamentalValue(kThreeHoursInMs),
2746 NULL);
2747 UpdateProviderPolicy(policies);
2748 base::RunLoop().RunUntilIdle();
2749 Mock::VerifyAndClearExpectations(&observer);
2751 // Decrease the session length limit to 1 hour. Verify that the session is
2752 // terminated immediately.
2753 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2754 policies.Set(key::kSessionLengthLimit,
2755 POLICY_LEVEL_MANDATORY,
2756 POLICY_SCOPE_USER,
2757 new base::FundamentalValue(kOneHourInMs),
2758 NULL);
2759 UpdateProviderPolicy(policies);
2760 base::RunLoop().RunUntilIdle();
2761 Mock::VerifyAndClearExpectations(&observer);
2764 // Disabled, see http://crbug.com/315308.
2765 IN_PROC_BROWSER_TEST_F(PolicyTest,
2766 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2767 // Indicate that the session started 2 hours ago and no user activity has
2768 // occurred yet.
2769 g_browser_process->local_state()->SetInt64(
2770 prefs::kSessionStartTime,
2771 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2772 .ToInternalValue());
2775 // Disabled, see http://crbug.com/315308.
2776 IN_PROC_BROWSER_TEST_F(PolicyTest,
2777 DISABLED_WaitForInitialUserActivityUsatisfied) {
2778 content::MockNotificationObserver observer;
2779 content::NotificationRegistrar registrar;
2780 registrar.Add(&observer,
2781 chrome::NOTIFICATION_APP_TERMINATING,
2782 content::NotificationService::AllSources());
2784 // Require initial user activity.
2785 PolicyMap policies;
2786 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2787 POLICY_SCOPE_USER,
2788 new base::FundamentalValue(true),
2789 NULL);
2790 UpdateProviderPolicy(policies);
2791 base::RunLoop().RunUntilIdle();
2793 // Set the session length limit to 1 hour. Verify that the session is not
2794 // terminated.
2795 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2796 .Times(0);
2797 policies.Set(key::kSessionLengthLimit,
2798 POLICY_LEVEL_MANDATORY,
2799 POLICY_SCOPE_USER,
2800 new base::FundamentalValue(kOneHourInMs),
2801 NULL);
2802 UpdateProviderPolicy(policies);
2803 base::RunLoop().RunUntilIdle();
2804 Mock::VerifyAndClearExpectations(&observer);
2807 // Disabled, see http://crbug.com/315308.
2808 IN_PROC_BROWSER_TEST_F(PolicyTest,
2809 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2810 // Indicate that initial user activity in this session occurred 2 hours ago.
2811 g_browser_process->local_state()->SetInt64(
2812 prefs::kSessionStartTime,
2813 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2814 .ToInternalValue());
2815 g_browser_process->local_state()->SetBoolean(
2816 prefs::kSessionUserActivitySeen,
2817 true);
2820 // Disabled, see http://crbug.com/315308.
2821 IN_PROC_BROWSER_TEST_F(PolicyTest,
2822 DISABLED_WaitForInitialUserActivitySatisfied) {
2823 content::MockNotificationObserver observer;
2824 content::NotificationRegistrar registrar;
2825 registrar.Add(&observer,
2826 chrome::NOTIFICATION_APP_TERMINATING,
2827 content::NotificationService::AllSources());
2829 // Require initial user activity and set the session length limit to 3 hours.
2830 // Verify that the session is not terminated.
2831 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2832 .Times(0);
2833 PolicyMap policies;
2834 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2835 POLICY_SCOPE_USER,
2836 new base::FundamentalValue(true),
2837 NULL);
2838 policies.Set(key::kSessionLengthLimit,
2839 POLICY_LEVEL_MANDATORY,
2840 POLICY_SCOPE_USER,
2841 new base::FundamentalValue(kThreeHoursInMs),
2842 NULL);
2843 UpdateProviderPolicy(policies);
2844 base::RunLoop().RunUntilIdle();
2845 Mock::VerifyAndClearExpectations(&observer);
2847 // Decrease the session length limit to 1 hour. Verify that the session is
2848 // terminated immediately.
2849 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2850 policies.Set(key::kSessionLengthLimit,
2851 POLICY_LEVEL_MANDATORY,
2852 POLICY_SCOPE_USER,
2853 new base::FundamentalValue(kOneHourInMs),
2854 NULL);
2855 UpdateProviderPolicy(policies);
2856 base::RunLoop().RunUntilIdle();
2857 Mock::VerifyAndClearExpectations(&observer);
2860 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2861 // Verifies that the large cursor accessibility feature can be controlled
2862 // through policy.
2863 chromeos::AccessibilityManager* accessibility_manager =
2864 chromeos::AccessibilityManager::Get();
2866 // Manually enable the large cursor.
2867 accessibility_manager->EnableLargeCursor(true);
2868 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2870 // Verify that policy overrides the manual setting.
2871 PolicyMap policies;
2872 policies.Set(key::kLargeCursorEnabled,
2873 POLICY_LEVEL_MANDATORY,
2874 POLICY_SCOPE_USER,
2875 new base::FundamentalValue(false),
2876 NULL);
2877 UpdateProviderPolicy(policies);
2878 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2880 // Verify that the large cursor cannot be enabled manually anymore.
2881 accessibility_manager->EnableLargeCursor(true);
2882 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2885 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2886 // Verifies that the spoken feedback accessibility feature can be controlled
2887 // through policy.
2888 chromeos::AccessibilityManager* accessibility_manager =
2889 chromeos::AccessibilityManager::Get();
2891 // Manually enable spoken feedback.
2892 accessibility_manager->EnableSpokenFeedback(
2893 true, ui::A11Y_NOTIFICATION_NONE);
2894 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2896 // Verify that policy overrides the manual setting.
2897 PolicyMap policies;
2898 policies.Set(key::kSpokenFeedbackEnabled,
2899 POLICY_LEVEL_MANDATORY,
2900 POLICY_SCOPE_USER,
2901 new base::FundamentalValue(false),
2902 NULL);
2903 UpdateProviderPolicy(policies);
2904 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2906 // Verify that spoken feedback cannot be enabled manually anymore.
2907 accessibility_manager->EnableSpokenFeedback(
2908 true, ui::A11Y_NOTIFICATION_NONE);
2909 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2912 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2913 // Verifies that the high contrast mode accessibility feature can be
2914 // controlled through policy.
2915 chromeos::AccessibilityManager* accessibility_manager =
2916 chromeos::AccessibilityManager::Get();
2918 // Manually enable high contrast mode.
2919 accessibility_manager->EnableHighContrast(true);
2920 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2922 // Verify that policy overrides the manual setting.
2923 PolicyMap policies;
2924 policies.Set(key::kHighContrastEnabled,
2925 POLICY_LEVEL_MANDATORY,
2926 POLICY_SCOPE_USER,
2927 new base::FundamentalValue(false),
2928 NULL);
2929 UpdateProviderPolicy(policies);
2930 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2932 // Verify that high contrast mode cannot be enabled manually anymore.
2933 accessibility_manager->EnableHighContrast(true);
2934 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2937 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2938 // Verifies that the screen magnifier can be disabled through policy.
2939 chromeos::MagnificationManager* magnification_manager =
2940 chromeos::MagnificationManager::Get();
2942 // Manually enable the full-screen magnifier.
2943 magnification_manager->SetMagnifierType(ui::MAGNIFIER_FULL);
2944 magnification_manager->SetMagnifierEnabled(true);
2945 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2946 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2948 // Verify that policy overrides the manual setting.
2949 PolicyMap policies;
2950 policies.Set(key::kScreenMagnifierType,
2951 POLICY_LEVEL_MANDATORY,
2952 POLICY_SCOPE_USER,
2953 new base::FundamentalValue(0),
2954 NULL);
2955 UpdateProviderPolicy(policies);
2956 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2958 // Verify that the screen magnifier cannot be enabled manually anymore.
2959 magnification_manager->SetMagnifierEnabled(true);
2960 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2963 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2964 // Verifies that the full-screen magnifier can be enabled through policy.
2965 chromeos::MagnificationManager* magnification_manager =
2966 chromeos::MagnificationManager::Get();
2968 // Verify that the screen magnifier is initially disabled.
2969 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2971 // Verify that policy can enable the full-screen magnifier.
2972 PolicyMap policies;
2973 policies.Set(key::kScreenMagnifierType,
2974 POLICY_LEVEL_MANDATORY,
2975 POLICY_SCOPE_USER,
2976 new base::FundamentalValue(ui::MAGNIFIER_FULL),
2977 NULL);
2978 UpdateProviderPolicy(policies);
2979 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2980 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2982 // Verify that the screen magnifier cannot be disabled manually anymore.
2983 magnification_manager->SetMagnifierEnabled(false);
2984 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2987 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
2988 // Verifies that the on-screen keyboard accessibility feature can be
2989 // controlled through policy.
2990 chromeos::AccessibilityManager* accessibility_manager =
2991 chromeos::AccessibilityManager::Get();
2993 // Manually enable the on-screen keyboard.
2994 accessibility_manager->EnableVirtualKeyboard(true);
2995 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2997 // Verify that policy overrides the manual setting.
2998 PolicyMap policies;
2999 policies.Set(key::kVirtualKeyboardEnabled,
3000 POLICY_LEVEL_MANDATORY,
3001 POLICY_SCOPE_USER,
3002 new base::FundamentalValue(false),
3003 NULL);
3004 UpdateProviderPolicy(policies);
3005 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3007 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3008 accessibility_manager->EnableVirtualKeyboard(true);
3009 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3012 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
3013 // Verify keyboard disabled by default.
3014 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3015 // Verify keyboard can be toggled by default.
3016 keyboard::SetTouchKeyboardEnabled(true);
3017 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3018 keyboard::SetTouchKeyboardEnabled(false);
3019 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3021 // Verify enabling the policy takes effect immediately and that that user
3022 // cannot disable the keyboard..
3023 PolicyMap policies;
3024 policies.Set(key::kTouchVirtualKeyboardEnabled,
3025 POLICY_LEVEL_MANDATORY,
3026 POLICY_SCOPE_USER,
3027 new base::FundamentalValue(true),
3028 NULL);
3029 UpdateProviderPolicy(policies);
3030 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3031 keyboard::SetTouchKeyboardEnabled(false);
3032 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3034 // Verify that disabling the policy takes effect immediately and that the user
3035 // cannot enable the keyboard.
3036 policies.Set(key::kTouchVirtualKeyboardEnabled,
3037 POLICY_LEVEL_MANDATORY,
3038 POLICY_SCOPE_USER,
3039 new base::FundamentalValue(false),
3040 NULL);
3041 UpdateProviderPolicy(policies);
3042 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3043 keyboard::SetTouchKeyboardEnabled(true);
3044 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3047 #endif
3049 namespace {
3051 static const char* kRestoredURLs[] = {
3052 "http://aaa.com/empty.html",
3053 "http://bbb.com/empty.html",
3056 bool IsNonSwitchArgument(const base::CommandLine::StringType& s) {
3057 return s.empty() || s[0] != '-';
3060 } // namespace
3062 // Similar to PolicyTest but allows setting policies before the browser is
3063 // created. Each test parameter is a method that sets up the early policies
3064 // and stores the expected startup URLs in |expected_urls_|.
3065 class RestoreOnStartupPolicyTest
3066 : public PolicyTest,
3067 public testing::WithParamInterface<
3068 void (RestoreOnStartupPolicyTest::*)(void)> {
3069 public:
3070 RestoreOnStartupPolicyTest() {}
3071 virtual ~RestoreOnStartupPolicyTest() {}
3073 #if defined(OS_CHROMEOS)
3074 void SetUpCommandLine(base::CommandLine* command_line) override {
3075 // TODO(nkostylev): Investigate if we can remove this switch.
3076 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
3077 PolicyTest::SetUpCommandLine(command_line);
3079 #endif
3081 void SetUpInProcessBrowserTestFixture() override {
3082 PolicyTest::SetUpInProcessBrowserTestFixture();
3083 // Set early policies now, before the browser is created.
3084 (this->*(GetParam()))();
3086 // Remove the non-switch arguments, so that session restore kicks in for
3087 // these tests.
3088 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
3089 base::CommandLine::StringVector argv = command_line->argv();
3090 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
3091 argv.end());
3092 command_line->InitFromArgv(argv);
3093 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
3094 command_line->argv().begin()));
3097 void SetUpOnMainThread() override {
3098 BrowserThread::PostTask(
3099 BrowserThread::IO,
3100 FROM_HERE,
3101 base::Bind(
3102 RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
3105 void HomepageIsNotNTP() {
3106 // Verifies that policy can set the startup pages to the homepage, when
3107 // the homepage is not the NTP.
3108 PolicyMap policies;
3109 policies.Set(
3110 key::kRestoreOnStartup,
3111 POLICY_LEVEL_MANDATORY,
3112 POLICY_SCOPE_USER,
3113 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3114 NULL);
3115 policies.Set(key::kHomepageIsNewTabPage,
3116 POLICY_LEVEL_MANDATORY,
3117 POLICY_SCOPE_USER,
3118 new base::FundamentalValue(false),
3119 NULL);
3120 policies.Set(key::kHomepageLocation,
3121 POLICY_LEVEL_MANDATORY,
3122 POLICY_SCOPE_USER,
3123 new base::StringValue(kRestoredURLs[1]),
3124 NULL);
3125 provider_.UpdateChromePolicy(policies);
3127 expected_urls_.push_back(GURL(kRestoredURLs[1]));
3130 void HomepageIsNTP() {
3131 // Verifies that policy can set the startup pages to the homepage, when
3132 // the homepage is the NTP.
3133 PolicyMap policies;
3134 policies.Set(
3135 key::kRestoreOnStartup,
3136 POLICY_LEVEL_MANDATORY,
3137 POLICY_SCOPE_USER,
3138 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3139 NULL);
3140 policies.Set(key::kHomepageIsNewTabPage,
3141 POLICY_LEVEL_MANDATORY,
3142 POLICY_SCOPE_USER,
3143 new base::FundamentalValue(true),
3144 NULL);
3145 provider_.UpdateChromePolicy(policies);
3147 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3150 void ListOfURLs() {
3151 // Verifies that policy can set the startup pages to a list of URLs.
3152 base::ListValue urls;
3153 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
3154 urls.Append(new base::StringValue(kRestoredURLs[i]));
3155 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3157 PolicyMap policies;
3158 policies.Set(key::kRestoreOnStartup,
3159 POLICY_LEVEL_MANDATORY,
3160 POLICY_SCOPE_USER,
3161 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
3162 NULL);
3163 policies.Set(
3164 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3165 urls.DeepCopy(), NULL);
3166 provider_.UpdateChromePolicy(policies);
3169 void NTP() {
3170 // Verifies that policy can set the startup page to the NTP.
3171 PolicyMap policies;
3172 policies.Set(
3173 key::kRestoreOnStartup,
3174 POLICY_LEVEL_MANDATORY,
3175 POLICY_SCOPE_USER,
3176 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
3177 NULL);
3178 provider_.UpdateChromePolicy(policies);
3179 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3182 void Last() {
3183 // Verifies that policy can set the startup pages to the last session.
3184 PolicyMap policies;
3185 policies.Set(key::kRestoreOnStartup,
3186 POLICY_LEVEL_MANDATORY,
3187 POLICY_SCOPE_USER,
3188 new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
3189 NULL);
3190 provider_.UpdateChromePolicy(policies);
3191 // This should restore the tabs opened at PRE_RunTest below.
3192 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
3193 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3196 std::vector<GURL> expected_urls_;
3199 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
3200 // Open some tabs to verify if they are restored after the browser restarts.
3201 // Most policy settings override this, except kPrefValueLast which enforces
3202 // a restore.
3203 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
3204 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
3205 content::WindowedNotificationObserver observer(
3206 content::NOTIFICATION_LOAD_STOP,
3207 content::NotificationService::AllSources());
3208 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
3209 ui::PAGE_TRANSITION_LINK);
3210 observer.Wait();
3214 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
3215 #if defined(OS_WIN) && defined(USE_ASH)
3216 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3217 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3218 switches::kAshBrowserTests))
3219 return;
3220 #endif
3222 TabStripModel* model = browser()->tab_strip_model();
3223 int size = static_cast<int>(expected_urls_.size());
3224 EXPECT_EQ(size, model->count());
3225 for (int i = 0; i < size && i < model->count(); ++i) {
3226 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
3230 INSTANTIATE_TEST_CASE_P(
3231 RestoreOnStartupPolicyTestInstance,
3232 RestoreOnStartupPolicyTest,
3233 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
3234 &RestoreOnStartupPolicyTest::HomepageIsNTP,
3235 &RestoreOnStartupPolicyTest::ListOfURLs,
3236 &RestoreOnStartupPolicyTest::NTP,
3237 &RestoreOnStartupPolicyTest::Last));
3239 // Similar to PolicyTest but sets a couple of policies before the browser is
3240 // started.
3241 class PolicyStatisticsCollectorTest : public PolicyTest {
3242 public:
3243 PolicyStatisticsCollectorTest() {}
3244 ~PolicyStatisticsCollectorTest() override {}
3246 void SetUpInProcessBrowserTestFixture() override {
3247 PolicyTest::SetUpInProcessBrowserTestFixture();
3248 PolicyMap policies;
3249 policies.Set(key::kShowHomeButton,
3250 POLICY_LEVEL_MANDATORY,
3251 POLICY_SCOPE_USER,
3252 new base::FundamentalValue(true),
3253 NULL);
3254 policies.Set(key::kBookmarkBarEnabled,
3255 POLICY_LEVEL_MANDATORY,
3256 POLICY_SCOPE_USER,
3257 new base::FundamentalValue(false),
3258 NULL);
3259 policies.Set(key::kHomepageLocation,
3260 POLICY_LEVEL_MANDATORY,
3261 POLICY_SCOPE_USER,
3262 new base::StringValue("http://chromium.org"),
3263 NULL);
3264 provider_.UpdateChromePolicy(policies);
3268 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
3269 // Verifies that policy usage histograms are collected at startup.
3271 // BrowserPolicyConnector::Init() has already been called. Make sure the
3272 // CompleteInitialization() task has executed as well.
3273 content::RunAllPendingInMessageLoop();
3275 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
3276 std::string(url::kStandardSchemeSeparator) +
3277 std::string(content::kChromeUIHistogramHost));
3278 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3279 content::WebContents* contents =
3280 browser()->tab_strip_model()->GetActiveWebContents();
3281 std::string text;
3282 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3283 contents,
3284 "var nodes = document.querySelectorAll('body > pre');"
3285 "var result = '';"
3286 "for (var i = 0; i < nodes.length; ++i) {"
3287 " var text = nodes[i].innerHTML;"
3288 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3289 " result = text;"
3290 " break;"
3291 " }"
3293 "domAutomationController.send(result);",
3294 &text));
3295 ASSERT_FALSE(text.empty());
3296 const std::string kExpectedLabel =
3297 "Histogram: Enterprise.Policies recorded 3 samples";
3298 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3299 // HomepageLocation has policy ID 1.
3300 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
3301 // ShowHomeButton has policy ID 35.
3302 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
3303 // BookmarkBarEnabled has policy ID 82.
3304 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
3307 class MediaStreamDevicesControllerBrowserTest
3308 : public PolicyTest,
3309 public testing::WithParamInterface<bool> {
3310 public:
3311 MediaStreamDevicesControllerBrowserTest()
3312 : request_url_allowed_via_whitelist_(false) {
3313 policy_value_ = GetParam();
3315 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3317 // Configure a given policy map.
3318 // The |policy_name| is the name of either the audio or video capture allow
3319 // policy and must never be NULL.
3320 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3321 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3322 // and the whitelist policy is set to contain either the |allow_rule| (if
3323 // non-NULL) or an "allow all" wildcard.
3324 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3325 const char* whitelist_policy,
3326 const char* allow_rule) {
3327 policies->Set(policy_name,
3328 POLICY_LEVEL_MANDATORY,
3329 POLICY_SCOPE_USER,
3330 new base::FundamentalValue(policy_value_),
3331 NULL);
3333 if (whitelist_policy) {
3334 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3335 // in the media exceptions UI.
3336 // See discussion here: https://codereview.chromium.org/15738004/
3337 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3338 switches::kKioskMode);
3340 // Add an entry to the whitelist that allows the specified URL regardless
3341 // of the setting of kAudioCapturedAllowed.
3342 request_url_ = GURL("http://www.example.com/foo");
3343 base::ListValue* list = new base::ListValue();
3344 if (allow_rule) {
3345 list->AppendString(allow_rule);
3346 request_url_allowed_via_whitelist_ = true;
3347 } else {
3348 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3349 // We should ignore all wildcard entries in the whitelist, so even
3350 // though we've added an entry, it should be ignored and our expectation
3351 // is that the request has not been allowed via the whitelist.
3352 request_url_allowed_via_whitelist_ = false;
3354 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3355 POLICY_SCOPE_USER, list, NULL);
3359 void Accept(const content::MediaStreamDevices& devices,
3360 content::MediaStreamRequestResult result,
3361 scoped_ptr<content::MediaStreamUI> ui) {
3362 if (policy_value_ || request_url_allowed_via_whitelist_) {
3363 ASSERT_EQ(1U, devices.size());
3364 ASSERT_EQ("fake_dev", devices[0].id);
3365 } else {
3366 ASSERT_EQ(0U, devices.size());
3370 void FinishAudioTest() {
3371 content::MediaStreamRequest request(0, 0, 0,
3372 request_url_.GetOrigin(), false,
3373 content::MEDIA_DEVICE_ACCESS,
3374 std::string(), std::string(),
3375 content::MEDIA_DEVICE_AUDIO_CAPTURE,
3376 content::MEDIA_NO_SERVICE);
3377 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3378 // and microphone permissions at the same time.
3379 MediaStreamDevicesController controller(
3380 browser()->tab_strip_model()->GetActiveWebContents(), request,
3381 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3382 controller.Accept(false);
3384 base::MessageLoop::current()->QuitWhenIdle();
3387 void FinishVideoTest() {
3388 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3389 // and microphone permissions at the same time.
3390 content::MediaStreamRequest request(0, 0, 0,
3391 request_url_.GetOrigin(), false,
3392 content::MEDIA_DEVICE_ACCESS,
3393 std::string(),
3394 std::string(),
3395 content::MEDIA_NO_SERVICE,
3396 content::MEDIA_DEVICE_VIDEO_CAPTURE);
3397 MediaStreamDevicesController controller(
3398 browser()->tab_strip_model()->GetActiveWebContents(), request,
3399 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3400 controller.Accept(false);
3402 base::MessageLoop::current()->QuitWhenIdle();
3405 bool policy_value_;
3406 bool request_url_allowed_via_whitelist_;
3407 GURL request_url_;
3408 static const char kExampleRequestPattern[];
3411 // static
3412 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3413 "http://[*.]example.com/";
3415 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3416 AudioCaptureAllowed) {
3417 content::MediaStreamDevices audio_devices;
3418 content::MediaStreamDevice fake_audio_device(
3419 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3420 audio_devices.push_back(fake_audio_device);
3422 PolicyMap policies;
3423 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3424 UpdateProviderPolicy(policies);
3426 content::BrowserThread::PostTaskAndReply(
3427 content::BrowserThread::IO, FROM_HERE,
3428 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3429 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3430 audio_devices),
3431 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3432 this));
3434 base::MessageLoop::current()->Run();
3437 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3438 AudioCaptureAllowedUrls) {
3439 content::MediaStreamDevices audio_devices;
3440 content::MediaStreamDevice fake_audio_device(
3441 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3442 audio_devices.push_back(fake_audio_device);
3444 const char* allow_pattern[] = {
3445 kExampleRequestPattern,
3446 // This will set an allow-all policy whitelist. Since we do not allow
3447 // setting an allow-all entry in the whitelist, this entry should be ignored
3448 // and therefore the request should be denied.
3449 NULL,
3452 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3453 PolicyMap policies;
3454 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3455 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3456 UpdateProviderPolicy(policies);
3458 content::BrowserThread::PostTaskAndReply(
3459 content::BrowserThread::IO, FROM_HERE,
3460 base::Bind(
3461 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3462 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3463 audio_devices),
3464 base::Bind(
3465 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3466 this));
3468 base::MessageLoop::current()->Run();
3472 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3473 VideoCaptureAllowed) {
3474 content::MediaStreamDevices video_devices;
3475 content::MediaStreamDevice fake_video_device(
3476 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3477 video_devices.push_back(fake_video_device);
3479 PolicyMap policies;
3480 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3481 UpdateProviderPolicy(policies);
3483 content::BrowserThread::PostTaskAndReply(
3484 content::BrowserThread::IO, FROM_HERE,
3485 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3486 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3487 video_devices),
3488 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3489 this));
3491 base::MessageLoop::current()->Run();
3494 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3495 VideoCaptureAllowedUrls) {
3496 content::MediaStreamDevices video_devices;
3497 content::MediaStreamDevice fake_video_device(
3498 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3499 video_devices.push_back(fake_video_device);
3501 const char* allow_pattern[] = {
3502 kExampleRequestPattern,
3503 // This will set an allow-all policy whitelist. Since we do not allow
3504 // setting an allow-all entry in the whitelist, this entry should be ignored
3505 // and therefore the request should be denied.
3506 NULL,
3509 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3510 PolicyMap policies;
3511 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3512 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3513 UpdateProviderPolicy(policies);
3515 content::BrowserThread::PostTaskAndReply(
3516 content::BrowserThread::IO, FROM_HERE,
3517 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3518 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3519 video_devices),
3520 base::Bind(
3521 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3522 this));
3524 base::MessageLoop::current()->Run();
3528 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3529 MediaStreamDevicesControllerBrowserTest,
3530 testing::Bool());
3532 #if !defined(OS_CHROMEOS)
3533 // Similar to PolicyTest but sets the proper policy before the browser is
3534 // started.
3535 class PolicyVariationsServiceTest : public PolicyTest {
3536 public:
3537 void SetUpInProcessBrowserTestFixture() override {
3538 PolicyTest::SetUpInProcessBrowserTestFixture();
3539 PolicyMap policies;
3540 policies.Set(key::kVariationsRestrictParameter,
3541 POLICY_LEVEL_MANDATORY,
3542 POLICY_SCOPE_USER,
3543 new base::StringValue("restricted"),
3544 NULL);
3545 provider_.UpdateChromePolicy(policies);
3549 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3550 const std::string default_variations_url =
3551 chrome_variations::VariationsService::
3552 GetDefaultVariationsServerURLForTesting();
3554 const GURL url =
3555 chrome_variations::VariationsService::GetVariationsServerURL(
3556 g_browser_process->local_state(), std::string());
3557 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
3558 std::string value;
3559 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3560 EXPECT_EQ("restricted", value);
3563 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3564 base::ListValue blacklist;
3565 blacklist.Append(new base::StringValue("host.name"));
3566 PolicyMap policies;
3567 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3568 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3569 UpdateProviderPolicy(policies);
3571 PrefService* prefs = browser()->profile()->GetPrefs();
3572 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3573 prefs, "host.name"));
3574 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3575 prefs, "other.host.name"));
3578 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3579 base::ListValue blacklist;
3580 blacklist.Append(new base::StringValue("*"));
3581 PolicyMap policies;
3582 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3583 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3584 UpdateProviderPolicy(policies);
3586 PrefService* prefs = browser()->profile()->GetPrefs();
3587 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3588 prefs, "host.name"));
3589 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3590 prefs, "other.host.name"));
3593 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3594 base::ListValue blacklist;
3595 blacklist.Append(new base::StringValue("*"));
3596 base::ListValue whitelist;
3597 whitelist.Append(new base::StringValue("host.name"));
3598 PolicyMap policies;
3599 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3600 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3601 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3602 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3603 UpdateProviderPolicy(policies);
3605 PrefService* prefs = browser()->profile()->GetPrefs();
3606 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3607 prefs, "host.name"));
3608 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3609 prefs, "other.host.name"));
3612 #endif // !defined(CHROME_OS)
3614 } // namespace policy