Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / chrome / browser / policy / policy_browsertest.cc
blob9b2ee7c1456e4b41d383229d687fc0bcf8c81d02
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_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/test/test_file_util.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/time/time.h"
29 #include "base/values.h"
30 #include "chrome/app/chrome_command_ids.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/interstitials/security_interstitial_page.h"
48 #include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
49 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
50 #include "chrome/browser/media/media_stream_devices_controller.h"
51 #include "chrome/browser/metrics/variations/variations_service.h"
52 #include "chrome/browser/net/prediction_options.h"
53 #include "chrome/browser/net/url_request_mock_util.h"
54 #include "chrome/browser/plugins/plugin_prefs.h"
55 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
56 #include "chrome/browser/policy/profile_policy_connector.h"
57 #include "chrome/browser/policy/profile_policy_connector_factory.h"
58 #include "chrome/browser/prefs/session_startup_pref.h"
59 #include "chrome/browser/profiles/profile.h"
60 #include "chrome/browser/search/instant_service.h"
61 #include "chrome/browser/search/instant_service_factory.h"
62 #include "chrome/browser/search/search.h"
63 #include "chrome/browser/search_engines/template_url_service_factory.h"
64 #include "chrome/browser/ssl/ssl_blocking_page.h"
65 #include "chrome/browser/translate/chrome_translate_client.h"
66 #include "chrome/browser/translate/cld_data_harness.h"
67 #include "chrome/browser/translate/cld_data_harness_factory.h"
68 #include "chrome/browser/translate/translate_service.h"
69 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
70 #include "chrome/browser/ui/browser.h"
71 #include "chrome/browser/ui/browser_commands.h"
72 #include "chrome/browser/ui/browser_list.h"
73 #include "chrome/browser/ui/browser_tabstrip.h"
74 #include "chrome/browser/ui/browser_window.h"
75 #include "chrome/browser/ui/host_desktop.h"
76 #include "chrome/browser/ui/location_bar/location_bar.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/omnibox/browser/autocomplete_controller.h"
92 #include "components/omnibox/browser/omnibox_edit_model.h"
93 #include "components/omnibox/browser/omnibox_view.h"
94 #include "components/policy/core/browser/browser_policy_connector.h"
95 #include "components/policy/core/common/external_data_fetcher.h"
96 #include "components/policy/core/common/mock_configuration_policy_provider.h"
97 #include "components/policy/core/common/policy_map.h"
98 #include "components/policy/core/common/policy_pref_names.h"
99 #include "components/policy/core/common/policy_service.h"
100 #include "components/policy/core/common/policy_service_impl.h"
101 #include "components/search/search.h"
102 #include "components/search_engines/template_url.h"
103 #include "components/search_engines/template_url_service.h"
104 #include "components/translate/core/browser/language_state.h"
105 #include "components/translate/core/browser/translate_infobar_delegate.h"
106 #include "components/version_info/version_info.h"
107 #include "content/public/browser/browser_child_process_host_iterator.h"
108 #include "content/public/browser/browser_context.h"
109 #include "content/public/browser/browser_thread.h"
110 #include "content/public/browser/child_process_data.h"
111 #include "content/public/browser/download_item.h"
112 #include "content/public/browser/download_manager.h"
113 #include "content/public/browser/gpu_data_manager.h"
114 #include "content/public/browser/interstitial_page.h"
115 #include "content/public/browser/notification_details.h"
116 #include "content/public/browser/notification_observer.h"
117 #include "content/public/browser/notification_registrar.h"
118 #include "content/public/browser/notification_service.h"
119 #include "content/public/browser/notification_source.h"
120 #include "content/public/browser/notification_types.h"
121 #include "content/public/browser/plugin_service.h"
122 #include "content/public/browser/render_frame_host.h"
123 #include "content/public/browser/render_process_host.h"
124 #include "content/public/browser/render_view_host.h"
125 #include "content/public/browser/web_contents.h"
126 #include "content/public/common/content_constants.h"
127 #include "content/public/common/content_paths.h"
128 #include "content/public/common/process_type.h"
129 #include "content/public/common/result_codes.h"
130 #include "content/public/common/url_constants.h"
131 #include "content/public/common/webplugininfo.h"
132 #include "content/public/test/browser_test_utils.h"
133 #include "content/public/test/download_test_observer.h"
134 #include "content/public/test/mock_notification_observer.h"
135 #include "content/public/test/test_navigation_observer.h"
136 #include "content/public/test/test_utils.h"
137 #include "extensions/browser/extension_dialog_auto_confirm.h"
138 #include "extensions/browser/extension_host.h"
139 #include "extensions/browser/extension_prefs.h"
140 #include "extensions/browser/extension_registry.h"
141 #include "extensions/browser/extension_system.h"
142 #include "extensions/browser/process_manager.h"
143 #include "extensions/browser/test_extension_registry_observer.h"
144 #include "extensions/browser/uninstall_reason.h"
145 #include "extensions/common/constants.h"
146 #include "extensions/common/extension.h"
147 #include "extensions/common/extension_set.h"
148 #include "extensions/common/manifest_handlers/shared_module_info.h"
149 #include "net/base/net_errors.h"
150 #include "net/base/net_util.h"
151 #include "net/base/url_util.h"
152 #include "net/http/http_stream_factory.h"
153 #include "net/ssl/ssl_config.h"
154 #include "net/ssl/ssl_config_service.h"
155 #include "net/test/spawned_test_server/spawned_test_server.h"
156 #include "net/test/url_request/url_request_failed_job.h"
157 #include "net/test/url_request/url_request_mock_http_job.h"
158 #include "net/url_request/url_request.h"
159 #include "net/url_request/url_request_filter.h"
160 #include "net/url_request/url_request_interceptor.h"
161 #include "policy/policy_constants.h"
162 #include "testing/gmock/include/gmock/gmock.h"
163 #include "testing/gtest/include/gtest/gtest.h"
164 #include "third_party/WebKit/public/web/WebInputEvent.h"
165 #include "ui/base/l10n/l10n_util.h"
166 #include "ui/base/page_transition_types.h"
167 #include "ui/base/resource/resource_bundle.h"
168 #include "url/gurl.h"
170 #if defined(OS_CHROMEOS)
171 #include "ash/accelerators/accelerator_controller.h"
172 #include "ash/accelerators/accelerator_table.h"
173 #include "ash/shell.h"
174 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
175 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
176 #include "chrome/browser/profiles/profile_manager.h"
177 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
178 #include "chromeos/audio/cras_audio_handler.h"
179 #include "ui/chromeos/accessibility_types.h"
180 #include "ui/keyboard/keyboard_util.h"
181 #include "ui/snapshot/screenshot_grabber.h"
182 #endif
184 #if !defined(OS_MACOSX)
185 #include "base/basictypes.h"
186 #include "base/compiler_specific.h"
187 #include "chrome/browser/ui/extensions/app_launch_params.h"
188 #include "chrome/browser/ui/extensions/application_launch.h"
189 #include "extensions/browser/app_window/app_window.h"
190 #include "extensions/browser/app_window/app_window_registry.h"
191 #include "extensions/browser/app_window/native_app_window.h"
192 #include "ui/base/window_open_disposition.h"
193 #endif
195 using content::BrowserThread;
196 using net::URLRequestMockHTTPJob;
197 using testing::Mock;
198 using testing::Return;
199 using testing::_;
201 namespace policy {
203 namespace {
205 #if defined(OS_CHROMEOS)
206 const int kOneHourInMs = 60 * 60 * 1000;
207 const int kThreeHoursInMs = 180 * 60 * 1000;
208 #endif
210 const char kURL[] = "http://example.com";
211 const char kCookieValue[] = "converted=true";
212 // Assigned to Philip J. Fry to fix eventually.
213 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
215 const base::FilePath::CharType kTestExtensionsDir[] =
216 FILE_PATH_LITERAL("extensions");
217 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
218 const base::FilePath::CharType kAdBlockCrxName[] =
219 FILE_PATH_LITERAL("adblock.crx");
220 const base::FilePath::CharType kHostedAppCrxName[] =
221 FILE_PATH_LITERAL("hosted_app.crx");
223 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
224 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
225 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
227 const base::FilePath::CharType kGood2CrxManifestName[] =
228 FILE_PATH_LITERAL("good2_update_manifest.xml");
229 const base::FilePath::CharType kGoodV1CrxManifestName[] =
230 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
231 const base::FilePath::CharType kGoodV1CrxName[] =
232 FILE_PATH_LITERAL("good_v1.crx");
233 const base::FilePath::CharType kGoodUnpackedExt[] =
234 FILE_PATH_LITERAL("good_unpacked");
235 const base::FilePath::CharType kAppUnpackedExt[] =
236 FILE_PATH_LITERAL("app");
238 #if !defined(OS_MACOSX)
239 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
240 FILE_PATH_LITERAL("fullscreen_app");
241 #endif // !defined(OS_MACOSX)
243 // Filters requests to the hosts in |urls| and redirects them to the test data
244 // dir through URLRequestMockHTTPJobs.
245 void RedirectHostsToTestData(const char* const urls[], size_t size) {
246 // Map the given hosts to the test data dir.
247 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
248 base::FilePath base_path;
249 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
250 for (size_t i = 0; i < size; ++i) {
251 const GURL url(urls[i]);
252 EXPECT_TRUE(url.is_valid());
253 filter->AddUrlInterceptor(url,
254 URLRequestMockHTTPJob::CreateInterceptor(
255 base_path, BrowserThread::GetBlockingPool()));
259 // Remove filters for requests to the hosts in |urls|.
260 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
261 // Map the given hosts to the test data dir.
262 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
263 for (size_t i = 0; i < size; ++i) {
264 const GURL url(urls[i]);
265 EXPECT_TRUE(url.is_valid());
266 filter->RemoveUrlHandler(url);
270 // Fails requests using ERR_CONNECTION_RESET.
271 class FailedJobInterceptor : public net::URLRequestInterceptor {
272 public:
273 FailedJobInterceptor() {}
274 ~FailedJobInterceptor() override {}
276 // URLRequestInterceptor implementation:
277 net::URLRequestJob* MaybeInterceptRequest(
278 net::URLRequest* request,
279 net::NetworkDelegate* network_delegate) const override {
280 return new net::URLRequestFailedJob(request, network_delegate,
281 net::ERR_CONNECTION_RESET);
284 private:
285 DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor);
288 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
289 class MakeRequestFail {
290 public:
291 // Sets up the filter on IO thread such that requests to |host| fail.
292 explicit MakeRequestFail(const std::string& host) : host_(host) {
293 BrowserThread::PostTaskAndReply(
294 BrowserThread::IO, FROM_HERE,
295 base::Bind(MakeRequestFailOnIO, host_),
296 base::MessageLoop::QuitClosure());
297 content::RunMessageLoop();
299 ~MakeRequestFail() {
300 BrowserThread::PostTaskAndReply(
301 BrowserThread::IO, FROM_HERE,
302 base::Bind(UndoMakeRequestFailOnIO, host_),
303 base::MessageLoop::QuitClosure());
304 content::RunMessageLoop();
307 private:
308 // Filters requests to the |host| such that they fail. Run on IO thread.
309 static void MakeRequestFailOnIO(const std::string& host) {
310 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
311 filter->AddHostnameInterceptor(
312 "http", host,
313 scoped_ptr<net::URLRequestInterceptor>(new FailedJobInterceptor()));
314 filter->AddHostnameInterceptor(
315 "https", host,
316 scoped_ptr<net::URLRequestInterceptor>(new FailedJobInterceptor()));
319 // Remove filters for requests to the |host|. Run on IO thread.
320 static void UndoMakeRequestFailOnIO(const std::string& host) {
321 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
322 filter->RemoveHostnameHandler("http", host);
323 filter->RemoveHostnameHandler("https", host);
326 const std::string host_;
329 // Verifies that the given url |spec| can be opened. This assumes that |spec|
330 // points at empty.html in the test data dir.
331 void CheckCanOpenURL(Browser* browser, const char* spec) {
332 GURL url(spec);
333 ui_test_utils::NavigateToURL(browser, url);
334 content::WebContents* contents =
335 browser->tab_strip_model()->GetActiveWebContents();
336 EXPECT_EQ(url, contents->GetURL());
337 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
338 base::string16 title =
339 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
340 EXPECT_NE(title, contents->GetTitle());
343 // Verifies that access to the given url |spec| is blocked.
344 void CheckURLIsBlocked(Browser* browser, const char* spec) {
345 GURL url(spec);
346 ui_test_utils::NavigateToURL(browser, url);
347 content::WebContents* contents =
348 browser->tab_strip_model()->GetActiveWebContents();
349 EXPECT_EQ(url, contents->GetURL());
350 base::string16 spec16 = base::UTF8ToUTF16(url.spec());
351 base::string16 title =
352 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED, spec16);
353 EXPECT_EQ(title, contents->GetTitle());
355 // Verify that the expected error page is being displayed.
356 bool result = false;
357 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
358 contents,
359 "var textContent = document.body.textContent;"
360 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
361 "domAutomationController.send(hasError);",
362 &result));
363 EXPECT_TRUE(result);
366 // Downloads a file named |file| and expects it to be saved to |dir|, which
367 // must be empty.
368 void DownloadAndVerifyFile(
369 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
370 content::DownloadManager* download_manager =
371 content::BrowserContext::GetDownloadManager(browser->profile());
372 content::DownloadTestObserverTerminal observer(
373 download_manager, 1,
374 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
375 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
376 base::FilePath downloaded = dir.Append(file);
377 EXPECT_FALSE(base::PathExists(downloaded));
378 ui_test_utils::NavigateToURL(browser, url);
379 observer.WaitForFinished();
380 EXPECT_EQ(
381 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
382 EXPECT_TRUE(base::PathExists(downloaded));
383 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
384 EXPECT_EQ(file, enumerator.Next().BaseName());
385 EXPECT_EQ(base::FilePath(), enumerator.Next());
388 #if defined(OS_CHROMEOS)
389 int CountScreenshots() {
390 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
391 ProfileManager::GetActiveUserProfile());
392 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
393 false, base::FileEnumerator::FILES,
394 "Screenshot*");
395 int count = 0;
396 while (!enumerator.Next().empty())
397 count++;
398 return count;
400 #endif
402 // Checks if WebGL is enabled in the given WebContents.
403 bool IsWebGLEnabled(content::WebContents* contents) {
404 bool result = false;
405 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
406 contents,
407 "var canvas = document.createElement('canvas');"
408 "var context = canvas.getContext('webgl');"
409 "domAutomationController.send(context != null);",
410 &result));
411 return result;
414 bool IsJavascriptEnabled(content::WebContents* contents) {
415 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
416 contents->GetMainFrame(), "123");
417 int result = 0;
418 if (!value->GetAsInteger(&result))
419 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
420 return result == 123;
423 bool IsNetworkPredictionEnabled(PrefService* prefs) {
424 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs);
427 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
428 const std::vector<content::WebPluginInfo>& in) {
429 *out = in;
430 base::MessageLoop::current()->QuitWhenIdle();
433 template<typename T>
434 void CopyValueAndQuit(T* out, T in) {
435 *out = in;
436 base::MessageLoop::current()->QuitWhenIdle();
439 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
440 content::PluginService* service = content::PluginService::GetInstance();
441 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
442 content::RunMessageLoop();
445 const content::WebPluginInfo* GetFlashPlugin(
446 const std::vector<content::WebPluginInfo>& plugins) {
447 const content::WebPluginInfo* flash = NULL;
448 for (size_t i = 0; i < plugins.size(); ++i) {
449 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
450 flash = &plugins[i];
451 break;
454 #if defined(OFFICIAL_BUILD)
455 // Official builds bundle Flash.
456 EXPECT_TRUE(flash);
457 #else
458 if (!flash)
459 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
460 #endif
461 return flash;
464 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
465 const content::WebPluginInfo* plugin,
466 bool enabled) {
467 bool ok = false;
468 plugin_prefs->EnablePlugin(enabled, plugin->path,
469 base::Bind(CopyValueAndQuit<bool>, &ok));
470 content::RunMessageLoop();
471 return ok;
474 int CountPluginsOnIOThread() {
475 int count = 0;
476 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
477 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
478 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
479 count++;
482 return count;
485 int CountPlugins() {
486 int count = -1;
487 BrowserThread::PostTaskAndReplyWithResult(
488 BrowserThread::IO, FROM_HERE,
489 base::Bind(CountPluginsOnIOThread),
490 base::Bind(CopyValueAndQuit<int>, &count));
491 content::RunMessageLoop();
492 EXPECT_GE(count, 0);
493 return count;
496 void FlushBlacklistPolicy() {
497 // Updates of the URLBlacklist are done on IO, after building the blacklist
498 // on the blocking pool, which is initiated from IO.
499 content::RunAllPendingInMessageLoop(BrowserThread::IO);
500 BrowserThread::GetBlockingPool()->FlushForTesting();
501 content::RunAllPendingInMessageLoop(BrowserThread::IO);
504 bool ContainsVisibleElement(content::WebContents* contents,
505 const std::string& id) {
506 bool result;
507 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
508 contents,
509 "var elem = document.getElementById('" + id + "');"
510 "domAutomationController.send(!!elem && !elem.hidden);",
511 &result));
512 return result;
515 #if defined(OS_CHROMEOS)
516 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
517 public:
518 TestAudioObserver() : output_mute_changed_count_(0) {
521 int output_mute_changed_count() const {
522 return output_mute_changed_count_;
525 ~TestAudioObserver() override {}
527 protected:
528 // chromeos::CrasAudioHandler::AudioObserver overrides.
529 void OnOutputMuteChanged(bool /* mute_on */,
530 bool /* system_adjust */) override {
531 ++output_mute_changed_count_;
534 private:
535 int output_mute_changed_count_;
537 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
539 #endif
541 // This class waits until either a load stops or the WebContents is destroyed.
542 class WebContentsLoadedOrDestroyedWatcher
543 : public content::WebContentsObserver {
544 public:
545 explicit WebContentsLoadedOrDestroyedWatcher(
546 content::WebContents* web_contents);
547 ~WebContentsLoadedOrDestroyedWatcher() override;
549 // Waits until the WebContents's load is done or until it is destroyed.
550 void Wait();
552 // Overridden WebContentsObserver methods.
553 void WebContentsDestroyed() override;
554 void DidStopLoading() override;
556 private:
557 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
559 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
562 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
563 content::WebContents* web_contents)
564 : content::WebContentsObserver(web_contents),
565 message_loop_runner_(new content::MessageLoopRunner) {
568 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
570 void WebContentsLoadedOrDestroyedWatcher::Wait() {
571 message_loop_runner_->Run();
574 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
575 message_loop_runner_->Quit();
578 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
579 message_loop_runner_->Quit();
582 #if !defined(OS_MACOSX)
584 // Observer used to wait for the creation of a new app window.
585 class TestAddAppWindowObserver
586 : public extensions::AppWindowRegistry::Observer {
587 public:
588 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry* registry);
589 ~TestAddAppWindowObserver() override;
591 // extensions::AppWindowRegistry::Observer:
592 void OnAppWindowAdded(extensions::AppWindow* app_window) override;
594 extensions::AppWindow* WaitForAppWindow();
596 private:
597 extensions::AppWindowRegistry* registry_; // Not owned.
598 extensions::AppWindow* window_; // Not owned.
599 base::RunLoop run_loop_;
601 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
604 TestAddAppWindowObserver::TestAddAppWindowObserver(
605 extensions::AppWindowRegistry* registry)
606 : registry_(registry), window_(NULL) {
607 registry_->AddObserver(this);
610 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
611 registry_->RemoveObserver(this);
614 void TestAddAppWindowObserver::OnAppWindowAdded(
615 extensions::AppWindow* app_window) {
616 window_ = app_window;
617 run_loop_.Quit();
620 extensions::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
621 run_loop_.Run();
622 return window_;
625 #endif
627 } // namespace
629 class PolicyTest : public InProcessBrowserTest {
630 protected:
631 PolicyTest() {}
632 ~PolicyTest() override {}
634 void SetUp() override {
635 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
636 InProcessBrowserTest::SetUp();
639 void SetUpInProcessBrowserTestFixture() override {
640 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
641 EXPECT_CALL(provider_, IsInitializationComplete(_))
642 .WillRepeatedly(Return(true));
643 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
646 void SetUpOnMainThread() override {
647 BrowserThread::PostTask(
648 BrowserThread::IO, FROM_HERE,
649 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
650 if (extension_service()->updater()) {
651 extension_service()->updater()->SetExtensionCacheForTesting(
652 test_extension_cache_.get());
656 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
657 // instead of chrome::DIR_TEST_DATA.
658 void ServeContentTestData() {
659 base::FilePath root_http;
660 PathService::Get(content::DIR_TEST_DATA, &root_http);
661 BrowserThread::PostTaskAndReply(
662 BrowserThread::IO, FROM_HERE,
663 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers, root_http,
664 make_scoped_refptr(BrowserThread::GetBlockingPool())),
665 base::MessageLoop::current()->QuitWhenIdleClosure());
666 content::RunMessageLoop();
669 void SetScreenshotPolicy(bool enabled) {
670 PolicyMap policies;
671 policies.Set(key::kDisableScreenshots,
672 POLICY_LEVEL_MANDATORY,
673 POLICY_SCOPE_USER,
674 new base::FundamentalValue(!enabled),
675 NULL);
676 UpdateProviderPolicy(policies);
679 #if defined(OS_CHROMEOS)
680 class QuitMessageLoopAfterScreenshot : public ui::ScreenshotGrabberObserver {
681 public:
682 void OnScreenshotCompleted(
683 ScreenshotGrabberObserver::Result screenshot_result,
684 const base::FilePath& screenshot_path) override {
685 BrowserThread::PostTaskAndReply(BrowserThread::IO,
686 FROM_HERE,
687 base::Bind(base::DoNothing),
688 base::MessageLoop::QuitClosure());
691 ~QuitMessageLoopAfterScreenshot() override {}
694 void TestScreenshotFile(bool enabled) {
695 // AddObserver is an ash-specific method, so just replace the screenshot
696 // grabber with one we've created here.
697 scoped_ptr<ChromeScreenshotGrabber> chrome_screenshot_grabber(
698 new ChromeScreenshotGrabber);
699 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
700 // is tied to the test instead.
701 chrome_screenshot_grabber->screenshot_grabber()->AddObserver(&observer_);
702 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
703 chrome_screenshot_grabber.Pass());
705 SetScreenshotPolicy(enabled);
706 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
707 ash::TAKE_SCREENSHOT);
709 content::RunMessageLoop();
710 static_cast<ChromeScreenshotGrabber*>(ash::Shell::GetInstance()
711 ->accelerator_controller()
712 ->screenshot_delegate())
713 ->screenshot_grabber()
714 ->RemoveObserver(&observer_);
716 #endif
718 ExtensionService* extension_service() {
719 extensions::ExtensionSystem* system =
720 extensions::ExtensionSystem::Get(browser()->profile());
721 return system->extension_service();
724 const extensions::Extension* InstallExtension(
725 const base::FilePath::StringType& name) {
726 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
727 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
728 scoped_refptr<extensions::CrxInstaller> installer =
729 extensions::CrxInstaller::CreateSilent(extension_service());
730 installer->set_allow_silent_install(true);
731 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
732 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
734 content::WindowedNotificationObserver observer(
735 extensions::NOTIFICATION_CRX_INSTALLER_DONE,
736 content::NotificationService::AllSources());
737 installer->InstallCrx(extension_path);
738 observer.Wait();
739 content::Details<const extensions::Extension> details = observer.details();
740 return details.ptr();
743 const extensions::Extension* LoadUnpackedExtension(
744 const base::FilePath::StringType& name, bool expect_success) {
745 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
746 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
747 scoped_refptr<extensions::UnpackedInstaller> installer =
748 extensions::UnpackedInstaller::Create(extension_service());
749 content::WindowedNotificationObserver observer(
750 expect_success ? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
751 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR,
752 content::NotificationService::AllSources());
753 installer->Load(extension_path);
754 observer.Wait();
756 extensions::ExtensionRegistry* registry =
757 extensions::ExtensionRegistry::Get(browser()->profile());
758 for (const scoped_refptr<const extensions::Extension>& extension :
759 registry->enabled_extensions()) {
760 if (extension->path() == extension_path)
761 return extension.get();
763 return NULL;
766 void UninstallExtension(const std::string& id, bool expect_success) {
767 if (expect_success) {
768 extensions::TestExtensionRegistryObserver observer(
769 extensions::ExtensionRegistry::Get(browser()->profile()));
770 extension_service()->UninstallExtension(
771 id, extensions::UNINSTALL_REASON_FOR_TESTING,
772 base::Bind(&base::DoNothing), NULL);
773 observer.WaitForExtensionUninstalled();
774 } else {
775 content::WindowedNotificationObserver observer(
776 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
777 content::NotificationService::AllSources());
778 extension_service()->UninstallExtension(
780 extensions::UNINSTALL_REASON_FOR_TESTING,
781 base::Bind(&base::DoNothing),
782 NULL);
783 observer.Wait();
787 void DisableExtension(const std::string& id) {
788 extensions::TestExtensionRegistryObserver observer(
789 extensions::ExtensionRegistry::Get(browser()->profile()));
790 extension_service()->DisableExtension(id,
791 extensions::Extension::DISABLE_NONE);
792 observer.WaitForExtensionUnloaded();
795 void UpdateProviderPolicy(const PolicyMap& policy) {
796 provider_.UpdateChromePolicy(policy);
797 DCHECK(base::MessageLoop::current());
798 base::RunLoop loop;
799 loop.RunUntilIdle();
802 // Sends a mouse click at the given coordinates to the current renderer.
803 void PerformClick(int x, int y) {
804 content::WebContents* contents =
805 browser()->tab_strip_model()->GetActiveWebContents();
806 blink::WebMouseEvent click_event;
807 click_event.type = blink::WebInputEvent::MouseDown;
808 click_event.button = blink::WebMouseEvent::ButtonLeft;
809 click_event.clickCount = 1;
810 click_event.x = x;
811 click_event.y = y;
812 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
813 click_event.type = blink::WebInputEvent::MouseUp;
814 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
817 void SetPolicy(PolicyMap* policies, const char* key, base::Value* value) {
818 if (value) {
819 policies->Set(key,
820 POLICY_LEVEL_MANDATORY,
821 POLICY_SCOPE_USER,
822 value,
823 nullptr);
824 } else {
825 policies->Erase(key);
829 void ApplySafeSearchPolicy(base::FundamentalValue* legacy_safe_search,
830 base::FundamentalValue* google_safe_search,
831 base::FundamentalValue* youtube_safety_mode) {
832 PolicyMap policies;
833 SetPolicy(&policies, key::kForceSafeSearch, legacy_safe_search);
834 SetPolicy(&policies, key::kForceGoogleSafeSearch, google_safe_search);
835 SetPolicy(&policies, key::kForceYouTubeSafetyMode, youtube_safety_mode);
836 UpdateProviderPolicy(policies);
839 void CheckSafeSearch(bool expect_safe_search) {
840 content::WebContents* web_contents =
841 browser()->tab_strip_model()->GetActiveWebContents();
842 content::TestNavigationObserver observer(web_contents);
843 chrome::FocusLocationBar(browser());
844 LocationBar* location_bar = browser()->window()->GetLocationBar();
845 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
846 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
847 observer.Wait();
848 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
850 std::string expected_url("http://google.com/");
851 if (expect_safe_search) {
852 expected_url += "?" + std::string(chrome::kSafeSearchSafeParameter) +
853 "&" + chrome::kSafeSearchSsuiParameter;
855 EXPECT_EQ(GURL(expected_url), web_contents->GetURL());
858 MockConfigurationPolicyProvider provider_;
859 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
860 #if defined(OS_CHROMEOS)
861 QuitMessageLoopAfterScreenshot observer_;
862 #endif
865 #if defined(OS_WIN)
866 // This policy only exists on Windows.
868 // Sets the locale policy before the browser is started.
869 class LocalePolicyTest : public PolicyTest {
870 public:
871 LocalePolicyTest() {}
872 ~LocalePolicyTest() override {}
874 void SetUpInProcessBrowserTestFixture() override {
875 PolicyTest::SetUpInProcessBrowserTestFixture();
876 PolicyMap policies;
877 policies.Set(key::kApplicationLocaleValue,
878 POLICY_LEVEL_MANDATORY,
879 POLICY_SCOPE_USER,
880 new base::StringValue("fr"),
881 NULL);
882 provider_.UpdateChromePolicy(policies);
883 // The "en-US" ResourceBundle is always loaded before this step for tests,
884 // but in this test we want the browser to load the bundle as it
885 // normally would.
886 ResourceBundle::CleanupSharedInstance();
890 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
891 // Verifies that the default locale can be overridden with policy.
892 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
893 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
894 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
895 base::string16 title;
896 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
897 EXPECT_EQ(french_title, title);
899 // Make sure this is really French and differs from the English title.
900 std::string loaded =
901 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
902 EXPECT_EQ("en-US", loaded);
903 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
904 EXPECT_NE(french_title, english_title);
906 #endif
908 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
909 #if defined(OS_WIN) && defined(USE_ASH)
910 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
911 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
912 switches::kAshBrowserTests))
913 return;
914 #endif
916 // Verifies that the bookmarks bar can be forced to always or never show up.
918 // Test starts in about:blank.
919 PrefService* prefs = browser()->profile()->GetPrefs();
920 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
921 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
922 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
924 PolicyMap policies;
925 policies.Set(key::kBookmarkBarEnabled,
926 POLICY_LEVEL_MANDATORY,
927 POLICY_SCOPE_USER,
928 new base::FundamentalValue(true),
929 NULL);
930 UpdateProviderPolicy(policies);
931 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
932 EXPECT_TRUE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
933 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
935 // The NTP has special handling of the bookmark bar.
936 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
937 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
939 policies.Set(key::kBookmarkBarEnabled,
940 POLICY_LEVEL_MANDATORY,
941 POLICY_SCOPE_USER,
942 new base::FundamentalValue(false),
943 NULL);
944 UpdateProviderPolicy(policies);
945 EXPECT_TRUE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
946 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
947 // The bookmark bar is hidden in the NTP when disabled by policy.
948 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
950 policies.Clear();
951 UpdateProviderPolicy(policies);
952 EXPECT_FALSE(prefs->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar));
953 EXPECT_FALSE(prefs->GetBoolean(bookmarks::prefs::kShowBookmarkBar));
954 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
955 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
958 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
959 // Verifies that cookies are deleted on shutdown. This test is split in 3
960 // parts because it spans 2 browser restarts.
962 Profile* profile = browser()->profile();
963 GURL url(kURL);
964 // No cookies at startup.
965 EXPECT_TRUE(content::GetCookies(profile, url).empty());
966 // Set a cookie now.
967 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
968 EXPECT_TRUE(content::SetCookie(profile, url, value));
969 // Verify it was set.
970 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
973 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
974 // Verify that the cookie persists across restarts.
975 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
976 // Now set the policy and the cookie should be gone after another restart.
977 PolicyMap policies;
978 policies.Set(key::kDefaultCookiesSetting,
979 POLICY_LEVEL_MANDATORY,
980 POLICY_SCOPE_USER,
981 new base::FundamentalValue(4),
982 NULL);
983 UpdateProviderPolicy(policies);
986 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
987 // Verify that the cookie is gone.
988 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
991 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
992 MakeRequestFail make_request_fail("search.example");
994 // Verifies that a default search is made using the provider configured via
995 // policy. Also checks that default search can be completely disabled.
996 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
997 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
998 const std::string kAlternateURL0(
999 "http://search.example/search#q={searchTerms}");
1000 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
1001 const std::string kSearchTermsReplacementKey("zekey");
1002 const std::string kImageURL("http://test.com/searchbyimage/upload");
1003 const std::string kImageURLPostParams(
1004 "image_content=content,image_url=http://test.com/test.png");
1005 const std::string kNewTabURL("http://search.example/newtab");
1007 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1008 browser()->profile());
1009 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1010 TemplateURL* default_search = service->GetDefaultSearchProvider();
1011 ASSERT_TRUE(default_search);
1012 EXPECT_NE(kKeyword, default_search->keyword());
1013 EXPECT_NE(kSearchURL, default_search->url());
1014 EXPECT_FALSE(
1015 default_search->alternate_urls().size() == 2 &&
1016 default_search->alternate_urls()[0] == kAlternateURL0 &&
1017 default_search->alternate_urls()[1] == kAlternateURL1 &&
1018 default_search->search_terms_replacement_key() ==
1019 kSearchTermsReplacementKey &&
1020 default_search->image_url() == kImageURL &&
1021 default_search->image_url_post_params() == kImageURLPostParams &&
1022 default_search->new_tab_url() == kNewTabURL);
1024 // Override the default search provider using policies.
1025 PolicyMap policies;
1026 policies.Set(key::kDefaultSearchProviderEnabled,
1027 POLICY_LEVEL_MANDATORY,
1028 POLICY_SCOPE_USER,
1029 new base::FundamentalValue(true),
1030 NULL);
1031 policies.Set(key::kDefaultSearchProviderKeyword,
1032 POLICY_LEVEL_MANDATORY,
1033 POLICY_SCOPE_USER,
1034 new base::StringValue(kKeyword),
1035 NULL);
1036 policies.Set(key::kDefaultSearchProviderSearchURL,
1037 POLICY_LEVEL_MANDATORY,
1038 POLICY_SCOPE_USER,
1039 new base::StringValue(kSearchURL),
1040 NULL);
1041 base::ListValue* alternate_urls = new base::ListValue();
1042 alternate_urls->AppendString(kAlternateURL0);
1043 alternate_urls->AppendString(kAlternateURL1);
1044 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1045 POLICY_SCOPE_USER, alternate_urls, NULL);
1046 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1047 POLICY_LEVEL_MANDATORY,
1048 POLICY_SCOPE_USER,
1049 new base::StringValue(kSearchTermsReplacementKey),
1050 NULL);
1051 policies.Set(key::kDefaultSearchProviderImageURL,
1052 POLICY_LEVEL_MANDATORY,
1053 POLICY_SCOPE_USER,
1054 new base::StringValue(kImageURL),
1055 NULL);
1056 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
1057 POLICY_LEVEL_MANDATORY,
1058 POLICY_SCOPE_USER,
1059 new base::StringValue(kImageURLPostParams),
1060 NULL);
1061 policies.Set(key::kDefaultSearchProviderNewTabURL,
1062 POLICY_LEVEL_MANDATORY,
1063 POLICY_SCOPE_USER,
1064 new base::StringValue(kNewTabURL),
1065 NULL);
1066 UpdateProviderPolicy(policies);
1067 default_search = service->GetDefaultSearchProvider();
1068 ASSERT_TRUE(default_search);
1069 EXPECT_EQ(kKeyword, default_search->keyword());
1070 EXPECT_EQ(kSearchURL, default_search->url());
1071 EXPECT_EQ(2U, default_search->alternate_urls().size());
1072 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1073 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1074 EXPECT_EQ(kSearchTermsReplacementKey,
1075 default_search->search_terms_replacement_key());
1076 EXPECT_EQ(kImageURL, default_search->image_url());
1077 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
1078 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
1080 // Verify that searching from the omnibox uses kSearchURL.
1081 chrome::FocusLocationBar(browser());
1082 LocationBar* location_bar = browser()->window()->GetLocationBar();
1083 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
1084 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1085 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1086 content::WebContents* web_contents =
1087 browser()->tab_strip_model()->GetActiveWebContents();
1088 GURL expected("http://search.example/search?q=stuff+to+search+for");
1089 EXPECT_EQ(expected, web_contents->GetURL());
1091 // Verify that searching from the omnibox can be disabled.
1092 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1093 policies.Set(key::kDefaultSearchProviderEnabled,
1094 POLICY_LEVEL_MANDATORY,
1095 POLICY_SCOPE_USER,
1096 new base::FundamentalValue(false),
1097 NULL);
1098 EXPECT_TRUE(service->GetDefaultSearchProvider());
1099 UpdateProviderPolicy(policies);
1100 EXPECT_FALSE(service->GetDefaultSearchProvider());
1101 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
1102 // This means that submitting won't trigger any action.
1103 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
1104 EXPECT_EQ(GURL(url::kAboutBlankURL), web_contents->GetURL());
1107 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
1108 // Add an individual proxy policy value.
1109 PolicyMap policies;
1110 policies.Set(key::kProxyServerMode,
1111 POLICY_LEVEL_MANDATORY,
1112 POLICY_SCOPE_USER,
1113 new base::FundamentalValue(3),
1114 NULL);
1115 UpdateProviderPolicy(policies);
1117 // It should be removed and replaced with a dictionary.
1118 PolicyMap expected;
1119 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
1120 expected_value->SetInteger(key::kProxyServerMode, 3);
1121 expected.Set(key::kProxySettings,
1122 POLICY_LEVEL_MANDATORY,
1123 POLICY_SCOPE_USER,
1124 expected_value.release(),
1125 NULL);
1127 // Check both the browser and the profile.
1128 const PolicyMap& actual_from_browser =
1129 g_browser_process->browser_policy_connector()
1130 ->GetPolicyService()
1131 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1132 EXPECT_TRUE(expected.Equals(actual_from_browser));
1133 const PolicyMap& actual_from_profile =
1134 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1135 ->policy_service()
1136 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
1137 EXPECT_TRUE(expected.Equals(actual_from_profile));
1140 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
1141 // Makes the requests fail since all we want to check is that the redirection
1142 // is done properly.
1143 MakeRequestFail make_request_fail("google.com");
1145 // Verifies that requests to Google Search engine with the SafeSearch
1146 // enabled set the safe=active&ssui=on parameters at the end of the query.
1147 // First check that nothing happens.
1148 CheckSafeSearch(false);
1150 // Go over all combinations of (undefined,true,false) for the three policies.
1151 for (int i = 0; i < 3 * 3 * 3; i++) {
1152 int legacy = i % 3;
1153 int google = (i / 3) % 3;
1154 int youtube = i / (3 * 3);
1156 // Override the default SafeSearch setting using policies.
1157 ApplySafeSearchPolicy(
1158 legacy == 0 ? nullptr : new base::FundamentalValue(legacy == 1),
1159 google == 0 ? nullptr : new base::FundamentalValue(google == 1),
1160 youtube == 0 ? nullptr : new base::FundamentalValue(youtube == 1));
1162 // The legacy policy should only have an effect if both google and youtube
1163 // are undefined.
1164 bool legacy_in_effect = (google == 0 && youtube == 0 && legacy != 0);
1165 bool legacy_enabled = legacy_in_effect && legacy == 1;
1167 PrefService* prefs = browser()->profile()->GetPrefs();
1168 EXPECT_EQ(google != 0 || legacy_in_effect,
1169 prefs->IsManagedPreference(prefs::kForceGoogleSafeSearch));
1170 EXPECT_EQ(google == 1 || legacy_enabled,
1171 prefs->GetBoolean(prefs::kForceGoogleSafeSearch));
1173 EXPECT_EQ(youtube != 0 || legacy_in_effect,
1174 prefs->IsManagedPreference(prefs::kForceYouTubeSafetyMode));
1175 EXPECT_EQ(youtube == 1 || legacy_enabled,
1176 prefs->GetBoolean(prefs::kForceYouTubeSafetyMode));
1178 CheckSafeSearch(google == 1 || legacy_enabled);
1182 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1183 MakeRequestFail make_request_fail("search.example");
1185 search::EnableQueryExtractionForTesting();
1187 // Verifies that a default search is made using the provider configured via
1188 // policy. Also checks that default search can be completely disabled.
1189 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1190 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1191 const std::string kInstantURL("http://does/not/exist");
1192 const std::string kAlternateURL0(
1193 "https://www.google.com/search#q={searchTerms}");
1194 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1195 const std::string kSearchTermsReplacementKey(
1196 "{google:instantExtendedEnabledKey}");
1198 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1199 browser()->profile());
1200 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1201 TemplateURL* default_search = service->GetDefaultSearchProvider();
1202 ASSERT_TRUE(default_search);
1203 EXPECT_NE(kKeyword, default_search->keyword());
1204 EXPECT_NE(kSearchURL, default_search->url());
1205 EXPECT_NE(kInstantURL, default_search->instant_url());
1206 EXPECT_FALSE(
1207 default_search->alternate_urls().size() == 2 &&
1208 default_search->alternate_urls()[0] == kAlternateURL0 &&
1209 default_search->alternate_urls()[1] == kAlternateURL1);
1211 // Override the default search provider using policies.
1212 PolicyMap policies;
1213 policies.Set(key::kDefaultSearchProviderEnabled,
1214 POLICY_LEVEL_MANDATORY,
1215 POLICY_SCOPE_USER,
1216 new base::FundamentalValue(true),
1217 NULL);
1218 policies.Set(key::kDefaultSearchProviderKeyword,
1219 POLICY_LEVEL_MANDATORY,
1220 POLICY_SCOPE_USER,
1221 new base::StringValue(kKeyword),
1222 NULL);
1223 policies.Set(key::kDefaultSearchProviderSearchURL,
1224 POLICY_LEVEL_MANDATORY,
1225 POLICY_SCOPE_USER,
1226 new base::StringValue(kSearchURL),
1227 NULL);
1228 policies.Set(key::kDefaultSearchProviderInstantURL,
1229 POLICY_LEVEL_MANDATORY,
1230 POLICY_SCOPE_USER,
1231 new base::StringValue(kInstantURL),
1232 NULL);
1233 base::ListValue* alternate_urls = new base::ListValue();
1234 alternate_urls->AppendString(kAlternateURL0);
1235 alternate_urls->AppendString(kAlternateURL1);
1236 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1237 POLICY_SCOPE_USER, alternate_urls, NULL);
1238 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1239 POLICY_LEVEL_MANDATORY,
1240 POLICY_SCOPE_USER,
1241 new base::StringValue(kSearchTermsReplacementKey),
1242 NULL);
1243 UpdateProviderPolicy(policies);
1244 default_search = service->GetDefaultSearchProvider();
1245 ASSERT_TRUE(default_search);
1246 EXPECT_EQ(kKeyword, default_search->keyword());
1247 EXPECT_EQ(kSearchURL, default_search->url());
1248 EXPECT_EQ(kInstantURL, default_search->instant_url());
1249 EXPECT_EQ(2U, default_search->alternate_urls().size());
1250 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1251 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1253 // Query terms replacement requires that the renderer process be a recognized
1254 // Instant renderer. Fake it.
1255 InstantService* instant_service =
1256 InstantServiceFactory::GetForProfile(browser()->profile());
1257 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1258 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1260 // Verify that searching from the omnibox does search term replacement with
1261 // first URL pattern.
1262 chrome::FocusLocationBar(browser());
1263 LocationBar* location_bar = browser()->window()->GetLocationBar();
1264 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1265 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1266 "https://www.google.com/?espv=1#q=foobar");
1267 EXPECT_TRUE(
1268 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1269 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1271 // Verify that not using espv=1 does not do search term replacement.
1272 chrome::FocusLocationBar(browser());
1273 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1274 "https://www.google.com/?q=foobar");
1275 EXPECT_FALSE(
1276 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1277 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1278 omnibox_view->GetText());
1280 // Verify that searching from the omnibox does search term replacement with
1281 // second URL pattern.
1282 chrome::FocusLocationBar(browser());
1283 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1284 "https://www.google.com/search?espv=1#q=banana");
1285 EXPECT_TRUE(
1286 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1287 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1289 // Verify that searching from the omnibox does search term replacement with
1290 // standard search URL pattern.
1291 chrome::FocusLocationBar(browser());
1292 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1293 "https://www.google.com/search?q=tractor+parts&espv=1");
1294 EXPECT_TRUE(
1295 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1296 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1298 // Verify that searching from the omnibox prioritizes hash over query.
1299 chrome::FocusLocationBar(browser());
1300 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1301 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1302 EXPECT_TRUE(
1303 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1304 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1307 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1308 // This test assumes Gpu access.
1309 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1310 return;
1312 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
1313 // WebGL is enabled by default.
1314 content::WebContents* contents =
1315 browser()->tab_strip_model()->GetActiveWebContents();
1316 EXPECT_TRUE(IsWebGLEnabled(contents));
1317 // Disable with a policy.
1318 PolicyMap policies;
1319 policies.Set(key::kDisable3DAPIs,
1320 POLICY_LEVEL_MANDATORY,
1321 POLICY_SCOPE_USER,
1322 new base::FundamentalValue(true),
1323 NULL);
1324 UpdateProviderPolicy(policies);
1325 // Crash and reload the tab to get a new renderer.
1326 content::CrashTab(contents);
1327 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1328 EXPECT_FALSE(IsWebGLEnabled(contents));
1329 // Enable with a policy.
1330 policies.Set(key::kDisable3DAPIs,
1331 POLICY_LEVEL_MANDATORY,
1332 POLICY_SCOPE_USER,
1333 new base::FundamentalValue(false),
1334 NULL);
1335 UpdateProviderPolicy(policies);
1336 content::CrashTab(contents);
1337 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1338 EXPECT_TRUE(IsWebGLEnabled(contents));
1341 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1342 // Verifies that SPDY can be disable by policy.
1343 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1344 PolicyMap policies;
1345 policies.Set(key::kDisableSpdy,
1346 POLICY_LEVEL_MANDATORY,
1347 POLICY_SCOPE_USER,
1348 new base::FundamentalValue(true),
1349 NULL);
1350 UpdateProviderPolicy(policies);
1351 content::RunAllPendingInMessageLoop();
1352 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1353 // Verify that it can be force-enabled too.
1354 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1355 policies.Set(key::kDisableSpdy,
1356 POLICY_LEVEL_MANDATORY,
1357 POLICY_SCOPE_USER,
1358 new base::FundamentalValue(false),
1359 NULL);
1360 UpdateProviderPolicy(policies);
1361 content::RunAllPendingInMessageLoop();
1362 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1365 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1366 // Verifies that plugins can be forced to be disabled by policy.
1368 // Verify that the Flash plugin exists and that it can be enabled and disabled
1369 // by the user.
1370 std::vector<content::WebPluginInfo> plugins;
1371 GetPluginList(&plugins);
1372 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1373 if (!flash)
1374 return;
1375 PluginPrefs* plugin_prefs =
1376 PluginPrefs::GetForProfile(browser()->profile()).get();
1377 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1378 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1379 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1380 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1381 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1383 // Now disable it with a policy.
1384 base::ListValue disabled_plugins;
1385 disabled_plugins.Append(new base::StringValue("*Flash*"));
1386 PolicyMap policies;
1387 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1388 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1389 UpdateProviderPolicy(policies);
1390 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1391 // The user shouldn't be able to enable it.
1392 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1393 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1396 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1397 // Verifies that plugins with an exception in the blacklist can be enabled.
1399 // Verify that the Flash plugin exists and that it can be enabled and disabled
1400 // by the user.
1401 std::vector<content::WebPluginInfo> plugins;
1402 GetPluginList(&plugins);
1403 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1404 if (!flash)
1405 return;
1406 PluginPrefs* plugin_prefs =
1407 PluginPrefs::GetForProfile(browser()->profile()).get();
1408 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1410 // Disable all plugins.
1411 base::ListValue disabled_plugins;
1412 disabled_plugins.Append(new base::StringValue("*"));
1413 PolicyMap policies;
1414 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1415 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1416 UpdateProviderPolicy(policies);
1417 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1418 // The user shouldn't be able to enable it.
1419 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1420 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1422 // Now open an exception for flash.
1423 base::ListValue disabled_plugins_exceptions;
1424 disabled_plugins_exceptions.Append(new base::StringValue("*Flash*"));
1425 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1426 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1427 UpdateProviderPolicy(policies);
1428 // It should revert to the user's preference automatically.
1429 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1430 // And the user should be able to disable and enable again.
1431 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1432 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1433 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1434 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1437 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1438 // Verifies that a plugin can be force-installed with a policy.
1439 std::vector<content::WebPluginInfo> plugins;
1440 GetPluginList(&plugins);
1441 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1442 if (!flash)
1443 return;
1444 PluginPrefs* plugin_prefs =
1445 PluginPrefs::GetForProfile(browser()->profile()).get();
1446 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1448 // The user disables it and then a policy forces it to be enabled.
1449 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1450 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1451 base::ListValue plugin_list;
1452 plugin_list.Append(new base::StringValue(content::kFlashPluginName));
1453 PolicyMap policies;
1454 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1455 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1456 UpdateProviderPolicy(policies);
1457 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1458 // The user can't disable it anymore.
1459 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1460 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1462 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1463 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1464 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1465 UpdateProviderPolicy(policies);
1466 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1469 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1470 // Verifies that dangerous plugins can be always authorized to run with
1471 // a policy.
1473 // Verify that the test page exists. It is only present in checkouts with
1474 // src-internal.
1475 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1476 base::FilePath(FILE_PATH_LITERAL("plugin")),
1477 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1478 LOG(INFO) <<
1479 "Test skipped because plugin/quicktime.html test file wasn't found.";
1480 return;
1483 ServeContentTestData();
1484 // No plugins at startup.
1485 EXPECT_EQ(0, CountPlugins());
1487 content::WebContents* contents =
1488 browser()->tab_strip_model()->GetActiveWebContents();
1489 ASSERT_TRUE(contents);
1490 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1491 ASSERT_TRUE(infobar_service);
1492 EXPECT_EQ(0u, infobar_service->infobar_count());
1494 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1495 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1496 ui_test_utils::NavigateToURL(browser(), url);
1497 // This should have triggered the dangerous plugin infobar.
1498 ASSERT_EQ(1u, infobar_service->infobar_count());
1499 EXPECT_TRUE(
1500 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1501 // And the plugin isn't running.
1502 EXPECT_EQ(0, CountPlugins());
1504 // Now set a policy to always authorize this.
1505 PolicyMap policies;
1506 policies.Set(key::kAlwaysAuthorizePlugins,
1507 POLICY_LEVEL_MANDATORY,
1508 POLICY_SCOPE_USER,
1509 new base::FundamentalValue(true),
1510 NULL);
1511 UpdateProviderPolicy(policies);
1512 // Reloading the page shouldn't trigger the infobar this time.
1513 ui_test_utils::NavigateToURL(browser(), url);
1514 EXPECT_EQ(0u, infobar_service->infobar_count());
1515 // And the plugin started automatically.
1516 EXPECT_EQ(1, CountPlugins());
1519 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1520 // Verifies that access to the developer tools can be disabled.
1522 // Open devtools.
1523 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1524 content::WebContents* contents =
1525 browser()->tab_strip_model()->GetActiveWebContents();
1526 DevToolsWindow* devtools_window =
1527 DevToolsWindow::GetInstanceForInspectedWebContents(contents);
1528 EXPECT_TRUE(devtools_window);
1530 // Disable devtools via policy.
1531 PolicyMap policies;
1532 policies.Set(key::kDeveloperToolsDisabled,
1533 POLICY_LEVEL_MANDATORY,
1534 POLICY_SCOPE_USER,
1535 new base::FundamentalValue(true),
1536 NULL);
1537 content::WindowedNotificationObserver close_observer(
1538 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1539 content::Source<content::WebContents>(
1540 DevToolsWindowTesting::Get(devtools_window)->main_web_contents()));
1541 UpdateProviderPolicy(policies);
1542 // wait for devtools close
1543 close_observer.Wait();
1544 // The existing devtools window should have closed.
1545 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1546 // And it's not possible to open it again.
1547 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1548 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents));
1551 // TODO(samarth): remove along with rest of NTP4 code.
1552 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1553 #if defined(OS_WIN) && defined(USE_ASH)
1554 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1555 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1556 switches::kAshBrowserTests))
1557 return;
1558 #endif
1560 // Verifies that the web store icons can be hidden from the new tab page.
1562 // Open new tab page and look for the web store icons.
1563 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1564 content::WebContents* contents =
1565 browser()->tab_strip_model()->GetActiveWebContents();
1567 #if !defined(OS_CHROMEOS)
1568 // Look for web store's app ID in the apps page.
1569 EXPECT_TRUE(ContainsVisibleElement(contents,
1570 "ahfgeienlihckogmohjhadlkjgocpleb"));
1571 #endif
1573 // The next NTP has no footer.
1574 if (ContainsVisibleElement(contents, "footer"))
1575 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1577 // Turn off the web store icons.
1578 PolicyMap policies;
1579 policies.Set(key::kHideWebStoreIcon,
1580 POLICY_LEVEL_MANDATORY,
1581 POLICY_SCOPE_USER,
1582 new base::FundamentalValue(true),
1583 NULL);
1584 UpdateProviderPolicy(policies);
1586 // The web store icons should now be hidden.
1587 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1588 EXPECT_FALSE(ContainsVisibleElement(contents,
1589 "ahfgeienlihckogmohjhadlkjgocpleb"));
1590 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1593 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1594 // Verifies that the download directory can be forced by policy.
1596 // Set the initial download directory.
1597 base::ScopedTempDir initial_dir;
1598 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1599 browser()->profile()->GetPrefs()->SetFilePath(
1600 prefs::kDownloadDefaultDirectory, initial_dir.path());
1601 // Don't prompt for the download location during this test.
1602 browser()->profile()->GetPrefs()->SetBoolean(
1603 prefs::kPromptForDownload, false);
1605 // Verify that downloads end up on the default directory.
1606 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1607 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1608 base::DieFileDie(initial_dir.path().Append(file), false);
1610 // Override the download directory with the policy and verify a download.
1611 base::ScopedTempDir forced_dir;
1612 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1613 PolicyMap policies;
1614 policies.Set(key::kDownloadDirectory,
1615 POLICY_LEVEL_MANDATORY,
1616 POLICY_SCOPE_USER,
1617 new base::StringValue(forced_dir.path().value()),
1618 NULL);
1619 UpdateProviderPolicy(policies);
1620 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1621 // Verify that the first download location wasn't affected.
1622 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1625 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1626 // Verifies that blacklisted extensions can't be installed.
1627 ExtensionService* service = extension_service();
1628 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1629 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1630 base::ListValue blacklist;
1631 blacklist.Append(new base::StringValue(kGoodCrxId));
1632 PolicyMap policies;
1633 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1634 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1635 UpdateProviderPolicy(policies);
1637 // "good.crx" is blacklisted.
1638 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1639 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1641 // "adblock.crx" is not.
1642 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1643 ASSERT_TRUE(adblock);
1644 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1645 EXPECT_EQ(adblock,
1646 service->GetExtensionById(kAdBlockCrxId, true));
1649 // Flaky on windows; http://crbug.com/307994.
1650 #if defined(OS_WIN)
1651 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1652 #else
1653 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1654 #endif
1655 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1656 // Verify that a wildcard blacklist takes effect.
1657 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1658 ExtensionService* service = extension_service();
1659 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1660 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1661 base::ListValue blacklist;
1662 blacklist.Append(new base::StringValue("*"));
1663 PolicyMap policies;
1664 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1665 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1666 UpdateProviderPolicy(policies);
1668 // AdBlock was automatically removed.
1669 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1671 // And can't be installed again, nor can good.crx.
1672 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1673 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1674 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1675 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1678 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSharedModules) {
1679 // Verifies that shared_modules are not affected by the blacklist.
1681 const char kImporterId[] = "pchakhniekfaeoddkifplhnfbffomabh";
1682 const char kSharedModuleId[] = "nfgclafboonjbiafbllihiailjlhelpm";
1684 // Make sure that "import" and "export" are available to these extension IDs
1685 // by mocking the release channel.
1686 extensions::ScopedCurrentChannel channel(version_info::Channel::DEV);
1688 // Verify that the extensions are not installed initially.
1689 ExtensionService* service = extension_service();
1690 ASSERT_FALSE(service->GetExtensionById(kImporterId, true));
1691 ASSERT_FALSE(service->GetExtensionById(kSharedModuleId, true));
1693 // Mock the webstore update URL. This is where the shared module extension
1694 // will be installed from.
1695 base::FilePath update_xml_path = base::FilePath(kTestExtensionsDir)
1696 .AppendASCII("policy_shared_module")
1697 .AppendASCII("update.xml");
1698 GURL update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path));
1699 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1700 switches::kAppsGalleryUpdateURL, update_xml_url.spec());
1701 ui_test_utils::NavigateToURL(browser(), update_xml_url);
1703 // Blacklist "*" but force-install the importer extension. The shared module
1704 // should be automatically installed too.
1705 base::ListValue blacklist;
1706 blacklist.AppendString("*");
1707 base::ListValue forcelist;
1708 forcelist.AppendString(
1709 base::StringPrintf("%s;%s", kImporterId, update_xml_url.spec().c_str()));
1710 PolicyMap policies;
1711 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1712 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1713 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1714 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1716 extensions::ExtensionRegistry* registry =
1717 extensions::ExtensionRegistry::Get(browser()->profile());
1718 extensions::TestExtensionRegistryObserver observe_importer(
1719 registry, kImporterId);
1720 extensions::TestExtensionRegistryObserver observe_shared_module(
1721 registry, kSharedModuleId);
1722 UpdateProviderPolicy(policies);
1723 observe_importer.WaitForExtensionLoaded();
1724 observe_shared_module.WaitForExtensionLoaded();
1726 // Verify that both extensions got installed.
1727 const extensions::Extension* importer =
1728 service->GetExtensionById(kImporterId, true);
1729 ASSERT_TRUE(importer);
1730 EXPECT_EQ(kImporterId, importer->id());
1731 const extensions::Extension* shared_module =
1732 service->GetExtensionById(kSharedModuleId, true);
1733 ASSERT_TRUE(shared_module);
1734 EXPECT_EQ(kSharedModuleId, shared_module->id());
1735 EXPECT_TRUE(shared_module->is_shared_module());
1737 // Verify the dependency.
1738 scoped_ptr<extensions::ExtensionSet> set =
1739 service->shared_module_service()->GetDependentExtensions(shared_module);
1740 ASSERT_TRUE(set);
1741 EXPECT_EQ(1u, set->size());
1742 EXPECT_TRUE(set->Contains(importer->id()));
1744 std::vector<extensions::SharedModuleInfo::ImportInfo> imports =
1745 extensions::SharedModuleInfo::GetImports(importer);
1746 ASSERT_EQ(1u, imports.size());
1747 EXPECT_EQ(kSharedModuleId, imports[0].extension_id);
1750 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1751 // Verifies that the whitelist can open exceptions to the blacklist.
1752 ExtensionService* service = extension_service();
1753 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1754 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1755 base::ListValue blacklist;
1756 blacklist.Append(new base::StringValue("*"));
1757 base::ListValue whitelist;
1758 whitelist.Append(new base::StringValue(kGoodCrxId));
1759 PolicyMap policies;
1760 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1761 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1762 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1763 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1764 UpdateProviderPolicy(policies);
1765 // "adblock.crx" is blacklisted.
1766 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1767 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1768 // "good.crx" has a whitelist exception.
1769 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1770 ASSERT_TRUE(good);
1771 EXPECT_EQ(kGoodCrxId, good->id());
1772 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1773 // The user can also remove this extension.
1774 UninstallExtension(kGoodCrxId, true);
1777 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1778 // Verifies that extensions that are force-installed by policies are
1779 // installed and can't be uninstalled.
1780 ExtensionService* service = extension_service();
1781 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1783 // Extensions that are force-installed come from an update URL, which defaults
1784 // to the webstore. Use a mock URL for this test with an update manifest
1785 // that includes "good_v1.crx".
1786 base::FilePath path =
1787 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1788 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1790 // Setting the forcelist extension should install "good_v1.crx".
1791 base::ListValue forcelist;
1792 forcelist.Append(new base::StringValue(
1793 base::StringPrintf("%s;%s", kGoodCrxId, url.spec().c_str())));
1794 PolicyMap policies;
1795 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1796 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1797 content::WindowedNotificationObserver observer(
1798 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1799 content::NotificationService::AllSources());
1800 UpdateProviderPolicy(policies);
1801 observer.Wait();
1802 // Note: Cannot check that the notification details match the expected
1803 // exception, since the details object has already been freed prior to
1804 // the completion of observer.Wait().
1806 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1808 // The user is not allowed to uninstall force-installed extensions.
1809 UninstallExtension(kGoodCrxId, false);
1811 // The user is not allowed to load an unpacked extension with the
1812 // same ID as a force-installed extension.
1813 LoadUnpackedExtension(kGoodUnpackedExt, false);
1815 // Loading other unpacked extensions are not blocked.
1816 LoadUnpackedExtension(kAppUnpackedExt, true);
1818 const std::string old_version_number =
1819 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1821 base::FilePath test_path;
1822 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1824 TestRequestInterceptor interceptor(
1825 "update.extension",
1826 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1827 interceptor.PushJobCallback(
1828 TestRequestInterceptor::FileJob(
1829 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1831 // Updating the force-installed extension.
1832 extensions::ExtensionUpdater* updater = service->updater();
1833 extensions::ExtensionUpdater::CheckParams params;
1834 params.install_immediately = true;
1835 content::WindowedNotificationObserver update_observer(
1836 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1837 content::NotificationService::AllSources());
1838 updater->CheckNow(params);
1839 update_observer.Wait();
1841 const base::Version* new_version =
1842 service->GetExtensionById(kGoodCrxId, true)->version();
1843 ASSERT_TRUE(new_version->IsValid());
1844 base::Version old_version(old_version_number);
1845 ASSERT_TRUE(old_version.IsValid());
1847 EXPECT_EQ(1, new_version->CompareTo(old_version));
1849 EXPECT_EQ(0u, interceptor.GetPendingSize());
1851 // Wait until any background pages belonging to force-installed extensions
1852 // have been loaded.
1853 extensions::ProcessManager* manager =
1854 extensions::ProcessManager::Get(browser()->profile());
1855 extensions::ProcessManager::FrameSet all_frames = manager->GetAllFrames();
1856 for (extensions::ProcessManager::FrameSet::const_iterator iter =
1857 all_frames.begin();
1858 iter != all_frames.end();) {
1859 content::WebContents* web_contents =
1860 content::WebContents::FromRenderFrameHost(*iter);
1861 ASSERT_TRUE(web_contents);
1862 if (!web_contents->IsLoading()) {
1863 ++iter;
1864 } else {
1865 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1867 // Test activity may have modified the set of extension processes during
1868 // message processing, so re-start the iteration to catch added/removed
1869 // processes.
1870 all_frames = manager->GetAllFrames();
1871 iter = all_frames.begin();
1875 // Test policy-installed extensions are reloaded when killed.
1876 BackgroundContentsService::
1877 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1878 content::WindowedNotificationObserver extension_crashed_observer(
1879 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1880 content::NotificationService::AllSources());
1881 content::WindowedNotificationObserver extension_loaded_observer(
1882 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1883 content::NotificationService::AllSources());
1884 extensions::ExtensionHost* extension_host =
1885 extensions::ProcessManager::Get(browser()->profile())
1886 ->GetBackgroundHostForExtension(kGoodCrxId);
1887 extension_host->render_process_host()->Shutdown(content::RESULT_CODE_KILLED,
1888 false);
1889 extension_crashed_observer.Wait();
1890 extension_loaded_observer.Wait();
1893 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionRecommendedInstallationMode) {
1894 // Verifies that extensions that are recommended-installed by policies are
1895 // installed, can be disabled but not uninstalled.
1896 ExtensionService* service = extension_service();
1897 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1899 base::FilePath path =
1900 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1901 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1903 // Setting the forcelist extension should install "good_v1.crx".
1904 base::DictionaryValue dict_value;
1905 dict_value.SetString(std::string(kGoodCrxId) + "." +
1906 extensions::schema_constants::kInstallationMode,
1907 extensions::schema_constants::kNormalInstalled);
1908 dict_value.SetString(
1909 std::string(kGoodCrxId) + "." + extensions::schema_constants::kUpdateUrl,
1910 url.spec());
1911 PolicyMap policies;
1912 policies.Set(key::kExtensionSettings,
1913 POLICY_LEVEL_MANDATORY,
1914 POLICY_SCOPE_USER,
1915 dict_value.DeepCopy(),
1916 NULL);
1917 content::WindowedNotificationObserver observer(
1918 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
1919 content::NotificationService::AllSources());
1920 UpdateProviderPolicy(policies);
1921 observer.Wait();
1923 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1925 // The user is not allowed to uninstall recommended-installed extensions.
1926 UninstallExtension(kGoodCrxId, false);
1928 // Explictly re-enables the extension.
1929 service->EnableExtension(kGoodCrxId);
1931 // But the user is allowed to disable them.
1932 EXPECT_TRUE(service->IsExtensionEnabled(kGoodCrxId));
1933 DisableExtension(kGoodCrxId);
1934 EXPECT_FALSE(service->IsExtensionEnabled(kGoodCrxId));
1937 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1938 // Verifies that extensions are blocked if policy specifies an allowed types
1939 // list and the extension's type is not on that list.
1940 ExtensionService* service = extension_service();
1941 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1942 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1944 base::ListValue allowed_types;
1945 allowed_types.AppendString("hosted_app");
1946 PolicyMap policies;
1947 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1948 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1949 UpdateProviderPolicy(policies);
1951 // "good.crx" is blocked.
1952 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1953 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1955 // "hosted_app.crx" is of a whitelisted type.
1956 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1957 ASSERT_TRUE(hosted_app);
1958 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1959 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1961 // The user can remove the extension.
1962 UninstallExtension(kHostedAppCrxId, true);
1965 // Checks that a click on an extension CRX download triggers the extension
1966 // installation prompt without further user interaction when the source is
1967 // whitelisted by policy.
1968 // Flaky on windows; http://crbug.com/295729 .
1969 #if defined(OS_WIN)
1970 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1971 #else
1972 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1973 #endif
1974 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1975 extensions::ScopedTestDialogAutoConfirm auto_confirm(
1976 extensions::ScopedTestDialogAutoConfirm::ACCEPT);
1978 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1979 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1980 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1981 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1983 base::ScopedTempDir download_directory;
1984 ASSERT_TRUE(download_directory.CreateUniqueTempDir());
1985 DownloadPrefs* download_prefs =
1986 DownloadPrefs::FromBrowserContext(browser()->profile());
1987 download_prefs->SetDownloadPath(download_directory.path());
1989 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1990 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1991 ui_test_utils::NavigateToURL(browser(), download_page_url);
1993 // As long as the policy is not present, extensions are considered dangerous.
1994 content::DownloadTestObserverTerminal download_observer(
1995 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1996 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1997 PerformClick(0, 0);
1998 download_observer.WaitForFinished();
2000 // Install the policy and trigger another download.
2001 base::ListValue install_sources;
2002 install_sources.AppendString(install_source_url.spec());
2003 install_sources.AppendString(referrer_url.spec());
2004 PolicyMap policies;
2005 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
2006 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
2007 UpdateProviderPolicy(policies);
2009 content::WindowedNotificationObserver observer(
2010 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2011 content::NotificationService::AllSources());
2012 PerformClick(1, 0);
2013 observer.Wait();
2014 // Note: Cannot check that the notification details match the expected
2015 // exception, since the details object has already been freed prior to
2016 // the completion of observer.Wait().
2018 // The first extension shouldn't be present, the second should be there.
2019 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
2020 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
2023 // Verifies that extensions with version older than the minimum version required
2024 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
2025 // policy changes as well as regular auto-updater scheduled updates.
2026 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequired) {
2027 ExtensionService* service = extension_service();
2028 extensions::ExtensionRegistry* registry =
2029 extensions::ExtensionRegistry::Get(browser()->profile());
2030 extensions::ExtensionPrefs* extension_prefs =
2031 extensions::ExtensionPrefs::Get(browser()->profile());
2033 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2034 service->updater()->StopTimerForTesting();
2036 // Setup interceptor for extension updates.
2037 base::FilePath test_path;
2038 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
2039 TestRequestInterceptor interceptor(
2040 "update.extension",
2041 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
2042 interceptor.PushJobCallback(TestRequestInterceptor::BadRequestJob());
2043 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
2044 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
2046 // Install the extension.
2047 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2048 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2050 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2051 // version 1.0.0.0) should still be enabled.
2053 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2054 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.0");
2056 base::RunLoop().RunUntilIdle();
2058 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2060 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2061 // version 1.0.0.0) should now be disabled.
2062 EXPECT_EQ(2u, interceptor.GetPendingSize());
2063 base::RunLoop service_request_run_loop;
2064 interceptor.AddRequestServicedCallback(
2065 service_request_run_loop.QuitClosure());
2067 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2068 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2070 service_request_run_loop.Run();
2071 EXPECT_EQ(1u, interceptor.GetPendingSize());
2073 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2074 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2075 extension_prefs->GetDisableReasons(kGoodCrxId));
2077 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2078 // via the update URL in the manifest of the older version.
2079 EXPECT_EQ(1u, interceptor.GetPendingSize());
2081 content::WindowedNotificationObserver update_observer(
2082 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2083 content::NotificationService::AllSources());
2084 service->updater()->CheckSoon();
2085 update_observer.Wait();
2087 EXPECT_EQ(0u, interceptor.GetPendingSize());
2089 // The extension should be auto-updated to newer version and re-enabled.
2090 EXPECT_EQ("1.0.0.1",
2091 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2092 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2095 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2096 // and orders.
2097 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionRequiredAlt) {
2098 ExtensionService* service = extension_service();
2099 extensions::ExtensionRegistry* registry =
2100 extensions::ExtensionRegistry::Get(browser()->profile());
2101 extensions::ExtensionPrefs* extension_prefs =
2102 extensions::ExtensionPrefs::Get(browser()->profile());
2104 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2105 service->updater()->StopTimerForTesting();
2107 // Setup interceptor for extension updates.
2108 base::FilePath test_path;
2109 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
2110 TestRequestInterceptor interceptor(
2111 "update.extension",
2112 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
2113 interceptor.PushJobCallback(TestRequestInterceptor::FileJob(
2114 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
2116 // Set the policy to require an even higher minimum version this time.
2118 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2119 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.2");
2121 base::RunLoop().RunUntilIdle();
2123 // Install the 1.0.0.0 version, it should be installed but disabled.
2124 EXPECT_TRUE(InstallExtension(kGoodV1CrxName));
2125 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2126 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2127 extension_prefs->GetDisableReasons(kGoodCrxId));
2128 EXPECT_EQ("1.0.0.0",
2129 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2131 // An extension management policy update should trigger an update as well.
2132 EXPECT_EQ(1u, interceptor.GetPendingSize());
2134 content::WindowedNotificationObserver update_observer(
2135 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2136 content::NotificationService::AllSources());
2138 // Set a higher minimum version, just intend to trigger a policy update.
2139 extensions::ExtensionManagementPolicyUpdater management_policy(
2140 &provider_);
2141 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.3");
2143 base::RunLoop().RunUntilIdle();
2144 update_observer.Wait();
2146 EXPECT_EQ(0u, interceptor.GetPendingSize());
2148 // It should be updated to 1.0.0.1 but remain disabled.
2149 EXPECT_EQ("1.0.0.1",
2150 service->GetInstalledExtension(kGoodCrxId)->version()->GetString());
2151 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2152 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2153 extension_prefs->GetDisableReasons(kGoodCrxId));
2155 // Remove the minimum version requirement. The extension should be re-enabled.
2157 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2158 management_policy.UnsetMinimumVersionRequired(kGoodCrxId);
2160 base::RunLoop().RunUntilIdle();
2162 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2163 EXPECT_FALSE(extension_prefs->HasDisableReason(
2164 kGoodCrxId, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY));
2167 // Verifies that a force-installed extension which does not meet a subsequently
2168 // set minimum version requirement is handled well.
2169 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionMinimumVersionForceInstalled) {
2170 extensions::ExtensionRegistry* registry =
2171 extensions::ExtensionRegistry::Get(browser()->profile());
2172 extensions::ExtensionPrefs* extension_prefs =
2173 extensions::ExtensionPrefs::Get(browser()->profile());
2175 // Prepare the update URL for force installing.
2176 const base::FilePath path =
2177 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
2178 const GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
2180 // Set policy to force-install the extension, it should be installed and
2181 // enabled.
2182 content::WindowedNotificationObserver install_observer(
2183 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
2184 content::NotificationService::AllSources());
2185 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2187 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2188 management_policy.SetIndividualExtensionAutoInstalled(kGoodCrxId,
2189 url.spec(), true);
2191 base::RunLoop().RunUntilIdle();
2192 install_observer.Wait();
2194 EXPECT_TRUE(registry->enabled_extensions().Contains(kGoodCrxId));
2196 // Set policy a minimum version of "1.0.0.1", the extension now should be
2197 // disabled.
2199 extensions::ExtensionManagementPolicyUpdater management_policy(&provider_);
2200 management_policy.SetMinimumVersionRequired(kGoodCrxId, "1.0.0.1");
2202 base::RunLoop().RunUntilIdle();
2203 EXPECT_FALSE(registry->enabled_extensions().Contains(kGoodCrxId));
2204 EXPECT_TRUE(registry->disabled_extensions().Contains(kGoodCrxId));
2205 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY,
2206 extension_prefs->GetDisableReasons(kGoodCrxId));
2209 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
2210 #if defined(OS_WIN) && defined(USE_ASH)
2211 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2212 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2213 switches::kAshBrowserTests))
2214 return;
2215 #endif
2217 // Verifies that the homepage can be configured with policies.
2218 // Set a default, and check that the home button navigates there.
2219 browser()->profile()->GetPrefs()->SetString(
2220 prefs::kHomePage, chrome::kChromeUIPolicyURL);
2221 browser()->profile()->GetPrefs()->SetBoolean(
2222 prefs::kHomePageIsNewTabPage, false);
2223 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
2224 browser()->profile()->GetHomePage());
2225 content::WebContents* contents =
2226 browser()->tab_strip_model()->GetActiveWebContents();
2227 EXPECT_EQ(GURL(url::kAboutBlankURL), contents->GetURL());
2228 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2229 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
2231 // Now override with policy.
2232 PolicyMap policies;
2233 policies.Set(key::kHomepageLocation,
2234 POLICY_LEVEL_MANDATORY,
2235 POLICY_SCOPE_USER,
2236 new base::StringValue(chrome::kChromeUICreditsURL),
2237 NULL);
2238 UpdateProviderPolicy(policies);
2239 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2240 content::WaitForLoadStop(contents);
2241 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
2243 policies.Set(key::kHomepageIsNewTabPage,
2244 POLICY_LEVEL_MANDATORY,
2245 POLICY_SCOPE_USER,
2246 new base::FundamentalValue(true),
2247 NULL);
2248 UpdateProviderPolicy(policies);
2249 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
2250 content::WaitForLoadStop(contents);
2251 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
2254 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
2255 // Verifies that incognito windows can't be opened when disabled by policy.
2257 const BrowserList* active_browser_list =
2258 BrowserList::GetInstance(chrome::GetActiveDesktop());
2260 // Disable incognito via policy and verify that incognito windows can't be
2261 // opened.
2262 EXPECT_EQ(1u, active_browser_list->size());
2263 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2264 PolicyMap policies;
2265 policies.Set(key::kIncognitoEnabled,
2266 POLICY_LEVEL_MANDATORY,
2267 POLICY_SCOPE_USER,
2268 new base::FundamentalValue(false),
2269 NULL);
2270 UpdateProviderPolicy(policies);
2271 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2272 EXPECT_EQ(1u, active_browser_list->size());
2273 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2275 // Enable via policy and verify that incognito windows can be opened.
2276 policies.Set(key::kIncognitoEnabled,
2277 POLICY_LEVEL_MANDATORY,
2278 POLICY_SCOPE_USER,
2279 new base::FundamentalValue(true),
2280 NULL);
2281 UpdateProviderPolicy(policies);
2282 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
2283 EXPECT_EQ(2u, active_browser_list->size());
2284 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2287 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
2288 // Verifies that Javascript can be disabled.
2289 content::WebContents* contents =
2290 browser()->tab_strip_model()->GetActiveWebContents();
2291 EXPECT_TRUE(IsJavascriptEnabled(contents));
2292 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2293 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2294 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2296 // Disable Javascript via policy.
2297 PolicyMap policies;
2298 policies.Set(key::kJavascriptEnabled,
2299 POLICY_LEVEL_MANDATORY,
2300 POLICY_SCOPE_USER,
2301 new base::FundamentalValue(false),
2302 NULL);
2303 UpdateProviderPolicy(policies);
2304 // Reload the page.
2305 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2306 EXPECT_FALSE(IsJavascriptEnabled(contents));
2307 // Developer tools still work when javascript is disabled.
2308 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
2309 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
2310 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
2311 // Javascript is always enabled for the internal pages.
2312 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
2313 EXPECT_TRUE(IsJavascriptEnabled(contents));
2315 // The javascript content setting policy overrides the javascript policy.
2316 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2317 EXPECT_FALSE(IsJavascriptEnabled(contents));
2318 policies.Set(key::kDefaultJavaScriptSetting,
2319 POLICY_LEVEL_MANDATORY,
2320 POLICY_SCOPE_USER,
2321 new base::FundamentalValue(CONTENT_SETTING_ALLOW),
2322 NULL);
2323 UpdateProviderPolicy(policies);
2324 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL));
2325 EXPECT_TRUE(IsJavascriptEnabled(contents));
2328 IN_PROC_BROWSER_TEST_F(PolicyTest, NetworkPrediction) {
2329 PrefService* prefs = browser()->profile()->GetPrefs();
2331 // Enabled by default.
2332 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2334 // Disable by old, deprecated policy.
2335 PolicyMap policies;
2336 policies.Set(key::kDnsPrefetchingEnabled,
2337 POLICY_LEVEL_MANDATORY,
2338 POLICY_SCOPE_USER,
2339 new base::FundamentalValue(false),
2340 NULL);
2341 UpdateProviderPolicy(policies);
2343 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs));
2345 // Enabled by new policy, this should override old one.
2346 policies.Set(
2347 key::kNetworkPredictionOptions,
2348 POLICY_LEVEL_MANDATORY,
2349 POLICY_SCOPE_USER,
2350 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS),
2351 NULL);
2352 UpdateProviderPolicy(policies);
2354 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs));
2357 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
2358 // Verifies that browsing history is not saved.
2359 PolicyMap policies;
2360 policies.Set(key::kSavingBrowserHistoryDisabled,
2361 POLICY_LEVEL_MANDATORY,
2362 POLICY_SCOPE_USER,
2363 new base::FundamentalValue(true),
2364 NULL);
2365 UpdateProviderPolicy(policies);
2366 GURL url = ui_test_utils::GetTestUrl(
2367 base::FilePath(base::FilePath::kCurrentDirectory),
2368 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2369 ui_test_utils::NavigateToURL(browser(), url);
2370 // Verify that the navigation wasn't saved in the history.
2371 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
2372 EXPECT_EQ(0u, enumerator1.urls().size());
2374 // Now flip the policy and try again.
2375 policies.Set(key::kSavingBrowserHistoryDisabled,
2376 POLICY_LEVEL_MANDATORY,
2377 POLICY_SCOPE_USER,
2378 new base::FundamentalValue(false),
2379 NULL);
2380 UpdateProviderPolicy(policies);
2381 ui_test_utils::NavigateToURL(browser(), url);
2382 // Verify that the navigation was saved in the history.
2383 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
2384 ASSERT_EQ(1u, enumerator2.urls().size());
2385 EXPECT_EQ(url, enumerator2.urls()[0]);
2388 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2389 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
2390 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2391 if (TranslateService::IsTranslateBubbleEnabled())
2392 return;
2394 scoped_ptr<test::CldDataHarness> cld_data_scope =
2395 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2396 ASSERT_NO_FATAL_FAILURE(cld_data_scope->Init());
2398 // Verifies that translate can be forced enabled or disabled by policy.
2400 // Get the InfoBarService, and verify that there are no infobars on startup.
2401 content::WebContents* contents =
2402 browser()->tab_strip_model()->GetActiveWebContents();
2403 ASSERT_TRUE(contents);
2404 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
2405 ASSERT_TRUE(infobar_service);
2406 EXPECT_EQ(0u, infobar_service->infobar_count());
2408 // Force enable the translate feature.
2409 PolicyMap policies;
2410 policies.Set(key::kTranslateEnabled,
2411 POLICY_LEVEL_MANDATORY,
2412 POLICY_SCOPE_USER,
2413 new base::FundamentalValue(true),
2414 NULL);
2415 UpdateProviderPolicy(policies);
2416 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2417 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2418 // TranslateManager observes. This allows checking that an infobar is NOT
2419 // shown below, without polling for infobars for some indeterminate amount
2420 // of time.
2421 GURL url = ui_test_utils::GetTestUrl(
2422 base::FilePath(),
2423 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2424 content::WindowedNotificationObserver language_observer1(
2425 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2426 content::NotificationService::AllSources());
2427 ui_test_utils::NavigateToURL(browser(), url);
2428 language_observer1.Wait();
2430 // Verify the translation detected for this tab.
2431 ChromeTranslateClient* chrome_translate_client =
2432 ChromeTranslateClient::FromWebContents(contents);
2433 ASSERT_TRUE(chrome_translate_client);
2434 translate::LanguageState& language_state =
2435 chrome_translate_client->GetLanguageState();
2436 EXPECT_EQ("fr", language_state.original_language());
2437 EXPECT_TRUE(language_state.page_needs_translation());
2438 EXPECT_FALSE(language_state.translation_pending());
2439 EXPECT_FALSE(language_state.translation_declined());
2440 EXPECT_FALSE(language_state.IsPageTranslated());
2442 // Verify that the translate infobar showed up.
2443 ASSERT_EQ(1u, infobar_service->infobar_count());
2444 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2445 translate::TranslateInfoBarDelegate* translate_infobar_delegate =
2446 infobar->delegate()->AsTranslateInfoBarDelegate();
2447 ASSERT_TRUE(translate_infobar_delegate);
2448 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
2449 translate_infobar_delegate->translate_step());
2450 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
2452 // Now force disable translate.
2453 infobar_service->RemoveInfoBar(infobar);
2454 EXPECT_EQ(0u, infobar_service->infobar_count());
2455 policies.Set(key::kTranslateEnabled,
2456 POLICY_LEVEL_MANDATORY,
2457 POLICY_SCOPE_USER,
2458 new base::FundamentalValue(false),
2459 NULL);
2460 UpdateProviderPolicy(policies);
2461 // Navigating to the same URL now doesn't trigger an infobar.
2462 content::WindowedNotificationObserver language_observer2(
2463 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
2464 content::NotificationService::AllSources());
2465 ui_test_utils::NavigateToURL(browser(), url);
2466 language_observer2.Wait();
2467 EXPECT_EQ(0u, infobar_service->infobar_count());
2470 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
2471 // Checks that URLs can be blacklisted, and that exceptions can be made to
2472 // the blacklist.
2474 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2475 // as URLRequestMockHTTPJobs.
2476 const char* kURLS[] = {
2477 "http://aaa.com/empty.html",
2478 "http://bbb.com/empty.html",
2479 "http://sub.bbb.com/empty.html",
2480 "http://bbb.com/policy/blank.html",
2481 "http://bbb.com./policy/blank.html",
2484 base::RunLoop loop;
2485 BrowserThread::PostTaskAndReply(
2486 BrowserThread::IO, FROM_HERE,
2487 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
2488 loop.QuitClosure());
2489 loop.Run();
2492 // Verify that "bbb.com" opens before applying the blacklist.
2493 CheckCanOpenURL(browser(), kURLS[1]);
2495 // Set a blacklist.
2496 base::ListValue blacklist;
2497 blacklist.Append(new base::StringValue("bbb.com"));
2498 PolicyMap policies;
2499 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2500 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2501 UpdateProviderPolicy(policies);
2502 FlushBlacklistPolicy();
2503 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2504 CheckCanOpenURL(browser(), kURLS[0]);
2505 for (size_t i = 1; i < arraysize(kURLS); ++i)
2506 CheckURLIsBlocked(browser(), kURLS[i]);
2508 // Whitelist some sites of bbb.com.
2509 base::ListValue whitelist;
2510 whitelist.Append(new base::StringValue("sub.bbb.com"));
2511 whitelist.Append(new base::StringValue("bbb.com/policy"));
2512 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2513 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2514 UpdateProviderPolicy(policies);
2515 FlushBlacklistPolicy();
2516 CheckURLIsBlocked(browser(), kURLS[1]);
2517 CheckCanOpenURL(browser(), kURLS[2]);
2518 CheckCanOpenURL(browser(), kURLS[3]);
2519 CheckCanOpenURL(browser(), kURLS[4]);
2522 base::RunLoop loop;
2523 BrowserThread::PostTaskAndReply(
2524 BrowserThread::IO, FROM_HERE,
2525 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
2526 loop.QuitClosure());
2527 loop.Run();
2531 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklistSubresources) {
2532 // Checks that an image with a blacklisted URL is loaded, but an iframe with a
2533 // blacklisted URL is not.
2535 GURL main_url = URLRequestMockHTTPJob::GetMockUrl(
2536 base::FilePath(FILE_PATH_LITERAL("policy/blacklist-subresources.html")));
2537 GURL image_url = URLRequestMockHTTPJob::GetMockUrl(
2538 base::FilePath(FILE_PATH_LITERAL("policy/pixel.png")));
2539 GURL subframe_url = URLRequestMockHTTPJob::GetMockUrl(
2540 base::FilePath(FILE_PATH_LITERAL("policy/blank.html")));
2542 // Set a blacklist containing the image and the iframe which are used by the
2543 // main document.
2544 base::ListValue blacklist;
2545 blacklist.Append(new base::StringValue(image_url.spec().c_str()));
2546 blacklist.Append(new base::StringValue(subframe_url.spec().c_str()));
2547 PolicyMap policies;
2548 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2549 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2550 UpdateProviderPolicy(policies);
2551 FlushBlacklistPolicy();
2553 std::string blacklisted_image_load_result;
2554 ui_test_utils::NavigateToURL(browser(), main_url);
2555 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2556 browser()->tab_strip_model()->GetActiveWebContents(),
2557 "window.domAutomationController.send(imageLoadResult)",
2558 &blacklisted_image_load_result));
2559 EXPECT_EQ("success", blacklisted_image_load_result);
2561 std::string blacklisted_iframe_load_result;
2562 ui_test_utils::NavigateToURL(browser(), main_url);
2563 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2564 browser()->tab_strip_model()->GetActiveWebContents(),
2565 "window.domAutomationController.send(iframeLoadResult)",
2566 &blacklisted_iframe_load_result));
2567 EXPECT_EQ("error", blacklisted_iframe_load_result);
2570 #if defined(OS_MACOSX)
2571 // http://crbug.com/339240
2572 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2573 #else
2574 #define MAYBE_FileURLBlacklist FileURLBlacklist
2575 #endif
2576 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_FileURLBlacklist) {
2577 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2578 // with URLblacklisting and URLwhitelisting.
2580 base::FilePath test_path;
2581 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
2582 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
2583 const std::string folder_path = base_path + "apptest/";
2584 const std::string file_path1 = base_path + "title1.html";
2585 const std::string file_path2 = folder_path + "basic.html";
2587 CheckCanOpenURL(browser(), file_path1.c_str());
2588 CheckCanOpenURL(browser(), file_path2.c_str());
2590 // Set a blacklist for all the files.
2591 base::ListValue blacklist;
2592 blacklist.Append(new base::StringValue("file://*"));
2593 PolicyMap policies;
2594 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2595 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2596 UpdateProviderPolicy(policies);
2597 FlushBlacklistPolicy();
2599 CheckURLIsBlocked(browser(), file_path1.c_str());
2600 CheckURLIsBlocked(browser(), file_path2.c_str());
2602 // Replace the URLblacklist with disabling the file scheme.
2603 blacklist.Remove(base::StringValue("file://*"), NULL);
2604 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2605 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2606 UpdateProviderPolicy(policies);
2607 FlushBlacklistPolicy();
2609 PrefService* prefs = browser()->profile()->GetPrefs();
2610 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2611 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2612 list_url->end());
2614 base::ListValue disabledscheme;
2615 disabledscheme.Append(new base::StringValue("file"));
2616 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2617 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2618 UpdateProviderPolicy(policies);
2619 FlushBlacklistPolicy();
2621 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2622 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2623 list_url->end());
2625 // Whitelist one folder and blacklist an another just inside.
2626 base::ListValue whitelist;
2627 whitelist.Append(new base::StringValue(base_path));
2628 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2629 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2630 blacklist.Append(new base::StringValue(folder_path));
2631 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2632 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2633 UpdateProviderPolicy(policies);
2634 FlushBlacklistPolicy();
2636 CheckCanOpenURL(browser(), file_path1.c_str());
2637 CheckURLIsBlocked(browser(), file_path2.c_str());
2640 namespace {
2642 void GetSSLVersionFallbackMinOnIOThread(
2643 const scoped_refptr<net::SSLConfigService>& config_service,
2644 uint16_t* version_fallback_min) {
2645 net::SSLConfig config;
2646 config_service->GetSSLConfig(&config);
2647 *version_fallback_min = config.version_fallback_min;
2650 uint16_t GetSSLVersionFallbackMin(Profile* profile) {
2651 scoped_refptr<net::SSLConfigService> config_service(
2652 profile->GetSSLConfigService());
2653 uint16_t version_fallback_min;
2654 base::RunLoop loop;
2655 BrowserThread::PostTaskAndReply(
2656 BrowserThread::IO, FROM_HERE,
2657 base::Bind(&GetSSLVersionFallbackMinOnIOThread, config_service,
2658 base::Unretained(&version_fallback_min)),
2659 loop.QuitClosure());
2660 loop.Run();
2661 return version_fallback_min;
2664 } // namespace
2666 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLVersionFallbackMin) {
2667 PrefService* prefs = g_browser_process->local_state();
2669 const std::string new_value("tls1.2");
2670 const std::string default_value(
2671 prefs->GetString(prefs::kSSLVersionFallbackMin));
2673 EXPECT_NE(default_value, new_value);
2674 EXPECT_NE(net::SSL_PROTOCOL_VERSION_TLS1_2,
2675 GetSSLVersionFallbackMin(browser()->profile()));
2677 PolicyMap policies;
2678 policies.Set(key::kSSLVersionFallbackMin,
2679 POLICY_LEVEL_MANDATORY,
2680 POLICY_SCOPE_USER,
2681 new base::StringValue(new_value),
2682 NULL);
2683 UpdateProviderPolicy(policies);
2685 EXPECT_EQ(net::SSL_PROTOCOL_VERSION_TLS1_2,
2686 GetSSLVersionFallbackMin(browser()->profile()));
2689 #if !defined(OS_MACOSX)
2690 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2691 PolicyMap policies;
2692 policies.Set(key::kFullscreenAllowed,
2693 POLICY_LEVEL_MANDATORY,
2694 POLICY_SCOPE_USER,
2695 new base::FundamentalValue(false),
2696 NULL);
2697 UpdateProviderPolicy(policies);
2699 BrowserWindow* browser_window = browser()->window();
2700 ASSERT_TRUE(browser_window);
2702 EXPECT_FALSE(browser_window->IsFullscreen());
2703 chrome::ToggleFullscreenMode(browser());
2704 EXPECT_FALSE(browser_window->IsFullscreen());
2707 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2708 PolicyMap policies;
2709 policies.Set(key::kFullscreenAllowed,
2710 POLICY_LEVEL_MANDATORY,
2711 POLICY_SCOPE_USER,
2712 new base::FundamentalValue(false),
2713 NULL);
2714 UpdateProviderPolicy(policies);
2716 const extensions::Extension* extension =
2717 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2718 ASSERT_TRUE(extension);
2720 // Launch an app that tries to open a fullscreen window.
2721 TestAddAppWindowObserver add_window_observer(
2722 extensions::AppWindowRegistry::Get(browser()->profile()));
2723 OpenApplication(AppLaunchParams(browser()->profile(), extension,
2724 extensions::LAUNCH_CONTAINER_NONE, NEW_WINDOW,
2725 extensions::SOURCE_TEST));
2726 extensions::AppWindow* window = add_window_observer.WaitForAppWindow();
2727 ASSERT_TRUE(window);
2729 // Verify that the window is not in fullscreen mode.
2730 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2732 // Verify that the window cannot be toggled into fullscreen mode via apps
2733 // APIs.
2734 EXPECT_TRUE(content::ExecuteScript(
2735 window->web_contents(),
2736 "chrome.app.window.current().fullscreen();"));
2737 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2739 // Verify that the window cannot be toggled into fullscreen mode from within
2740 // Chrome (e.g., using keyboard accelerators).
2741 window->Fullscreen();
2742 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2744 #endif
2746 #if defined(OS_CHROMEOS)
2748 // Flaky http://crbug.com/476964
2749 #if defined(MEMORY_SANITIZER)
2750 #define MAYBE_DisableScreenshotsFile DISABLED_DisableScreenshotsFile
2751 #else
2752 #define MAYBE_DisableScreenshotsFile DisableScreenshotsFile
2753 #endif
2755 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_DisableScreenshotsFile) {
2756 int screenshot_count = CountScreenshots();
2758 // Make sure screenshots are counted correctly.
2759 TestScreenshotFile(true);
2760 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2762 // Check if trying to take a screenshot fails when disabled by policy.
2763 TestScreenshotFile(false);
2764 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2767 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2768 // Set up the mock observer.
2769 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2770 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2771 audio_handler->AddAudioObserver(test_observer.get());
2773 bool prior_state = audio_handler->IsOutputMuted();
2774 // Make sure the audio is not muted and then toggle the policy and observe
2775 // if the output mute changed event is fired.
2776 audio_handler->SetOutputMute(false);
2777 EXPECT_FALSE(audio_handler->IsOutputMuted());
2778 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2779 PolicyMap policies;
2780 policies.Set(key::kAudioOutputAllowed,
2781 POLICY_LEVEL_MANDATORY,
2782 POLICY_SCOPE_USER,
2783 new base::FundamentalValue(false),
2784 NULL);
2785 UpdateProviderPolicy(policies);
2786 EXPECT_TRUE(audio_handler->IsOutputMuted());
2787 // This should not change the state now and should not trigger output mute
2788 // changed event.
2789 audio_handler->SetOutputMute(false);
2790 EXPECT_TRUE(audio_handler->IsOutputMuted());
2791 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2793 // Toggle back and observe if the output mute changed event is fired.
2794 policies.Set(key::kAudioOutputAllowed,
2795 POLICY_LEVEL_MANDATORY,
2796 POLICY_SCOPE_USER,
2797 new base::FundamentalValue(true),
2798 NULL);
2799 UpdateProviderPolicy(policies);
2800 EXPECT_FALSE(audio_handler->IsOutputMuted());
2801 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2802 audio_handler->SetOutputMute(true);
2803 EXPECT_TRUE(audio_handler->IsOutputMuted());
2804 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2805 // Revert the prior state.
2806 audio_handler->SetOutputMute(prior_state);
2807 audio_handler->RemoveAudioObserver(test_observer.get());
2810 // Disabled, see http://crbug.com/315308.
2811 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2812 // Indicate that the session started 2 hours ago and no user activity has
2813 // occurred yet.
2814 g_browser_process->local_state()->SetInt64(
2815 prefs::kSessionStartTime,
2816 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2817 .ToInternalValue());
2820 // Disabled, see http://crbug.com/315308.
2821 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2822 content::MockNotificationObserver observer;
2823 content::NotificationRegistrar registrar;
2824 registrar.Add(&observer,
2825 chrome::NOTIFICATION_APP_TERMINATING,
2826 content::NotificationService::AllSources());
2828 // Set the session length limit to 3 hours. Verify that the session is not
2829 // terminated.
2830 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2831 .Times(0);
2832 PolicyMap policies;
2833 policies.Set(key::kSessionLengthLimit,
2834 POLICY_LEVEL_MANDATORY,
2835 POLICY_SCOPE_USER,
2836 new base::FundamentalValue(kThreeHoursInMs),
2837 NULL);
2838 UpdateProviderPolicy(policies);
2839 base::RunLoop().RunUntilIdle();
2840 Mock::VerifyAndClearExpectations(&observer);
2842 // Decrease the session length limit to 1 hour. Verify that the session is
2843 // terminated immediately.
2844 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2845 policies.Set(key::kSessionLengthLimit,
2846 POLICY_LEVEL_MANDATORY,
2847 POLICY_SCOPE_USER,
2848 new base::FundamentalValue(kOneHourInMs),
2849 NULL);
2850 UpdateProviderPolicy(policies);
2851 base::RunLoop().RunUntilIdle();
2852 Mock::VerifyAndClearExpectations(&observer);
2855 // Disabled, see http://crbug.com/315308.
2856 IN_PROC_BROWSER_TEST_F(PolicyTest,
2857 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2858 // Indicate that the session started 2 hours ago and no user activity has
2859 // occurred yet.
2860 g_browser_process->local_state()->SetInt64(
2861 prefs::kSessionStartTime,
2862 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2863 .ToInternalValue());
2866 // Disabled, see http://crbug.com/315308.
2867 IN_PROC_BROWSER_TEST_F(PolicyTest,
2868 DISABLED_WaitForInitialUserActivityUsatisfied) {
2869 content::MockNotificationObserver observer;
2870 content::NotificationRegistrar registrar;
2871 registrar.Add(&observer,
2872 chrome::NOTIFICATION_APP_TERMINATING,
2873 content::NotificationService::AllSources());
2875 // Require initial user activity.
2876 PolicyMap policies;
2877 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2878 POLICY_SCOPE_USER,
2879 new base::FundamentalValue(true),
2880 NULL);
2881 UpdateProviderPolicy(policies);
2882 base::RunLoop().RunUntilIdle();
2884 // Set the session length limit to 1 hour. Verify that the session is not
2885 // terminated.
2886 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2887 .Times(0);
2888 policies.Set(key::kSessionLengthLimit,
2889 POLICY_LEVEL_MANDATORY,
2890 POLICY_SCOPE_USER,
2891 new base::FundamentalValue(kOneHourInMs),
2892 NULL);
2893 UpdateProviderPolicy(policies);
2894 base::RunLoop().RunUntilIdle();
2895 Mock::VerifyAndClearExpectations(&observer);
2898 // Disabled, see http://crbug.com/315308.
2899 IN_PROC_BROWSER_TEST_F(PolicyTest,
2900 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2901 // Indicate that initial user activity in this session occurred 2 hours ago.
2902 g_browser_process->local_state()->SetInt64(
2903 prefs::kSessionStartTime,
2904 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2905 .ToInternalValue());
2906 g_browser_process->local_state()->SetBoolean(
2907 prefs::kSessionUserActivitySeen,
2908 true);
2911 // Disabled, see http://crbug.com/315308.
2912 IN_PROC_BROWSER_TEST_F(PolicyTest,
2913 DISABLED_WaitForInitialUserActivitySatisfied) {
2914 content::MockNotificationObserver observer;
2915 content::NotificationRegistrar registrar;
2916 registrar.Add(&observer,
2917 chrome::NOTIFICATION_APP_TERMINATING,
2918 content::NotificationService::AllSources());
2920 // Require initial user activity and set the session length limit to 3 hours.
2921 // Verify that the session is not terminated.
2922 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2923 .Times(0);
2924 PolicyMap policies;
2925 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2926 POLICY_SCOPE_USER,
2927 new base::FundamentalValue(true),
2928 NULL);
2929 policies.Set(key::kSessionLengthLimit,
2930 POLICY_LEVEL_MANDATORY,
2931 POLICY_SCOPE_USER,
2932 new base::FundamentalValue(kThreeHoursInMs),
2933 NULL);
2934 UpdateProviderPolicy(policies);
2935 base::RunLoop().RunUntilIdle();
2936 Mock::VerifyAndClearExpectations(&observer);
2938 // Decrease the session length limit to 1 hour. Verify that the session is
2939 // terminated immediately.
2940 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2941 policies.Set(key::kSessionLengthLimit,
2942 POLICY_LEVEL_MANDATORY,
2943 POLICY_SCOPE_USER,
2944 new base::FundamentalValue(kOneHourInMs),
2945 NULL);
2946 UpdateProviderPolicy(policies);
2947 base::RunLoop().RunUntilIdle();
2948 Mock::VerifyAndClearExpectations(&observer);
2951 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2952 // Verifies that the large cursor accessibility feature can be controlled
2953 // through policy.
2954 chromeos::AccessibilityManager* accessibility_manager =
2955 chromeos::AccessibilityManager::Get();
2957 // Manually enable the large cursor.
2958 accessibility_manager->EnableLargeCursor(true);
2959 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2961 // Verify that policy overrides the manual setting.
2962 PolicyMap policies;
2963 policies.Set(key::kLargeCursorEnabled,
2964 POLICY_LEVEL_MANDATORY,
2965 POLICY_SCOPE_USER,
2966 new base::FundamentalValue(false),
2967 NULL);
2968 UpdateProviderPolicy(policies);
2969 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2971 // Verify that the large cursor cannot be enabled manually anymore.
2972 accessibility_manager->EnableLargeCursor(true);
2973 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2976 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2977 // Verifies that the spoken feedback accessibility feature can be controlled
2978 // through policy.
2979 chromeos::AccessibilityManager* accessibility_manager =
2980 chromeos::AccessibilityManager::Get();
2982 // Manually enable spoken feedback.
2983 accessibility_manager->EnableSpokenFeedback(
2984 true, ui::A11Y_NOTIFICATION_NONE);
2985 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2987 // Verify that policy overrides the manual setting.
2988 PolicyMap policies;
2989 policies.Set(key::kSpokenFeedbackEnabled,
2990 POLICY_LEVEL_MANDATORY,
2991 POLICY_SCOPE_USER,
2992 new base::FundamentalValue(false),
2993 NULL);
2994 UpdateProviderPolicy(policies);
2995 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2997 // Verify that spoken feedback cannot be enabled manually anymore.
2998 accessibility_manager->EnableSpokenFeedback(
2999 true, ui::A11Y_NOTIFICATION_NONE);
3000 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
3003 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
3004 // Verifies that the high contrast mode accessibility feature can be
3005 // controlled through policy.
3006 chromeos::AccessibilityManager* accessibility_manager =
3007 chromeos::AccessibilityManager::Get();
3009 // Manually enable high contrast mode.
3010 accessibility_manager->EnableHighContrast(true);
3011 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
3013 // Verify that policy overrides the manual setting.
3014 PolicyMap policies;
3015 policies.Set(key::kHighContrastEnabled,
3016 POLICY_LEVEL_MANDATORY,
3017 POLICY_SCOPE_USER,
3018 new base::FundamentalValue(false),
3019 NULL);
3020 UpdateProviderPolicy(policies);
3021 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
3023 // Verify that high contrast mode cannot be enabled manually anymore.
3024 accessibility_manager->EnableHighContrast(true);
3025 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
3028 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
3029 // Verifies that the screen magnifier can be disabled through policy.
3030 chromeos::MagnificationManager* magnification_manager =
3031 chromeos::MagnificationManager::Get();
3033 // Manually enable the full-screen magnifier.
3034 magnification_manager->SetMagnifierType(ui::MAGNIFIER_FULL);
3035 magnification_manager->SetMagnifierEnabled(true);
3036 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
3037 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3039 // Verify that policy overrides the manual setting.
3040 PolicyMap policies;
3041 policies.Set(key::kScreenMagnifierType,
3042 POLICY_LEVEL_MANDATORY,
3043 POLICY_SCOPE_USER,
3044 new base::FundamentalValue(0),
3045 NULL);
3046 UpdateProviderPolicy(policies);
3047 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
3049 // Verify that the screen magnifier cannot be enabled manually anymore.
3050 magnification_manager->SetMagnifierEnabled(true);
3051 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
3054 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
3055 // Verifies that the full-screen magnifier can be enabled through policy.
3056 chromeos::MagnificationManager* magnification_manager =
3057 chromeos::MagnificationManager::Get();
3059 // Verify that the screen magnifier is initially disabled.
3060 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
3062 // Verify that policy can enable the full-screen magnifier.
3063 PolicyMap policies;
3064 policies.Set(key::kScreenMagnifierType,
3065 POLICY_LEVEL_MANDATORY,
3066 POLICY_SCOPE_USER,
3067 new base::FundamentalValue(ui::MAGNIFIER_FULL),
3068 NULL);
3069 UpdateProviderPolicy(policies);
3070 EXPECT_EQ(ui::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
3071 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3073 // Verify that the screen magnifier cannot be disabled manually anymore.
3074 magnification_manager->SetMagnifierEnabled(false);
3075 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
3078 IN_PROC_BROWSER_TEST_F(PolicyTest, AccessibilityVirtualKeyboardEnabled) {
3079 // Verifies that the on-screen keyboard accessibility feature can be
3080 // controlled through policy.
3081 chromeos::AccessibilityManager* accessibility_manager =
3082 chromeos::AccessibilityManager::Get();
3084 // Manually enable the on-screen keyboard.
3085 accessibility_manager->EnableVirtualKeyboard(true);
3086 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
3088 // Verify that policy overrides the manual setting.
3089 PolicyMap policies;
3090 policies.Set(key::kVirtualKeyboardEnabled,
3091 POLICY_LEVEL_MANDATORY,
3092 POLICY_SCOPE_USER,
3093 new base::FundamentalValue(false),
3094 NULL);
3095 UpdateProviderPolicy(policies);
3096 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3098 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3099 accessibility_manager->EnableVirtualKeyboard(true);
3100 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
3103 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
3104 // Verify keyboard disabled by default.
3105 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3106 // Verify keyboard can be toggled by default.
3107 keyboard::SetTouchKeyboardEnabled(true);
3108 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3109 keyboard::SetTouchKeyboardEnabled(false);
3110 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3112 // Verify enabling the policy takes effect immediately and that that user
3113 // cannot disable the keyboard..
3114 PolicyMap policies;
3115 policies.Set(key::kTouchVirtualKeyboardEnabled,
3116 POLICY_LEVEL_MANDATORY,
3117 POLICY_SCOPE_USER,
3118 new base::FundamentalValue(true),
3119 NULL);
3120 UpdateProviderPolicy(policies);
3121 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3122 keyboard::SetTouchKeyboardEnabled(false);
3123 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3125 // Verify that disabling the policy takes effect immediately and that the user
3126 // cannot enable the keyboard.
3127 policies.Set(key::kTouchVirtualKeyboardEnabled,
3128 POLICY_LEVEL_MANDATORY,
3129 POLICY_SCOPE_USER,
3130 new base::FundamentalValue(false),
3131 NULL);
3132 UpdateProviderPolicy(policies);
3133 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3134 keyboard::SetTouchKeyboardEnabled(true);
3135 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3138 #endif
3140 namespace {
3142 static const char* kRestoredURLs[] = {
3143 "http://aaa.com/empty.html",
3144 "http://bbb.com/empty.html",
3147 bool IsNonSwitchArgument(const base::CommandLine::StringType& s) {
3148 return s.empty() || s[0] != '-';
3151 } // namespace
3153 // Similar to PolicyTest but allows setting policies before the browser is
3154 // created. Each test parameter is a method that sets up the early policies
3155 // and stores the expected startup URLs in |expected_urls_|.
3156 class RestoreOnStartupPolicyTest
3157 : public PolicyTest,
3158 public testing::WithParamInterface<
3159 void (RestoreOnStartupPolicyTest::*)(void)> {
3160 public:
3161 RestoreOnStartupPolicyTest() {}
3162 virtual ~RestoreOnStartupPolicyTest() {}
3164 #if defined(OS_CHROMEOS)
3165 void SetUpCommandLine(base::CommandLine* command_line) override {
3166 // TODO(nkostylev): Investigate if we can remove this switch.
3167 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
3168 PolicyTest::SetUpCommandLine(command_line);
3170 #endif
3172 void SetUpInProcessBrowserTestFixture() override {
3173 PolicyTest::SetUpInProcessBrowserTestFixture();
3174 // Set early policies now, before the browser is created.
3175 (this->*(GetParam()))();
3177 // Remove the non-switch arguments, so that session restore kicks in for
3178 // these tests.
3179 base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
3180 base::CommandLine::StringVector argv = command_line->argv();
3181 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
3182 argv.end());
3183 command_line->InitFromArgv(argv);
3184 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
3185 command_line->argv().begin()));
3188 void SetUpOnMainThread() override {
3189 BrowserThread::PostTask(
3190 BrowserThread::IO,
3191 FROM_HERE,
3192 base::Bind(
3193 RedirectHostsToTestData, kRestoredURLs, arraysize(kRestoredURLs)));
3196 void HomepageIsNotNTP() {
3197 // Verifies that policy can set the startup pages to the homepage, when
3198 // the homepage is not the NTP.
3199 PolicyMap policies;
3200 policies.Set(
3201 key::kRestoreOnStartup,
3202 POLICY_LEVEL_MANDATORY,
3203 POLICY_SCOPE_USER,
3204 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3205 NULL);
3206 policies.Set(key::kHomepageIsNewTabPage,
3207 POLICY_LEVEL_MANDATORY,
3208 POLICY_SCOPE_USER,
3209 new base::FundamentalValue(false),
3210 NULL);
3211 policies.Set(key::kHomepageLocation,
3212 POLICY_LEVEL_MANDATORY,
3213 POLICY_SCOPE_USER,
3214 new base::StringValue(kRestoredURLs[1]),
3215 NULL);
3216 provider_.UpdateChromePolicy(policies);
3218 expected_urls_.push_back(GURL(kRestoredURLs[1]));
3221 void HomepageIsNTP() {
3222 // Verifies that policy can set the startup pages to the homepage, when
3223 // the homepage is the NTP.
3224 PolicyMap policies;
3225 policies.Set(
3226 key::kRestoreOnStartup,
3227 POLICY_LEVEL_MANDATORY,
3228 POLICY_SCOPE_USER,
3229 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage),
3230 NULL);
3231 policies.Set(key::kHomepageIsNewTabPage,
3232 POLICY_LEVEL_MANDATORY,
3233 POLICY_SCOPE_USER,
3234 new base::FundamentalValue(true),
3235 NULL);
3236 provider_.UpdateChromePolicy(policies);
3238 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3241 void ListOfURLs() {
3242 // Verifies that policy can set the startup pages to a list of URLs.
3243 base::ListValue urls;
3244 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
3245 urls.Append(new base::StringValue(kRestoredURLs[i]));
3246 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3248 PolicyMap policies;
3249 policies.Set(key::kRestoreOnStartup,
3250 POLICY_LEVEL_MANDATORY,
3251 POLICY_SCOPE_USER,
3252 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs),
3253 NULL);
3254 policies.Set(
3255 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3256 urls.DeepCopy(), NULL);
3257 provider_.UpdateChromePolicy(policies);
3260 void NTP() {
3261 // Verifies that policy can set the startup page to the NTP.
3262 PolicyMap policies;
3263 policies.Set(
3264 key::kRestoreOnStartup,
3265 POLICY_LEVEL_MANDATORY,
3266 POLICY_SCOPE_USER,
3267 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab),
3268 NULL);
3269 provider_.UpdateChromePolicy(policies);
3270 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
3273 void Last() {
3274 // Verifies that policy can set the startup pages to the last session.
3275 PolicyMap policies;
3276 policies.Set(key::kRestoreOnStartup,
3277 POLICY_LEVEL_MANDATORY,
3278 POLICY_SCOPE_USER,
3279 new base::FundamentalValue(SessionStartupPref::kPrefValueLast),
3280 NULL);
3281 provider_.UpdateChromePolicy(policies);
3282 // This should restore the tabs opened at PRE_RunTest below.
3283 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
3284 expected_urls_.push_back(GURL(kRestoredURLs[i]));
3287 std::vector<GURL> expected_urls_;
3290 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
3291 // Open some tabs to verify if they are restored after the browser restarts.
3292 // Most policy settings override this, except kPrefValueLast which enforces
3293 // a restore.
3294 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
3295 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
3296 content::WindowedNotificationObserver observer(
3297 content::NOTIFICATION_LOAD_STOP,
3298 content::NotificationService::AllSources());
3299 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
3300 ui::PAGE_TRANSITION_LINK);
3301 observer.Wait();
3305 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
3306 #if defined(OS_WIN) && defined(USE_ASH)
3307 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3308 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3309 switches::kAshBrowserTests))
3310 return;
3311 #endif
3313 TabStripModel* model = browser()->tab_strip_model();
3314 int size = static_cast<int>(expected_urls_.size());
3315 EXPECT_EQ(size, model->count());
3316 for (int i = 0; i < size && i < model->count(); ++i) {
3317 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
3321 INSTANTIATE_TEST_CASE_P(
3322 RestoreOnStartupPolicyTestInstance,
3323 RestoreOnStartupPolicyTest,
3324 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
3325 &RestoreOnStartupPolicyTest::HomepageIsNTP,
3326 &RestoreOnStartupPolicyTest::ListOfURLs,
3327 &RestoreOnStartupPolicyTest::NTP,
3328 &RestoreOnStartupPolicyTest::Last));
3330 // Similar to PolicyTest but sets a couple of policies before the browser is
3331 // started.
3332 class PolicyStatisticsCollectorTest : public PolicyTest {
3333 public:
3334 PolicyStatisticsCollectorTest() {}
3335 ~PolicyStatisticsCollectorTest() override {}
3337 void SetUpInProcessBrowserTestFixture() override {
3338 PolicyTest::SetUpInProcessBrowserTestFixture();
3339 PolicyMap policies;
3340 policies.Set(key::kShowHomeButton,
3341 POLICY_LEVEL_MANDATORY,
3342 POLICY_SCOPE_USER,
3343 new base::FundamentalValue(true),
3344 NULL);
3345 policies.Set(key::kBookmarkBarEnabled,
3346 POLICY_LEVEL_MANDATORY,
3347 POLICY_SCOPE_USER,
3348 new base::FundamentalValue(false),
3349 NULL);
3350 policies.Set(key::kHomepageLocation,
3351 POLICY_LEVEL_MANDATORY,
3352 POLICY_SCOPE_USER,
3353 new base::StringValue("http://chromium.org"),
3354 NULL);
3355 provider_.UpdateChromePolicy(policies);
3359 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
3360 // Verifies that policy usage histograms are collected at startup.
3362 // BrowserPolicyConnector::Init() has already been called. Make sure the
3363 // CompleteInitialization() task has executed as well.
3364 content::RunAllPendingInMessageLoop();
3366 GURL kAboutHistograms = GURL(std::string(url::kAboutScheme) +
3367 std::string(url::kStandardSchemeSeparator) +
3368 std::string(content::kChromeUIHistogramHost));
3369 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
3370 content::WebContents* contents =
3371 browser()->tab_strip_model()->GetActiveWebContents();
3372 std::string text;
3373 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3374 contents,
3375 "var nodes = document.querySelectorAll('body > pre');"
3376 "var result = '';"
3377 "for (var i = 0; i < nodes.length; ++i) {"
3378 " var text = nodes[i].innerHTML;"
3379 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3380 " result = text;"
3381 " break;"
3382 " }"
3384 "domAutomationController.send(result);",
3385 &text));
3386 ASSERT_FALSE(text.empty());
3387 const std::string kExpectedLabel =
3388 "Histogram: Enterprise.Policies recorded 3 samples";
3389 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
3390 // HomepageLocation has policy ID 1.
3391 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
3392 // ShowHomeButton has policy ID 35.
3393 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
3394 // BookmarkBarEnabled has policy ID 82.
3395 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
3398 class MediaStreamDevicesControllerBrowserTest
3399 : public PolicyTest,
3400 public testing::WithParamInterface<bool> {
3401 public:
3402 MediaStreamDevicesControllerBrowserTest()
3403 : request_url_allowed_via_whitelist_(false),
3404 request_url_("http://www.example.com/foo") {
3405 policy_value_ = GetParam();
3407 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3409 // Configure a given policy map. The |policy_name| is the name of either the
3410 // audio or video capture allow policy and must never be NULL.
3411 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3412 // policy is set. If non-NULL, the whitelist policy is set to contain either
3413 // the |allow_rule| (if non-NULL) or an "allow all" wildcard.
3414 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
3415 const char* whitelist_policy,
3416 const char* allow_rule) {
3417 policies->Set(policy_name,
3418 POLICY_LEVEL_MANDATORY,
3419 POLICY_SCOPE_USER,
3420 new base::FundamentalValue(policy_value_),
3421 NULL);
3423 if (whitelist_policy) {
3424 // Add an entry to the whitelist that allows the specified URL regardless
3425 // of the setting of kAudioCapturedAllowed.
3426 base::ListValue* list = new base::ListValue();
3427 if (allow_rule) {
3428 list->AppendString(allow_rule);
3429 request_url_allowed_via_whitelist_ = true;
3430 } else {
3431 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
3432 // We should ignore all wildcard entries in the whitelist, so even
3433 // though we've added an entry, it should be ignored and our expectation
3434 // is that the request has not been allowed via the whitelist.
3435 request_url_allowed_via_whitelist_ = false;
3437 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
3438 POLICY_SCOPE_USER, list, NULL);
3442 void Accept(const content::MediaStreamDevices& devices,
3443 content::MediaStreamRequestResult result,
3444 scoped_ptr<content::MediaStreamUI> ui) {
3445 if (policy_value_ || request_url_allowed_via_whitelist_) {
3446 ASSERT_EQ(1U, devices.size());
3447 ASSERT_EQ("fake_dev", devices[0].id);
3448 } else {
3449 ASSERT_EQ(0U, devices.size());
3453 void FinishAudioTest() {
3454 content::MediaStreamRequest request(0, 0, 0,
3455 request_url_.GetOrigin(), false,
3456 content::MEDIA_DEVICE_ACCESS,
3457 std::string(), std::string(),
3458 content::MEDIA_DEVICE_AUDIO_CAPTURE,
3459 content::MEDIA_NO_SERVICE);
3460 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3461 // and microphone permissions at the same time.
3462 MediaStreamDevicesController controller(
3463 browser()->tab_strip_model()->GetActiveWebContents(), request,
3464 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3465 if (controller.IsAskingForAudio())
3466 controller.PermissionGranted();
3468 base::MessageLoop::current()->QuitWhenIdle();
3471 void FinishVideoTest() {
3472 content::MediaStreamRequest request(0, 0, 0,
3473 request_url_.GetOrigin(), false,
3474 content::MEDIA_DEVICE_ACCESS,
3475 std::string(),
3476 std::string(),
3477 content::MEDIA_NO_SERVICE,
3478 content::MEDIA_DEVICE_VIDEO_CAPTURE);
3479 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3480 // and microphone permissions at the same time.
3481 MediaStreamDevicesController controller(
3482 browser()->tab_strip_model()->GetActiveWebContents(), request,
3483 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
3484 if (controller.IsAskingForVideo())
3485 controller.PermissionGranted();
3487 base::MessageLoop::current()->QuitWhenIdle();
3490 bool policy_value_;
3491 bool request_url_allowed_via_whitelist_;
3492 GURL request_url_;
3493 static const char kExampleRequestPattern[];
3496 // static
3497 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
3498 "http://[*.]example.com/";
3500 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3501 AudioCaptureAllowed) {
3502 content::MediaStreamDevices audio_devices;
3503 content::MediaStreamDevice fake_audio_device(
3504 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3505 audio_devices.push_back(fake_audio_device);
3507 PolicyMap policies;
3508 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
3509 UpdateProviderPolicy(policies);
3511 content::BrowserThread::PostTaskAndReply(
3512 content::BrowserThread::IO, FROM_HERE,
3513 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3514 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3515 audio_devices),
3516 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3517 this));
3519 base::MessageLoop::current()->Run();
3522 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3523 AudioCaptureAllowedUrls) {
3524 content::MediaStreamDevices audio_devices;
3525 content::MediaStreamDevice fake_audio_device(
3526 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
3527 audio_devices.push_back(fake_audio_device);
3529 const char* allow_pattern[] = {
3530 kExampleRequestPattern,
3531 // This will set an allow-all policy whitelist. Since we do not allow
3532 // setting an allow-all entry in the whitelist, this entry should be ignored
3533 // and therefore the request should be denied.
3534 NULL,
3537 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3538 PolicyMap policies;
3539 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
3540 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
3541 UpdateProviderPolicy(policies);
3543 content::BrowserThread::PostTaskAndReply(
3544 content::BrowserThread::IO, FROM_HERE,
3545 base::Bind(
3546 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
3547 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3548 audio_devices),
3549 base::Bind(
3550 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
3551 this));
3553 base::MessageLoop::current()->Run();
3557 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3558 VideoCaptureAllowed) {
3559 content::MediaStreamDevices video_devices;
3560 content::MediaStreamDevice fake_video_device(
3561 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3562 video_devices.push_back(fake_video_device);
3564 PolicyMap policies;
3565 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
3566 UpdateProviderPolicy(policies);
3568 content::BrowserThread::PostTaskAndReply(
3569 content::BrowserThread::IO, FROM_HERE,
3570 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3571 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3572 video_devices),
3573 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3574 this));
3576 base::MessageLoop::current()->Run();
3579 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
3580 VideoCaptureAllowedUrls) {
3581 content::MediaStreamDevices video_devices;
3582 content::MediaStreamDevice fake_video_device(
3583 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
3584 video_devices.push_back(fake_video_device);
3586 const char* allow_pattern[] = {
3587 kExampleRequestPattern,
3588 // This will set an allow-all policy whitelist. Since we do not allow
3589 // setting an allow-all entry in the whitelist, this entry should be ignored
3590 // and therefore the request should be denied.
3591 NULL,
3594 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
3595 PolicyMap policies;
3596 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
3597 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
3598 UpdateProviderPolicy(policies);
3600 content::BrowserThread::PostTaskAndReply(
3601 content::BrowserThread::IO, FROM_HERE,
3602 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
3603 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3604 video_devices),
3605 base::Bind(
3606 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
3607 this));
3609 base::MessageLoop::current()->Run();
3613 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
3614 MediaStreamDevicesControllerBrowserTest,
3615 testing::Bool());
3617 // Test that when extended reporting opt-in is disabled by policy, the
3618 // opt-in checkbox does not appear on SSL blocking pages.
3619 IN_PROC_BROWSER_TEST_F(PolicyTest, SafeBrowsingExtendedReportingOptInAllowed) {
3620 net::SpawnedTestServer https_server_expired(
3621 net::SpawnedTestServer::TYPE_HTTPS,
3622 net::SpawnedTestServer::SSLOptions(
3623 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED),
3624 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3625 ASSERT_TRUE(https_server_expired.Start());
3627 // Set the enterprise policy to disallow opt-in.
3628 const PrefService* const prefs = browser()->profile()->GetPrefs();
3629 EXPECT_TRUE(
3630 prefs->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed));
3631 PolicyMap policies;
3632 policies.Set(key::kSafeBrowsingExtendedReportingOptInAllowed,
3633 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
3634 new base::FundamentalValue(false), NULL);
3635 UpdateProviderPolicy(policies);
3636 EXPECT_FALSE(
3637 prefs->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed));
3639 // Navigate to an SSL error page.
3640 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
3642 const content::InterstitialPage* const interstitial =
3643 content::InterstitialPage::GetInterstitialPage(
3644 browser()->tab_strip_model()->GetActiveWebContents());
3645 ASSERT_TRUE(interstitial);
3646 ASSERT_TRUE(content::WaitForRenderFrameReady(interstitial->GetMainFrame()));
3647 content::RenderViewHost* const rvh =
3648 interstitial->GetMainFrame()->GetRenderViewHost();
3649 ASSERT_TRUE(rvh);
3651 // Check that the checkbox is not visible.
3652 int result = 0;
3653 const std::string command = base::StringPrintf(
3654 "var node = document.getElementById('extended-reporting-opt-in');"
3655 "if (node) {"
3656 " window.domAutomationController.send(node.offsetWidth > 0 || "
3657 " node.offsetHeight > 0 ? %d : %d);"
3658 "} else {"
3659 // The node should be present but not visible, so trigger an error
3660 // by sending false if it's not present.
3661 " window.domAutomationController.send(%d);"
3662 "}",
3663 SecurityInterstitialPage::CMD_TEXT_FOUND,
3664 SecurityInterstitialPage::CMD_TEXT_NOT_FOUND,
3665 SecurityInterstitialPage::CMD_ERROR);
3666 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(rvh, command, &result));
3667 EXPECT_EQ(SecurityInterstitialPage::CMD_TEXT_NOT_FOUND, result);
3670 // Test that when SSL error overriding is allowed by policy (default), the
3671 // proceed link appears on SSL blocking pages.
3672 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingAllowed) {
3673 net::SpawnedTestServer https_server_expired(
3674 net::SpawnedTestServer::TYPE_HTTPS,
3675 net::SpawnedTestServer::SSLOptions(
3676 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED),
3677 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3678 ASSERT_TRUE(https_server_expired.Start());
3680 const PrefService* const prefs = browser()->profile()->GetPrefs();
3682 // Policy should allow overriding by default.
3683 EXPECT_TRUE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
3685 // Policy allows overriding - navigate to an SSL error page and expect the
3686 // proceed link.
3687 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
3689 const content::InterstitialPage* const interstitial =
3690 content::InterstitialPage::GetInterstitialPage(
3691 browser()->tab_strip_model()->GetActiveWebContents());
3692 ASSERT_TRUE(interstitial);
3693 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial->GetMainFrame()));
3695 // The interstitial should display the proceed link.
3696 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3697 interstitial, "proceed-link"));
3700 // Test that when SSL error overriding is disallowed by policy, the
3701 // proceed link does not appear on SSL blocking pages and users should not
3702 // be able to proceed.
3703 IN_PROC_BROWSER_TEST_F(PolicyTest, SSLErrorOverridingDisallowed) {
3704 net::SpawnedTestServer https_server_expired(
3705 net::SpawnedTestServer::TYPE_HTTPS,
3706 net::SpawnedTestServer::SSLOptions(
3707 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED),
3708 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3709 ASSERT_TRUE(https_server_expired.Start());
3711 const PrefService* const prefs = browser()->profile()->GetPrefs();
3712 EXPECT_TRUE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
3714 // Disallowing the proceed link by setting the policy to |false|.
3715 PolicyMap policies;
3716 policies.Set(key::kSSLErrorOverrideAllowed, POLICY_LEVEL_MANDATORY,
3717 POLICY_SCOPE_USER, new base::FundamentalValue(false), NULL);
3718 UpdateProviderPolicy(policies);
3720 // Policy should not allow overriding anymore.
3721 EXPECT_FALSE(prefs->GetBoolean(prefs::kSSLErrorOverrideAllowed));
3723 // Policy disallows overriding - navigate to an SSL error page and expect no
3724 // proceed link.
3725 ui_test_utils::NavigateToURL(browser(), https_server_expired.GetURL("/"));
3726 const content::InterstitialPage* const interstitial =
3727 content::InterstitialPage::GetInterstitialPage(
3728 browser()->tab_strip_model()->GetActiveWebContents());
3729 ASSERT_TRUE(interstitial);
3730 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial->GetMainFrame()));
3732 // The interstitial should not display the proceed link.
3733 EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3734 interstitial, "proceed-link"));
3736 // The interstitial should not proceed, even if the command is sent in
3737 // some other way (e.g., via the keyboard shortcut).
3738 content::InterstitialPageDelegate* interstitial_delegate =
3739 content::InterstitialPage::GetInterstitialPage(
3740 browser()->tab_strip_model()->GetActiveWebContents())
3741 ->GetDelegateForTesting();
3742 ASSERT_EQ(SSLBlockingPage::kTypeForTesting,
3743 interstitial_delegate->GetTypeForTesting());
3744 SSLBlockingPage* ssl_delegate =
3745 static_cast<SSLBlockingPage*>(interstitial_delegate);
3746 ssl_delegate->CommandReceived(
3747 base::IntToString(SecurityInterstitialPage::CMD_PROCEED));
3748 EXPECT_TRUE(interstitial);
3749 EXPECT_TRUE(browser()
3750 ->tab_strip_model()
3751 ->GetActiveWebContents()
3752 ->ShowingInterstitialPage());
3755 #if !defined(OS_CHROMEOS)
3756 // Similar to PolicyTest but sets the proper policy before the browser is
3757 // started.
3758 class PolicyVariationsServiceTest : public PolicyTest {
3759 public:
3760 void SetUpInProcessBrowserTestFixture() override {
3761 PolicyTest::SetUpInProcessBrowserTestFixture();
3762 PolicyMap policies;
3763 policies.Set(key::kVariationsRestrictParameter,
3764 POLICY_LEVEL_MANDATORY,
3765 POLICY_SCOPE_USER,
3766 new base::StringValue("restricted"),
3767 NULL);
3768 provider_.UpdateChromePolicy(policies);
3772 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
3773 const std::string default_variations_url =
3774 chrome_variations::VariationsService::
3775 GetDefaultVariationsServerURLForTesting();
3777 const GURL url =
3778 chrome_variations::VariationsService::GetVariationsServerURL(
3779 g_browser_process->local_state(), std::string());
3780 EXPECT_TRUE(base::StartsWith(url.spec(), default_variations_url,
3781 base::CompareCase::SENSITIVE));
3782 std::string value;
3783 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
3784 EXPECT_EQ("restricted", value);
3787 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
3788 base::ListValue blacklist;
3789 blacklist.Append(new base::StringValue("host.name"));
3790 PolicyMap policies;
3791 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3792 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3793 UpdateProviderPolicy(policies);
3795 PrefService* prefs = browser()->profile()->GetPrefs();
3796 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3797 prefs, "host.name"));
3798 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3799 prefs, "other.host.name"));
3802 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
3803 base::ListValue blacklist;
3804 blacklist.Append(new base::StringValue("*"));
3805 PolicyMap policies;
3806 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3807 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3808 UpdateProviderPolicy(policies);
3810 PrefService* prefs = browser()->profile()->GetPrefs();
3811 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3812 prefs, "host.name"));
3813 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3814 prefs, "other.host.name"));
3817 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
3818 base::ListValue blacklist;
3819 blacklist.Append(new base::StringValue("*"));
3820 base::ListValue whitelist;
3821 whitelist.Append(new base::StringValue("host.name"));
3822 PolicyMap policies;
3823 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
3824 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
3825 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
3826 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
3827 UpdateProviderPolicy(policies);
3829 PrefService* prefs = browser()->profile()->GetPrefs();
3830 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3831 prefs, "host.name"));
3832 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3833 prefs, "other.host.name"));
3836 #endif // !defined(CHROME_OS)
3839 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3840 // Sets the hardware acceleration mode policy before the browser is started.
3841 class HardwareAccelerationModePolicyTest : public PolicyTest {
3842 public:
3843 HardwareAccelerationModePolicyTest() {}
3845 void SetUpInProcessBrowserTestFixture() override {
3846 PolicyTest::SetUpInProcessBrowserTestFixture();
3847 PolicyMap policies;
3848 policies.Set(key::kHardwareAccelerationModeEnabled,
3849 POLICY_LEVEL_MANDATORY,
3850 POLICY_SCOPE_USER,
3851 new base::FundamentalValue(false),
3852 NULL);
3853 provider_.UpdateChromePolicy(policies);
3857 IN_PROC_BROWSER_TEST_F(HardwareAccelerationModePolicyTest,
3858 HardwareAccelerationDisabled) {
3859 // Verifies that hardware acceleration can be disabled with policy.
3860 EXPECT_FALSE(
3861 content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr));
3863 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3865 } // namespace policy