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.
9 #include "ash/display/display_manager.h"
10 #include "base/bind.h"
11 #include "base/bind_helpers.h"
12 #include "base/callback.h"
13 #include "base/command_line.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/file_util.h"
17 #include "base/files/scoped_temp_dir.h"
18 #include "base/memory/ref_counted.h"
19 #include "base/memory/scoped_ptr.h"
20 #include "base/path_service.h"
21 #include "base/prefs/pref_service.h"
22 #include "base/run_loop.h"
23 #include "base/strings/string16.h"
24 #include "base/strings/string_number_conversions.h"
25 #include "base/strings/string_util.h"
26 #include "base/strings/stringprintf.h"
27 #include "base/strings/utf_string_conversions.h"
28 #include "base/test/test_file_util.h"
29 #include "base/threading/sequenced_worker_pool.h"
30 #include "base/time/time.h"
31 #include "base/values.h"
32 #include "chrome/app/chrome_command_ids.h"
33 #include "chrome/browser/background/background_contents_service.h"
34 #include "chrome/browser/browser_process.h"
35 #include "chrome/browser/chrome_notification_types.h"
36 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
37 #include "chrome/browser/devtools/devtools_window_testing.h"
38 #include "chrome/browser/download/download_prefs.h"
39 #include "chrome/browser/extensions/api/messaging/message_service.h"
40 #include "chrome/browser/extensions/crx_installer.h"
41 #include "chrome/browser/extensions/extension_management_constants.h"
42 #include "chrome/browser/extensions/extension_management_test_util.h"
43 #include "chrome/browser/extensions/extension_service.h"
44 #include "chrome/browser/extensions/shared_module_service.h"
45 #include "chrome/browser/extensions/unpacked_installer.h"
46 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
47 #include "chrome/browser/extensions/updater/extension_updater.h"
48 #include "chrome/browser/infobars/infobar_service.h"
49 #include "chrome/browser/interstitials/security_interstitial_page.h"
50 #include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
51 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
52 #include "chrome/browser/media/media_stream_devices_controller.h"
53 #include "chrome/browser/metrics/variations/chrome_variations_service_client.h"
54 #include "chrome/browser/net/prediction_options.h"
55 #include "chrome/browser/net/url_request_mock_util.h"
56 #include "chrome/browser/plugins/plugin_prefs.h"
57 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
58 #include "chrome/browser/policy/profile_policy_connector.h"
59 #include "chrome/browser/policy/profile_policy_connector_factory.h"
60 #include "chrome/browser/prefs/session_startup_pref.h"
61 #include "chrome/browser/profiles/profile.h"
62 #include "chrome/browser/search/instant_service.h"
63 #include "chrome/browser/search/instant_service_factory.h"
64 #include "chrome/browser/search/search.h"
65 #include "chrome/browser/search_engines/template_url_service_factory.h"
66 #include "chrome/browser/ssl/ssl_blocking_page.h"
67 #include "chrome/browser/translate/chrome_translate_client.h"
68 #include "chrome/browser/translate/cld_data_harness.h"
69 #include "chrome/browser/translate/cld_data_harness_factory.h"
70 #include "chrome/browser/translate/translate_service.h"
71 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
72 #include "chrome/browser/ui/browser.h"
73 #include "chrome/browser/ui/browser_commands.h"
74 #include "chrome/browser/ui/browser_list.h"
75 #include "chrome/browser/ui/browser_tabstrip.h"
76 #include "chrome/browser/ui/browser_window.h"
77 #include "chrome/browser/ui/host_desktop.h"
78 #include "chrome/browser/ui/location_bar/location_bar.h"
79 #include "chrome/browser/ui/tabs/tab_strip_model.h"
80 #include "chrome/common/chrome_paths.h"
81 #include "chrome/common/chrome_switches.h"
82 #include "chrome/common/extensions/extension_constants.h"
83 #include "chrome/common/extensions/features/feature_channel.h"
84 #include "chrome/common/pref_names.h"
85 #include "chrome/common/url_constants.h"
86 #include "chrome/grit/generated_resources.h"
87 #include "chrome/test/base/in_process_browser_test.h"
88 #include "chrome/test/base/test_switches.h"
89 #include "chrome/test/base/ui_test_utils.h"
90 #include "components/content_settings/core/common/content_settings.h"
91 #include "components/content_settings/core/common/content_settings_pattern.h"
92 #include "components/infobars/core/infobar.h"
93 #include "components/omnibox/browser/autocomplete_controller.h"
94 #include "components/omnibox/browser/omnibox_edit_model.h"
95 #include "components/omnibox/browser/omnibox_view.h"
96 #include "components/policy/core/browser/browser_policy_connector.h"
97 #include "components/policy/core/common/external_data_fetcher.h"
98 #include "components/policy/core/common/mock_configuration_policy_provider.h"
99 #include "components/policy/core/common/policy_map.h"
100 #include "components/policy/core/common/policy_pref_names.h"
101 #include "components/policy/core/common/policy_service.h"
102 #include "components/policy/core/common/policy_service_impl.h"
103 #include "components/policy/core/common/policy_types.h"
104 #include "components/search/search.h"
105 #include "components/search_engines/template_url.h"
106 #include "components/search_engines/template_url_service.h"
107 #include "components/translate/core/browser/language_state.h"
108 #include "components/translate/core/browser/translate_infobar_delegate.h"
109 #include "components/variations/service/variations_service.h"
110 #include "components/version_info/version_info.h"
111 #include "content/public/browser/browser_child_process_host_iterator.h"
112 #include "content/public/browser/browser_context.h"
113 #include "content/public/browser/browser_thread.h"
114 #include "content/public/browser/child_process_data.h"
115 #include "content/public/browser/download_item.h"
116 #include "content/public/browser/download_manager.h"
117 #include "content/public/browser/gpu_data_manager.h"
118 #include "content/public/browser/interstitial_page.h"
119 #include "content/public/browser/notification_details.h"
120 #include "content/public/browser/notification_observer.h"
121 #include "content/public/browser/notification_registrar.h"
122 #include "content/public/browser/notification_service.h"
123 #include "content/public/browser/notification_source.h"
124 #include "content/public/browser/notification_types.h"
125 #include "content/public/browser/plugin_service.h"
126 #include "content/public/browser/render_frame_host.h"
127 #include "content/public/browser/render_process_host.h"
128 #include "content/public/browser/render_view_host.h"
129 #include "content/public/browser/web_contents.h"
130 #include "content/public/common/content_constants.h"
131 #include "content/public/common/content_paths.h"
132 #include "content/public/common/process_type.h"
133 #include "content/public/common/result_codes.h"
134 #include "content/public/common/url_constants.h"
135 #include "content/public/common/webplugininfo.h"
136 #include "content/public/test/browser_test_utils.h"
137 #include "content/public/test/download_test_observer.h"
138 #include "content/public/test/mock_notification_observer.h"
139 #include "content/public/test/test_navigation_observer.h"
140 #include "content/public/test/test_utils.h"
141 #include "extensions/browser/extension_dialog_auto_confirm.h"
142 #include "extensions/browser/extension_host.h"
143 #include "extensions/browser/extension_prefs.h"
144 #include "extensions/browser/extension_registry.h"
145 #include "extensions/browser/extension_system.h"
146 #include "extensions/browser/process_manager.h"
147 #include "extensions/browser/test_extension_registry_observer.h"
148 #include "extensions/browser/uninstall_reason.h"
149 #include "extensions/common/constants.h"
150 #include "extensions/common/extension.h"
151 #include "extensions/common/extension_set.h"
152 #include "extensions/common/manifest_handlers/shared_module_info.h"
153 #include "net/base/net_errors.h"
154 #include "net/base/net_util.h"
155 #include "net/base/url_util.h"
156 #include "net/http/http_stream_factory.h"
157 #include "net/ssl/ssl_config.h"
158 #include "net/ssl/ssl_config_service.h"
159 #include "net/test/spawned_test_server/spawned_test_server.h"
160 #include "net/test/url_request/url_request_failed_job.h"
161 #include "net/test/url_request/url_request_mock_http_job.h"
162 #include "net/url_request/url_request.h"
163 #include "net/url_request/url_request_filter.h"
164 #include "net/url_request/url_request_interceptor.h"
165 #include "policy/policy_constants.h"
166 #include "testing/gmock/include/gmock/gmock.h"
167 #include "testing/gtest/include/gtest/gtest.h"
168 #include "third_party/WebKit/public/web/WebInputEvent.h"
169 #include "ui/base/l10n/l10n_util.h"
170 #include "ui/base/page_transition_types.h"
171 #include "ui/base/resource/resource_bundle.h"
172 #include "url/gurl.h"
174 #if defined(OS_CHROMEOS)
175 #include "ash/accelerators/accelerator_controller.h"
176 #include "ash/accelerators/accelerator_table.h"
177 #include "ash/shell.h"
178 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
179 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
180 #include "chrome/browser/profiles/profile_manager.h"
181 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
182 #include "chromeos/audio/cras_audio_handler.h"
183 #include "ui/chromeos/accessibility_types.h"
184 #include "ui/keyboard/keyboard_util.h"
185 #include "ui/snapshot/screenshot_grabber.h"
188 #if !defined(OS_MACOSX)
189 #include "base/basictypes.h"
190 #include "base/compiler_specific.h"
191 #include "chrome/browser/ui/extensions/app_launch_params.h"
192 #include "chrome/browser/ui/extensions/application_launch.h"
193 #include "extensions/browser/app_window/app_window.h"
194 #include "extensions/browser/app_window/app_window_registry.h"
195 #include "extensions/browser/app_window/native_app_window.h"
196 #include "ui/base/window_open_disposition.h"
199 using content::BrowserThread
;
200 using net::URLRequestMockHTTPJob
;
202 using testing::Return
;
209 #if defined(OS_CHROMEOS)
210 const int kOneHourInMs
= 60 * 60 * 1000;
211 const int kThreeHoursInMs
= 180 * 60 * 1000;
214 const char kURL
[] = "http://example.com";
215 const char kCookieValue
[] = "converted=true";
216 // Assigned to Philip J. Fry to fix eventually.
217 const char kCookieOptions
[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
219 const base::FilePath::CharType kTestExtensionsDir
[] =
220 FILE_PATH_LITERAL("extensions");
221 const base::FilePath::CharType kGoodCrxName
[] = FILE_PATH_LITERAL("good.crx");
222 const base::FilePath::CharType kAdBlockCrxName
[] =
223 FILE_PATH_LITERAL("adblock.crx");
224 const base::FilePath::CharType kHostedAppCrxName
[] =
225 FILE_PATH_LITERAL("hosted_app.crx");
227 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
228 const char kAdBlockCrxId
[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
229 const char kHostedAppCrxId
[] = "kbmnembihfiondgfjekmnmcbddelicoi";
231 const base::FilePath::CharType kGood2CrxManifestName
[] =
232 FILE_PATH_LITERAL("good2_update_manifest.xml");
233 const base::FilePath::CharType kGoodV1CrxManifestName
[] =
234 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
235 const base::FilePath::CharType kGoodV1CrxName
[] =
236 FILE_PATH_LITERAL("good_v1.crx");
237 const base::FilePath::CharType kGoodUnpackedExt
[] =
238 FILE_PATH_LITERAL("good_unpacked");
239 const base::FilePath::CharType kAppUnpackedExt
[] =
240 FILE_PATH_LITERAL("app");
242 #if !defined(OS_MACOSX)
243 const base::FilePath::CharType kUnpackedFullscreenAppName
[] =
244 FILE_PATH_LITERAL("fullscreen_app");
245 #endif // !defined(OS_MACOSX)
247 // Filters requests to the hosts in |urls| and redirects them to the test data
248 // dir through URLRequestMockHTTPJobs.
249 void RedirectHostsToTestData(const char* const urls
[], size_t size
) {
250 // Map the given hosts to the test data dir.
251 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
252 base::FilePath base_path
;
253 PathService::Get(chrome::DIR_TEST_DATA
, &base_path
);
254 for (size_t i
= 0; i
< size
; ++i
) {
255 const GURL
url(urls
[i
]);
256 EXPECT_TRUE(url
.is_valid());
257 filter
->AddUrlInterceptor(url
,
258 URLRequestMockHTTPJob::CreateInterceptor(
259 base_path
, BrowserThread::GetBlockingPool()));
263 // Remove filters for requests to the hosts in |urls|.
264 void UndoRedirectHostsToTestData(const char* const urls
[], size_t size
) {
265 // Map the given hosts to the test data dir.
266 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
267 for (size_t i
= 0; i
< size
; ++i
) {
268 const GURL
url(urls
[i
]);
269 EXPECT_TRUE(url
.is_valid());
270 filter
->RemoveUrlHandler(url
);
274 // Fails requests using ERR_CONNECTION_RESET.
275 class FailedJobInterceptor
: public net::URLRequestInterceptor
{
277 FailedJobInterceptor() {}
278 ~FailedJobInterceptor() override
{}
280 // URLRequestInterceptor implementation:
281 net::URLRequestJob
* MaybeInterceptRequest(
282 net::URLRequest
* request
,
283 net::NetworkDelegate
* network_delegate
) const override
{
284 return new net::URLRequestFailedJob(request
, network_delegate
,
285 net::ERR_CONNECTION_RESET
);
289 DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor
);
292 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
293 class MakeRequestFail
{
295 // Sets up the filter on IO thread such that requests to |host| fail.
296 explicit MakeRequestFail(const std::string
& host
) : host_(host
) {
297 BrowserThread::PostTaskAndReply(
298 BrowserThread::IO
, FROM_HERE
,
299 base::Bind(MakeRequestFailOnIO
, host_
),
300 base::MessageLoop::QuitClosure());
301 content::RunMessageLoop();
304 BrowserThread::PostTaskAndReply(
305 BrowserThread::IO
, FROM_HERE
,
306 base::Bind(UndoMakeRequestFailOnIO
, host_
),
307 base::MessageLoop::QuitClosure());
308 content::RunMessageLoop();
312 // Filters requests to the |host| such that they fail. Run on IO thread.
313 static void MakeRequestFailOnIO(const std::string
& host
) {
314 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
315 filter
->AddHostnameInterceptor(
317 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
318 filter
->AddHostnameInterceptor(
320 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
323 // Remove filters for requests to the |host|. Run on IO thread.
324 static void UndoMakeRequestFailOnIO(const std::string
& host
) {
325 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
326 filter
->RemoveHostnameHandler("http", host
);
327 filter
->RemoveHostnameHandler("https", host
);
330 const std::string host_
;
333 // Verifies that the given url |spec| can be opened. This assumes that |spec|
334 // points at empty.html in the test data dir.
335 void CheckCanOpenURL(Browser
* browser
, const char* spec
) {
337 ui_test_utils::NavigateToURL(browser
, url
);
338 content::WebContents
* contents
=
339 browser
->tab_strip_model()->GetActiveWebContents();
340 EXPECT_EQ(url
, contents
->GetURL());
341 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
342 base::string16 title
=
343 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
344 EXPECT_NE(title
, contents
->GetTitle());
347 // Verifies that access to the given url |spec| is blocked.
348 void CheckURLIsBlocked(Browser
* browser
, const char* spec
) {
350 ui_test_utils::NavigateToURL(browser
, url
);
351 content::WebContents
* contents
=
352 browser
->tab_strip_model()->GetActiveWebContents();
353 EXPECT_EQ(url
, contents
->GetURL());
354 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
355 base::string16 title
=
356 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
357 EXPECT_EQ(title
, contents
->GetTitle());
359 // Verify that the expected error page is being displayed.
361 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
363 "var textContent = document.body.textContent;"
364 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
365 "domAutomationController.send(hasError);",
370 // Downloads a file named |file| and expects it to be saved to |dir|, which
372 void DownloadAndVerifyFile(
373 Browser
* browser
, const base::FilePath
& dir
, const base::FilePath
& file
) {
374 content::DownloadManager
* download_manager
=
375 content::BrowserContext::GetDownloadManager(browser
->profile());
376 content::DownloadTestObserverTerminal
observer(
378 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
379 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
380 base::FilePath downloaded
= dir
.Append(file
);
381 EXPECT_FALSE(base::PathExists(downloaded
));
382 ui_test_utils::NavigateToURL(browser
, url
);
383 observer
.WaitForFinished();
385 1u, observer
.NumDownloadsSeenInState(content::DownloadItem::COMPLETE
));
386 EXPECT_TRUE(base::PathExists(downloaded
));
387 base::FileEnumerator
enumerator(dir
, false, base::FileEnumerator::FILES
);
388 EXPECT_EQ(file
, enumerator
.Next().BaseName());
389 EXPECT_EQ(base::FilePath(), enumerator
.Next());
392 #if defined(OS_CHROMEOS)
393 int CountScreenshots() {
394 DownloadPrefs
* download_prefs
= DownloadPrefs::FromBrowserContext(
395 ProfileManager::GetActiveUserProfile());
396 base::FileEnumerator
enumerator(download_prefs
->DownloadPath(),
397 false, base::FileEnumerator::FILES
,
400 while (!enumerator
.Next().empty())
406 // Checks if WebGL is enabled in the given WebContents.
407 bool IsWebGLEnabled(content::WebContents
* contents
) {
409 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
411 "var canvas = document.createElement('canvas');"
412 "var context = canvas.getContext('webgl');"
413 "domAutomationController.send(context != null);",
418 bool IsJavascriptEnabled(content::WebContents
* contents
) {
419 scoped_ptr
<base::Value
> value
= content::ExecuteScriptAndGetValue(
420 contents
->GetMainFrame(), "123");
422 if (!value
->GetAsInteger(&result
))
423 EXPECT_EQ(base::Value::TYPE_NULL
, value
->GetType());
424 return result
== 123;
427 bool IsNetworkPredictionEnabled(PrefService
* prefs
) {
428 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs
);
431 void CopyPluginListAndQuit(std::vector
<content::WebPluginInfo
>* out
,
432 const std::vector
<content::WebPluginInfo
>& in
) {
434 base::MessageLoop::current()->QuitWhenIdle();
438 void CopyValueAndQuit(T
* out
, T in
) {
440 base::MessageLoop::current()->QuitWhenIdle();
443 void GetPluginList(std::vector
<content::WebPluginInfo
>* plugins
) {
444 content::PluginService
* service
= content::PluginService::GetInstance();
445 service
->GetPlugins(base::Bind(CopyPluginListAndQuit
, plugins
));
446 content::RunMessageLoop();
449 const content::WebPluginInfo
* GetFlashPlugin(
450 const std::vector
<content::WebPluginInfo
>& plugins
) {
451 const content::WebPluginInfo
* flash
= NULL
;
452 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
453 if (plugins
[i
].name
== base::ASCIIToUTF16(content::kFlashPluginName
)) {
458 #if defined(OFFICIAL_BUILD)
459 // Official builds bundle Flash.
463 LOG(INFO
) << "Test skipped because the Flash plugin couldn't be found.";
468 bool SetPluginEnabled(PluginPrefs
* plugin_prefs
,
469 const content::WebPluginInfo
* plugin
,
472 plugin_prefs
->EnablePlugin(enabled
, plugin
->path
,
473 base::Bind(CopyValueAndQuit
<bool>, &ok
));
474 content::RunMessageLoop();
478 int CountPluginsOnIOThread() {
480 for (content::BrowserChildProcessHostIterator iter
; !iter
.Done(); ++iter
) {
481 if (iter
.GetData().process_type
== content::PROCESS_TYPE_PLUGIN
||
482 iter
.GetData().process_type
== content::PROCESS_TYPE_PPAPI_PLUGIN
) {
491 BrowserThread::PostTaskAndReplyWithResult(
492 BrowserThread::IO
, FROM_HERE
,
493 base::Bind(CountPluginsOnIOThread
),
494 base::Bind(CopyValueAndQuit
<int>, &count
));
495 content::RunMessageLoop();
500 void FlushBlacklistPolicy() {
501 // Updates of the URLBlacklist are done on IO, after building the blacklist
502 // on the blocking pool, which is initiated from IO.
503 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
504 BrowserThread::GetBlockingPool()->FlushForTesting();
505 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
508 bool ContainsVisibleElement(content::WebContents
* contents
,
509 const std::string
& id
) {
511 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
513 "var elem = document.getElementById('" + id
+ "');"
514 "domAutomationController.send(!!elem && !elem.hidden);",
519 #if defined(OS_CHROMEOS)
520 class TestAudioObserver
: public chromeos::CrasAudioHandler::AudioObserver
{
522 TestAudioObserver() : output_mute_changed_count_(0) {
525 int output_mute_changed_count() const {
526 return output_mute_changed_count_
;
529 ~TestAudioObserver() override
{}
532 // chromeos::CrasAudioHandler::AudioObserver overrides.
533 void OnOutputMuteChanged(bool /* mute_on */,
534 bool /* system_adjust */) override
{
535 ++output_mute_changed_count_
;
539 int output_mute_changed_count_
;
541 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver
);
545 // This class waits until either a load stops or the WebContents is destroyed.
546 class WebContentsLoadedOrDestroyedWatcher
547 : public content::WebContentsObserver
{
549 explicit WebContentsLoadedOrDestroyedWatcher(
550 content::WebContents
* web_contents
);
551 ~WebContentsLoadedOrDestroyedWatcher() override
;
553 // Waits until the WebContents's load is done or until it is destroyed.
556 // Overridden WebContentsObserver methods.
557 void WebContentsDestroyed() override
;
558 void DidStopLoading() override
;
561 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
563 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher
);
566 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
567 content::WebContents
* web_contents
)
568 : content::WebContentsObserver(web_contents
),
569 message_loop_runner_(new content::MessageLoopRunner
) {
572 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
574 void WebContentsLoadedOrDestroyedWatcher::Wait() {
575 message_loop_runner_
->Run();
578 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
579 message_loop_runner_
->Quit();
582 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
583 message_loop_runner_
->Quit();
586 #if !defined(OS_MACOSX)
588 // Observer used to wait for the creation of a new app window.
589 class TestAddAppWindowObserver
590 : public extensions::AppWindowRegistry::Observer
{
592 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry
* registry
);
593 ~TestAddAppWindowObserver() override
;
595 // extensions::AppWindowRegistry::Observer:
596 void OnAppWindowAdded(extensions::AppWindow
* app_window
) override
;
598 extensions::AppWindow
* WaitForAppWindow();
601 extensions::AppWindowRegistry
* registry_
; // Not owned.
602 extensions::AppWindow
* window_
; // Not owned.
603 base::RunLoop run_loop_
;
605 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver
);
608 TestAddAppWindowObserver::TestAddAppWindowObserver(
609 extensions::AppWindowRegistry
* registry
)
610 : registry_(registry
), window_(NULL
) {
611 registry_
->AddObserver(this);
614 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
615 registry_
->RemoveObserver(this);
618 void TestAddAppWindowObserver::OnAppWindowAdded(
619 extensions::AppWindow
* app_window
) {
620 window_
= app_window
;
624 extensions::AppWindow
* TestAddAppWindowObserver::WaitForAppWindow() {
633 class PolicyTest
: public InProcessBrowserTest
{
636 ~PolicyTest() override
{}
638 void SetUp() override
{
639 test_extension_cache_
.reset(new extensions::ExtensionCacheFake());
640 InProcessBrowserTest::SetUp();
643 void SetUpInProcessBrowserTestFixture() override
{
644 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
645 EXPECT_CALL(provider_
, IsInitializationComplete(_
))
646 .WillRepeatedly(Return(true));
647 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_
);
650 void SetUpOnMainThread() override
{
651 BrowserThread::PostTask(
652 BrowserThread::IO
, FROM_HERE
,
653 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled
, true));
654 if (extension_service()->updater()) {
655 extension_service()->updater()->SetExtensionCacheForTesting(
656 test_extension_cache_
.get());
660 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
661 // instead of chrome::DIR_TEST_DATA.
662 void ServeContentTestData() {
663 base::FilePath root_http
;
664 PathService::Get(content::DIR_TEST_DATA
, &root_http
);
665 BrowserThread::PostTaskAndReply(
666 BrowserThread::IO
, FROM_HERE
,
667 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers
, root_http
,
668 make_scoped_refptr(BrowserThread::GetBlockingPool())),
669 base::MessageLoop::current()->QuitWhenIdleClosure());
670 content::RunMessageLoop();
673 void SetScreenshotPolicy(bool enabled
) {
675 policies
.Set(key::kDisableScreenshots
,
676 POLICY_LEVEL_MANDATORY
,
679 new base::FundamentalValue(!enabled
),
681 UpdateProviderPolicy(policies
);
684 #if defined(OS_CHROMEOS)
685 class QuitMessageLoopAfterScreenshot
: public ui::ScreenshotGrabberObserver
{
687 void OnScreenshotCompleted(
688 ScreenshotGrabberObserver::Result screenshot_result
,
689 const base::FilePath
& screenshot_path
) override
{
690 BrowserThread::PostTaskAndReply(BrowserThread::IO
,
692 base::Bind(base::DoNothing
),
693 base::MessageLoop::QuitClosure());
696 ~QuitMessageLoopAfterScreenshot() override
{}
699 void TestScreenshotFile(bool enabled
) {
700 // AddObserver is an ash-specific method, so just replace the screenshot
701 // grabber with one we've created here.
702 scoped_ptr
<ChromeScreenshotGrabber
> chrome_screenshot_grabber(
703 new ChromeScreenshotGrabber
);
704 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
705 // is tied to the test instead.
706 chrome_screenshot_grabber
->screenshot_grabber()->AddObserver(&observer_
);
707 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
708 chrome_screenshot_grabber
.Pass());
710 SetScreenshotPolicy(enabled
);
711 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
712 ash::TAKE_SCREENSHOT
);
714 content::RunMessageLoop();
715 static_cast<ChromeScreenshotGrabber
*>(ash::Shell::GetInstance()
716 ->accelerator_controller()
717 ->screenshot_delegate())
718 ->screenshot_grabber()
719 ->RemoveObserver(&observer_
);
723 ExtensionService
* extension_service() {
724 extensions::ExtensionSystem
* system
=
725 extensions::ExtensionSystem::Get(browser()->profile());
726 return system
->extension_service();
729 const extensions::Extension
* InstallExtension(
730 const base::FilePath::StringType
& name
) {
731 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
732 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
733 scoped_refptr
<extensions::CrxInstaller
> installer
=
734 extensions::CrxInstaller::CreateSilent(extension_service());
735 installer
->set_allow_silent_install(true);
736 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
737 installer
->set_creation_flags(extensions::Extension::FROM_WEBSTORE
);
739 content::WindowedNotificationObserver
observer(
740 extensions::NOTIFICATION_CRX_INSTALLER_DONE
,
741 content::NotificationService::AllSources());
742 installer
->InstallCrx(extension_path
);
744 content::Details
<const extensions::Extension
> details
= observer
.details();
745 return details
.ptr();
748 const extensions::Extension
* LoadUnpackedExtension(
749 const base::FilePath::StringType
& name
, bool expect_success
) {
750 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
751 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
752 scoped_refptr
<extensions::UnpackedInstaller
> installer
=
753 extensions::UnpackedInstaller::Create(extension_service());
754 content::WindowedNotificationObserver
observer(
755 expect_success
? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
756 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR
,
757 content::NotificationService::AllSources());
758 installer
->Load(extension_path
);
761 extensions::ExtensionRegistry
* registry
=
762 extensions::ExtensionRegistry::Get(browser()->profile());
763 for (const scoped_refptr
<const extensions::Extension
>& extension
:
764 registry
->enabled_extensions()) {
765 if (extension
->path() == extension_path
)
766 return extension
.get();
771 void UninstallExtension(const std::string
& id
, bool expect_success
) {
772 if (expect_success
) {
773 extensions::TestExtensionRegistryObserver
observer(
774 extensions::ExtensionRegistry::Get(browser()->profile()));
775 extension_service()->UninstallExtension(
776 id
, extensions::UNINSTALL_REASON_FOR_TESTING
,
777 base::Bind(&base::DoNothing
), NULL
);
778 observer
.WaitForExtensionUninstalled();
780 content::WindowedNotificationObserver
observer(
781 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
782 content::NotificationService::AllSources());
783 extension_service()->UninstallExtension(
785 extensions::UNINSTALL_REASON_FOR_TESTING
,
786 base::Bind(&base::DoNothing
),
792 void DisableExtension(const std::string
& id
) {
793 extensions::TestExtensionRegistryObserver
observer(
794 extensions::ExtensionRegistry::Get(browser()->profile()));
795 extension_service()->DisableExtension(id
,
796 extensions::Extension::DISABLE_NONE
);
797 observer
.WaitForExtensionUnloaded();
800 void UpdateProviderPolicy(const PolicyMap
& policy
) {
801 provider_
.UpdateChromePolicy(policy
);
802 DCHECK(base::MessageLoop::current());
807 // Sends a mouse click at the given coordinates to the current renderer.
808 void PerformClick(int x
, int y
) {
809 content::WebContents
* contents
=
810 browser()->tab_strip_model()->GetActiveWebContents();
811 blink::WebMouseEvent click_event
;
812 click_event
.type
= blink::WebInputEvent::MouseDown
;
813 click_event
.button
= blink::WebMouseEvent::ButtonLeft
;
814 click_event
.clickCount
= 1;
817 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
818 click_event
.type
= blink::WebInputEvent::MouseUp
;
819 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
822 void SetPolicy(PolicyMap
* policies
, const char* key
, base::Value
* value
) {
825 POLICY_LEVEL_MANDATORY
,
831 policies
->Erase(key
);
835 void ApplySafeSearchPolicy(base::FundamentalValue
* legacy_safe_search
,
836 base::FundamentalValue
* google_safe_search
,
837 base::FundamentalValue
* youtube_safety_mode
) {
839 SetPolicy(&policies
, key::kForceSafeSearch
, legacy_safe_search
);
840 SetPolicy(&policies
, key::kForceGoogleSafeSearch
, google_safe_search
);
841 SetPolicy(&policies
, key::kForceYouTubeSafetyMode
, youtube_safety_mode
);
842 UpdateProviderPolicy(policies
);
845 void CheckSafeSearch(bool expect_safe_search
) {
846 content::WebContents
* web_contents
=
847 browser()->tab_strip_model()->GetActiveWebContents();
848 content::TestNavigationObserver
observer(web_contents
);
849 chrome::FocusLocationBar(browser());
850 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
851 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
852 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
854 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
856 std::string
expected_url("http://google.com/");
857 if (expect_safe_search
) {
858 expected_url
+= "?" + std::string(chrome::kSafeSearchSafeParameter
) +
859 "&" + chrome::kSafeSearchSsuiParameter
;
861 EXPECT_EQ(GURL(expected_url
), web_contents
->GetURL());
864 MockConfigurationPolicyProvider provider_
;
865 scoped_ptr
<extensions::ExtensionCacheFake
> test_extension_cache_
;
866 #if defined(OS_CHROMEOS)
867 QuitMessageLoopAfterScreenshot observer_
;
872 // This policy only exists on Windows.
874 // Sets the locale policy before the browser is started.
875 class LocalePolicyTest
: public PolicyTest
{
877 LocalePolicyTest() {}
878 ~LocalePolicyTest() override
{}
880 void SetUpInProcessBrowserTestFixture() override
{
881 PolicyTest::SetUpInProcessBrowserTestFixture();
883 policies
.Set(key::kApplicationLocaleValue
,
884 POLICY_LEVEL_MANDATORY
,
887 new base::StringValue("fr"),
889 provider_
.UpdateChromePolicy(policies
);
890 // The "en-US" ResourceBundle is always loaded before this step for tests,
891 // but in this test we want the browser to load the bundle as it
893 ResourceBundle::CleanupSharedInstance();
897 IN_PROC_BROWSER_TEST_F(LocalePolicyTest
, ApplicationLocaleValue
) {
898 // Verifies that the default locale can be overridden with policy.
899 EXPECT_EQ("fr", g_browser_process
->GetApplicationLocale());
900 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
901 base::string16 french_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
902 base::string16 title
;
903 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title
));
904 EXPECT_EQ(french_title
, title
);
906 // Make sure this is really French and differs from the English title.
908 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
909 EXPECT_EQ("en-US", loaded
);
910 base::string16 english_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
911 EXPECT_NE(french_title
, english_title
);
915 IN_PROC_BROWSER_TEST_F(PolicyTest
, BookmarkBarEnabled
) {
916 #if defined(OS_WIN) && defined(USE_ASH)
917 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
918 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
919 switches::kAshBrowserTests
))
923 // Verifies that the bookmarks bar can be forced to always or never show up.
925 // Test starts in about:blank.
926 PrefService
* prefs
= browser()->profile()->GetPrefs();
927 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
928 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
929 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
932 policies
.Set(key::kBookmarkBarEnabled
,
933 POLICY_LEVEL_MANDATORY
,
936 new base::FundamentalValue(true),
938 UpdateProviderPolicy(policies
);
939 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
940 EXPECT_TRUE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
941 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
943 // The NTP has special handling of the bookmark bar.
944 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
945 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
947 policies
.Set(key::kBookmarkBarEnabled
,
948 POLICY_LEVEL_MANDATORY
,
951 new base::FundamentalValue(false),
953 UpdateProviderPolicy(policies
);
954 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
955 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
956 // The bookmark bar is hidden in the NTP when disabled by policy.
957 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
960 UpdateProviderPolicy(policies
);
961 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
962 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
963 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
964 EXPECT_EQ(BookmarkBar::DETACHED
, browser()->bookmark_bar_state());
967 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_PRE_DefaultCookiesSetting
) {
968 // Verifies that cookies are deleted on shutdown. This test is split in 3
969 // parts because it spans 2 browser restarts.
971 Profile
* profile
= browser()->profile();
973 // No cookies at startup.
974 EXPECT_TRUE(content::GetCookies(profile
, url
).empty());
976 std::string value
= std::string(kCookieValue
) + std::string(kCookieOptions
);
977 EXPECT_TRUE(content::SetCookie(profile
, url
, value
));
978 // Verify it was set.
979 EXPECT_EQ(kCookieValue
, GetCookies(profile
, url
));
982 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_DefaultCookiesSetting
) {
983 // Verify that the cookie persists across restarts.
984 EXPECT_EQ(kCookieValue
, GetCookies(browser()->profile(), GURL(kURL
)));
985 // Now set the policy and the cookie should be gone after another restart.
987 policies
.Set(key::kDefaultCookiesSetting
,
988 POLICY_LEVEL_MANDATORY
,
991 new base::FundamentalValue(4),
993 UpdateProviderPolicy(policies
);
996 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultCookiesSetting
) {
997 // Verify that the cookie is gone.
998 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL
)).empty());
1001 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultSearchProvider
) {
1002 MakeRequestFail
make_request_fail("search.example");
1004 // Verifies that a default search is made using the provider configured via
1005 // policy. Also checks that default search can be completely disabled.
1006 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1007 const std::string
kSearchURL("http://search.example/search?q={searchTerms}");
1008 const std::string
kAlternateURL0(
1009 "http://search.example/search#q={searchTerms}");
1010 const std::string
kAlternateURL1("http://search.example/#q={searchTerms}");
1011 const std::string
kSearchTermsReplacementKey("zekey");
1012 const std::string
kImageURL("http://test.com/searchbyimage/upload");
1013 const std::string
kImageURLPostParams(
1014 "image_content=content,image_url=http://test.com/test.png");
1015 const std::string
kNewTabURL("http://search.example/newtab");
1017 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1018 browser()->profile());
1019 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1020 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1021 ASSERT_TRUE(default_search
);
1022 EXPECT_NE(kKeyword
, default_search
->keyword());
1023 EXPECT_NE(kSearchURL
, default_search
->url());
1025 default_search
->alternate_urls().size() == 2 &&
1026 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1027 default_search
->alternate_urls()[1] == kAlternateURL1
&&
1028 default_search
->search_terms_replacement_key() ==
1029 kSearchTermsReplacementKey
&&
1030 default_search
->image_url() == kImageURL
&&
1031 default_search
->image_url_post_params() == kImageURLPostParams
&&
1032 default_search
->new_tab_url() == kNewTabURL
);
1034 // Override the default search provider using policies.
1036 policies
.Set(key::kDefaultSearchProviderEnabled
,
1037 POLICY_LEVEL_MANDATORY
,
1039 POLICY_SOURCE_CLOUD
,
1040 new base::FundamentalValue(true),
1042 policies
.Set(key::kDefaultSearchProviderKeyword
,
1043 POLICY_LEVEL_MANDATORY
,
1045 POLICY_SOURCE_CLOUD
,
1046 new base::StringValue(kKeyword
),
1048 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1049 POLICY_LEVEL_MANDATORY
,
1051 POLICY_SOURCE_CLOUD
,
1052 new base::StringValue(kSearchURL
),
1054 base::ListValue
* alternate_urls
= new base::ListValue();
1055 alternate_urls
->AppendString(kAlternateURL0
);
1056 alternate_urls
->AppendString(kAlternateURL1
);
1057 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1058 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, alternate_urls
, nullptr);
1059 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1060 POLICY_LEVEL_MANDATORY
,
1062 POLICY_SOURCE_CLOUD
,
1063 new base::StringValue(kSearchTermsReplacementKey
),
1065 policies
.Set(key::kDefaultSearchProviderImageURL
,
1066 POLICY_LEVEL_MANDATORY
,
1068 POLICY_SOURCE_CLOUD
,
1069 new base::StringValue(kImageURL
),
1071 policies
.Set(key::kDefaultSearchProviderImageURLPostParams
,
1072 POLICY_LEVEL_MANDATORY
,
1074 POLICY_SOURCE_CLOUD
,
1075 new base::StringValue(kImageURLPostParams
),
1077 policies
.Set(key::kDefaultSearchProviderNewTabURL
,
1078 POLICY_LEVEL_MANDATORY
,
1080 POLICY_SOURCE_CLOUD
,
1081 new base::StringValue(kNewTabURL
),
1083 UpdateProviderPolicy(policies
);
1084 default_search
= service
->GetDefaultSearchProvider();
1085 ASSERT_TRUE(default_search
);
1086 EXPECT_EQ(kKeyword
, default_search
->keyword());
1087 EXPECT_EQ(kSearchURL
, default_search
->url());
1088 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1089 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1090 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1091 EXPECT_EQ(kSearchTermsReplacementKey
,
1092 default_search
->search_terms_replacement_key());
1093 EXPECT_EQ(kImageURL
, default_search
->image_url());
1094 EXPECT_EQ(kImageURLPostParams
, default_search
->image_url_post_params());
1095 EXPECT_EQ(kNewTabURL
, default_search
->new_tab_url());
1097 // Verify that searching from the omnibox uses kSearchURL.
1098 chrome::FocusLocationBar(browser());
1099 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1100 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "stuff to search for");
1101 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1102 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1103 content::WebContents
* web_contents
=
1104 browser()->tab_strip_model()->GetActiveWebContents();
1105 GURL
expected("http://search.example/search?q=stuff+to+search+for");
1106 EXPECT_EQ(expected
, web_contents
->GetURL());
1108 // Verify that searching from the omnibox can be disabled.
1109 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1110 policies
.Set(key::kDefaultSearchProviderEnabled
,
1111 POLICY_LEVEL_MANDATORY
,
1113 POLICY_SOURCE_CLOUD
,
1114 new base::FundamentalValue(false),
1116 EXPECT_TRUE(service
->GetDefaultSearchProvider());
1117 UpdateProviderPolicy(policies
);
1118 EXPECT_FALSE(service
->GetDefaultSearchProvider());
1119 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "should not work");
1120 // This means that submitting won't trigger any action.
1121 EXPECT_FALSE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1122 EXPECT_EQ(GURL(url::kAboutBlankURL
), web_contents
->GetURL());
1125 IN_PROC_BROWSER_TEST_F(PolicyTest
, PolicyPreprocessing
) {
1126 // Add an individual proxy policy value.
1128 policies
.Set(key::kProxyServerMode
,
1129 POLICY_LEVEL_MANDATORY
,
1131 POLICY_SOURCE_CLOUD
,
1132 new base::FundamentalValue(3),
1134 UpdateProviderPolicy(policies
);
1136 // It should be removed and replaced with a dictionary.
1138 scoped_ptr
<base::DictionaryValue
> expected_value(new base::DictionaryValue
);
1139 expected_value
->SetInteger(key::kProxyServerMode
, 3);
1140 expected
.Set(key::kProxySettings
,
1141 POLICY_LEVEL_MANDATORY
,
1143 POLICY_SOURCE_CLOUD
,
1144 expected_value
.release(),
1147 // Check both the browser and the profile.
1148 const PolicyMap
& actual_from_browser
=
1149 g_browser_process
->browser_policy_connector()
1150 ->GetPolicyService()
1151 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1152 EXPECT_TRUE(expected
.Equals(actual_from_browser
));
1153 const PolicyMap
& actual_from_profile
=
1154 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1156 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1157 EXPECT_TRUE(expected
.Equals(actual_from_profile
));
1160 IN_PROC_BROWSER_TEST_F(PolicyTest
, ForceSafeSearch
) {
1161 // Makes the requests fail since all we want to check is that the redirection
1162 // is done properly.
1163 MakeRequestFail
make_request_fail("google.com");
1165 // Verifies that requests to Google Search engine with the SafeSearch
1166 // enabled set the safe=active&ssui=on parameters at the end of the query.
1167 // First check that nothing happens.
1168 CheckSafeSearch(false);
1170 // Go over all combinations of (undefined,true,false) for the three policies.
1171 for (int i
= 0; i
< 3 * 3 * 3; i
++) {
1173 int google
= (i
/ 3) % 3;
1174 int youtube
= i
/ (3 * 3);
1176 // Override the default SafeSearch setting using policies.
1177 ApplySafeSearchPolicy(
1178 legacy
== 0 ? nullptr : new base::FundamentalValue(legacy
== 1),
1179 google
== 0 ? nullptr : new base::FundamentalValue(google
== 1),
1180 youtube
== 0 ? nullptr : new base::FundamentalValue(youtube
== 1));
1182 // The legacy policy should only have an effect if both google and youtube
1184 bool legacy_in_effect
= (google
== 0 && youtube
== 0 && legacy
!= 0);
1185 bool legacy_enabled
= legacy_in_effect
&& legacy
== 1;
1187 PrefService
* prefs
= browser()->profile()->GetPrefs();
1188 EXPECT_EQ(google
!= 0 || legacy_in_effect
,
1189 prefs
->IsManagedPreference(prefs::kForceGoogleSafeSearch
));
1190 EXPECT_EQ(google
== 1 || legacy_enabled
,
1191 prefs
->GetBoolean(prefs::kForceGoogleSafeSearch
));
1193 EXPECT_EQ(youtube
!= 0 || legacy_in_effect
,
1194 prefs
->IsManagedPreference(prefs::kForceYouTubeSafetyMode
));
1195 EXPECT_EQ(youtube
== 1 || legacy_enabled
,
1196 prefs
->GetBoolean(prefs::kForceYouTubeSafetyMode
));
1198 CheckSafeSearch(google
== 1 || legacy_enabled
);
1202 IN_PROC_BROWSER_TEST_F(PolicyTest
, ReplaceSearchTerms
) {
1203 MakeRequestFail
make_request_fail("search.example");
1205 search::EnableQueryExtractionForTesting();
1207 // Verifies that a default search is made using the provider configured via
1208 // policy. Also checks that default search can be completely disabled.
1209 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1210 const std::string
kSearchURL("https://www.google.com/search?q={searchTerms}");
1211 const std::string
kInstantURL("http://does/not/exist");
1212 const std::string
kAlternateURL0(
1213 "https://www.google.com/search#q={searchTerms}");
1214 const std::string
kAlternateURL1("https://www.google.com/#q={searchTerms}");
1215 const std::string
kSearchTermsReplacementKey(
1216 "{google:instantExtendedEnabledKey}");
1218 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1219 browser()->profile());
1220 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1221 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1222 ASSERT_TRUE(default_search
);
1223 EXPECT_NE(kKeyword
, default_search
->keyword());
1224 EXPECT_NE(kSearchURL
, default_search
->url());
1225 EXPECT_NE(kInstantURL
, default_search
->instant_url());
1227 default_search
->alternate_urls().size() == 2 &&
1228 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1229 default_search
->alternate_urls()[1] == kAlternateURL1
);
1231 // Override the default search provider using policies.
1233 policies
.Set(key::kDefaultSearchProviderEnabled
,
1234 POLICY_LEVEL_MANDATORY
,
1236 POLICY_SOURCE_CLOUD
,
1237 new base::FundamentalValue(true),
1239 policies
.Set(key::kDefaultSearchProviderKeyword
,
1240 POLICY_LEVEL_MANDATORY
,
1242 POLICY_SOURCE_CLOUD
,
1243 new base::StringValue(kKeyword
),
1245 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1246 POLICY_LEVEL_MANDATORY
,
1248 POLICY_SOURCE_CLOUD
,
1249 new base::StringValue(kSearchURL
),
1251 policies
.Set(key::kDefaultSearchProviderInstantURL
,
1252 POLICY_LEVEL_MANDATORY
,
1254 POLICY_SOURCE_CLOUD
,
1255 new base::StringValue(kInstantURL
),
1257 base::ListValue
* alternate_urls
= new base::ListValue();
1258 alternate_urls
->AppendString(kAlternateURL0
);
1259 alternate_urls
->AppendString(kAlternateURL1
);
1260 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1262 POLICY_SOURCE_CLOUD
, alternate_urls
, nullptr);
1263 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1264 POLICY_LEVEL_MANDATORY
,
1266 POLICY_SOURCE_CLOUD
,
1267 new base::StringValue(kSearchTermsReplacementKey
),
1269 UpdateProviderPolicy(policies
);
1270 default_search
= service
->GetDefaultSearchProvider();
1271 ASSERT_TRUE(default_search
);
1272 EXPECT_EQ(kKeyword
, default_search
->keyword());
1273 EXPECT_EQ(kSearchURL
, default_search
->url());
1274 EXPECT_EQ(kInstantURL
, default_search
->instant_url());
1275 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1276 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1277 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1279 // Query terms replacement requires that the renderer process be a recognized
1280 // Instant renderer. Fake it.
1281 InstantService
* instant_service
=
1282 InstantServiceFactory::GetForProfile(browser()->profile());
1283 instant_service
->AddInstantProcess(browser()->tab_strip_model()->
1284 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1286 // Verify that searching from the omnibox does search term replacement with
1287 // first URL pattern.
1288 chrome::FocusLocationBar(browser());
1289 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1290 OmniboxView
* omnibox_view
= location_bar
->GetOmniboxView();
1291 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1292 "https://www.google.com/?espv=1#q=foobar");
1294 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1295 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1297 // Verify that not using espv=1 does not do search term replacement.
1298 chrome::FocusLocationBar(browser());
1299 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1300 "https://www.google.com/?q=foobar");
1302 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1303 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1304 omnibox_view
->GetText());
1306 // Verify that searching from the omnibox does search term replacement with
1307 // second URL pattern.
1308 chrome::FocusLocationBar(browser());
1309 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1310 "https://www.google.com/search?espv=1#q=banana");
1312 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1313 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view
->GetText());
1315 // Verify that searching from the omnibox does search term replacement with
1316 // standard search URL pattern.
1317 chrome::FocusLocationBar(browser());
1318 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1319 "https://www.google.com/search?q=tractor+parts&espv=1");
1321 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1322 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view
->GetText());
1324 // Verify that searching from the omnibox prioritizes hash over query.
1325 chrome::FocusLocationBar(browser());
1326 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1327 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1329 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1330 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1333 IN_PROC_BROWSER_TEST_F(PolicyTest
, Disable3DAPIs
) {
1334 // This test assumes Gpu access.
1335 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
))
1338 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1339 // WebGL is enabled by default.
1340 content::WebContents
* contents
=
1341 browser()->tab_strip_model()->GetActiveWebContents();
1342 EXPECT_TRUE(IsWebGLEnabled(contents
));
1343 // Disable with a policy.
1345 policies
.Set(key::kDisable3DAPIs
,
1346 POLICY_LEVEL_MANDATORY
,
1348 POLICY_SOURCE_CLOUD
,
1349 new base::FundamentalValue(true),
1351 UpdateProviderPolicy(policies
);
1352 // Crash and reload the tab to get a new renderer.
1353 content::CrashTab(contents
);
1354 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1355 EXPECT_FALSE(IsWebGLEnabled(contents
));
1356 // Enable with a policy.
1357 policies
.Set(key::kDisable3DAPIs
,
1358 POLICY_LEVEL_MANDATORY
,
1360 POLICY_SOURCE_CLOUD
,
1361 new base::FundamentalValue(false),
1363 UpdateProviderPolicy(policies
);
1364 content::CrashTab(contents
);
1365 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1366 EXPECT_TRUE(IsWebGLEnabled(contents
));
1369 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableSpdy
) {
1370 // Verifies that SPDY can be disable by policy.
1371 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1373 policies
.Set(key::kDisableSpdy
,
1374 POLICY_LEVEL_MANDATORY
,
1376 POLICY_SOURCE_CLOUD
,
1377 new base::FundamentalValue(true),
1379 UpdateProviderPolicy(policies
);
1380 content::RunAllPendingInMessageLoop();
1381 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1382 // Verify that it can be force-enabled too.
1383 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy
, true);
1384 policies
.Set(key::kDisableSpdy
,
1385 POLICY_LEVEL_MANDATORY
,
1387 POLICY_SOURCE_CLOUD
,
1388 new base::FundamentalValue(false),
1390 UpdateProviderPolicy(policies
);
1391 content::RunAllPendingInMessageLoop();
1392 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1395 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPlugins
) {
1396 // Verifies that plugins can be forced to be disabled by policy.
1398 // Verify that the Flash plugin exists and that it can be enabled and disabled
1400 std::vector
<content::WebPluginInfo
> plugins
;
1401 GetPluginList(&plugins
);
1402 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1405 PluginPrefs
* plugin_prefs
=
1406 PluginPrefs::GetForProfile(browser()->profile()).get();
1407 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1408 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1409 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1410 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1411 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1413 // Now disable it with a policy.
1414 base::ListValue disabled_plugins
;
1415 disabled_plugins
.Append(new base::StringValue("*Flash*"));
1417 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
1418 POLICY_SOURCE_CLOUD
, disabled_plugins
.DeepCopy(), nullptr);
1419 UpdateProviderPolicy(policies
);
1420 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1421 // The user shouldn't be able to enable it.
1422 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1423 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1426 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPluginsExceptions
) {
1427 // Verifies that plugins with an exception in the blacklist can be enabled.
1429 // Verify that the Flash plugin exists and that it can be enabled and disabled
1431 std::vector
<content::WebPluginInfo
> plugins
;
1432 GetPluginList(&plugins
);
1433 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1436 PluginPrefs
* plugin_prefs
=
1437 PluginPrefs::GetForProfile(browser()->profile()).get();
1438 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1440 // Disable all plugins.
1441 base::ListValue disabled_plugins
;
1442 disabled_plugins
.Append(new base::StringValue("*"));
1444 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
1445 POLICY_SOURCE_CLOUD
, disabled_plugins
.DeepCopy(), nullptr);
1446 UpdateProviderPolicy(policies
);
1447 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1448 // The user shouldn't be able to enable it.
1449 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1450 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1452 // Now open an exception for flash.
1453 base::ListValue disabled_plugins_exceptions
;
1454 disabled_plugins_exceptions
.Append(new base::StringValue("*Flash*"));
1455 policies
.Set(key::kDisabledPluginsExceptions
, POLICY_LEVEL_MANDATORY
,
1456 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
,
1457 disabled_plugins_exceptions
.DeepCopy(), nullptr);
1458 UpdateProviderPolicy(policies
);
1459 // It should revert to the user's preference automatically.
1460 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1461 // And the user should be able to disable and enable again.
1462 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1463 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1464 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1465 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1468 IN_PROC_BROWSER_TEST_F(PolicyTest
, EnabledPlugins
) {
1469 // Verifies that a plugin can be force-installed with a policy.
1470 std::vector
<content::WebPluginInfo
> plugins
;
1471 GetPluginList(&plugins
);
1472 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1475 PluginPrefs
* plugin_prefs
=
1476 PluginPrefs::GetForProfile(browser()->profile()).get();
1477 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1479 // The user disables it and then a policy forces it to be enabled.
1480 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1481 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1482 base::ListValue plugin_list
;
1483 plugin_list
.Append(new base::StringValue(content::kFlashPluginName
));
1485 policies
.Set(key::kEnabledPlugins
, POLICY_LEVEL_MANDATORY
,
1486 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, plugin_list
.DeepCopy(),
1488 UpdateProviderPolicy(policies
);
1489 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1490 // The user can't disable it anymore.
1491 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, false));
1492 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1494 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1495 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1496 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, plugin_list
.DeepCopy(),
1498 UpdateProviderPolicy(policies
);
1499 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1502 IN_PROC_BROWSER_TEST_F(PolicyTest
, AlwaysAuthorizePlugins
) {
1503 // Verifies that dangerous plugins can be always authorized to run with
1506 // Verify that the test page exists. It is only present in checkouts with
1508 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1509 base::FilePath(FILE_PATH_LITERAL("plugin")),
1510 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1512 "Test skipped because plugin/quicktime.html test file wasn't found.";
1516 ServeContentTestData();
1517 // No plugins at startup.
1518 EXPECT_EQ(0, CountPlugins());
1520 content::WebContents
* contents
=
1521 browser()->tab_strip_model()->GetActiveWebContents();
1522 ASSERT_TRUE(contents
);
1523 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
1524 ASSERT_TRUE(infobar_service
);
1525 EXPECT_EQ(0u, infobar_service
->infobar_count());
1527 base::FilePath
path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1528 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1529 ui_test_utils::NavigateToURL(browser(), url
);
1530 // This should have triggered the dangerous plugin infobar.
1531 ASSERT_EQ(1u, infobar_service
->infobar_count());
1533 infobar_service
->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1534 // And the plugin isn't running.
1535 EXPECT_EQ(0, CountPlugins());
1537 // Now set a policy to always authorize this.
1539 policies
.Set(key::kAlwaysAuthorizePlugins
,
1540 POLICY_LEVEL_MANDATORY
,
1542 POLICY_SOURCE_CLOUD
,
1543 new base::FundamentalValue(true),
1545 UpdateProviderPolicy(policies
);
1546 // Reloading the page shouldn't trigger the infobar this time.
1547 ui_test_utils::NavigateToURL(browser(), url
);
1548 EXPECT_EQ(0u, infobar_service
->infobar_count());
1549 // And the plugin started automatically.
1550 EXPECT_EQ(1, CountPlugins());
1553 IN_PROC_BROWSER_TEST_F(PolicyTest
, DeveloperToolsDisabled
) {
1554 // Verifies that access to the developer tools can be disabled.
1557 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1558 content::WebContents
* contents
=
1559 browser()->tab_strip_model()->GetActiveWebContents();
1560 DevToolsWindow
* devtools_window
=
1561 DevToolsWindow::GetInstanceForInspectedWebContents(contents
);
1562 EXPECT_TRUE(devtools_window
);
1564 // Disable devtools via policy.
1566 policies
.Set(key::kDeveloperToolsDisabled
,
1567 POLICY_LEVEL_MANDATORY
,
1569 POLICY_SOURCE_CLOUD
,
1570 new base::FundamentalValue(true),
1572 content::WindowedNotificationObserver
close_observer(
1573 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
1574 content::Source
<content::WebContents
>(
1575 DevToolsWindowTesting::Get(devtools_window
)->main_web_contents()));
1576 UpdateProviderPolicy(policies
);
1577 // wait for devtools close
1578 close_observer
.Wait();
1579 // The existing devtools window should have closed.
1580 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1581 // And it's not possible to open it again.
1582 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1583 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1586 // TODO(samarth): remove along with rest of NTP4 code.
1587 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_WebStoreIconHidden
) {
1588 #if defined(OS_WIN) && defined(USE_ASH)
1589 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1590 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1591 switches::kAshBrowserTests
))
1595 // Verifies that the web store icons can be hidden from the new tab page.
1597 // Open new tab page and look for the web store icons.
1598 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1599 content::WebContents
* contents
=
1600 browser()->tab_strip_model()->GetActiveWebContents();
1602 #if !defined(OS_CHROMEOS)
1603 // Look for web store's app ID in the apps page.
1604 EXPECT_TRUE(ContainsVisibleElement(contents
,
1605 "ahfgeienlihckogmohjhadlkjgocpleb"));
1608 // The next NTP has no footer.
1609 if (ContainsVisibleElement(contents
, "footer"))
1610 EXPECT_TRUE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1612 // Turn off the web store icons.
1614 policies
.Set(key::kHideWebStoreIcon
,
1615 POLICY_LEVEL_MANDATORY
,
1617 POLICY_SOURCE_CLOUD
,
1618 new base::FundamentalValue(true),
1620 UpdateProviderPolicy(policies
);
1622 // The web store icons should now be hidden.
1623 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1624 EXPECT_FALSE(ContainsVisibleElement(contents
,
1625 "ahfgeienlihckogmohjhadlkjgocpleb"));
1626 EXPECT_FALSE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1629 IN_PROC_BROWSER_TEST_F(PolicyTest
, DownloadDirectory
) {
1630 // Verifies that the download directory can be forced by policy.
1632 // Set the initial download directory.
1633 base::ScopedTempDir initial_dir
;
1634 ASSERT_TRUE(initial_dir
.CreateUniqueTempDir());
1635 browser()->profile()->GetPrefs()->SetFilePath(
1636 prefs::kDownloadDefaultDirectory
, initial_dir
.path());
1637 // Don't prompt for the download location during this test.
1638 browser()->profile()->GetPrefs()->SetBoolean(
1639 prefs::kPromptForDownload
, false);
1641 // Verify that downloads end up on the default directory.
1642 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1643 DownloadAndVerifyFile(browser(), initial_dir
.path(), file
);
1644 base::DieFileDie(initial_dir
.path().Append(file
), false);
1646 // Override the download directory with the policy and verify a download.
1647 base::ScopedTempDir forced_dir
;
1648 ASSERT_TRUE(forced_dir
.CreateUniqueTempDir());
1650 policies
.Set(key::kDownloadDirectory
,
1651 POLICY_LEVEL_MANDATORY
,
1653 POLICY_SOURCE_CLOUD
,
1654 new base::StringValue(forced_dir
.path().value()),
1656 UpdateProviderPolicy(policies
);
1657 DownloadAndVerifyFile(browser(), forced_dir
.path(), file
);
1658 // Verify that the first download location wasn't affected.
1659 EXPECT_FALSE(base::PathExists(initial_dir
.path().Append(file
)));
1662 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSelective
) {
1663 // Verifies that blacklisted extensions can't be installed.
1664 ExtensionService
* service
= extension_service();
1665 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1666 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1667 base::ListValue blacklist
;
1668 blacklist
.Append(new base::StringValue(kGoodCrxId
));
1670 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1671 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
1673 UpdateProviderPolicy(policies
);
1675 // "good.crx" is blacklisted.
1676 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1677 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1679 // "adblock.crx" is not.
1680 const extensions::Extension
* adblock
= InstallExtension(kAdBlockCrxName
);
1681 ASSERT_TRUE(adblock
);
1682 EXPECT_EQ(kAdBlockCrxId
, adblock
->id());
1684 service
->GetExtensionById(kAdBlockCrxId
, true));
1687 // Flaky on windows; http://crbug.com/307994.
1689 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1691 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1693 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallBlacklistWildcard
) {
1694 // Verify that a wildcard blacklist takes effect.
1695 EXPECT_TRUE(InstallExtension(kAdBlockCrxName
));
1696 ExtensionService
* service
= extension_service();
1697 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1698 ASSERT_TRUE(service
->GetExtensionById(kAdBlockCrxId
, true));
1699 base::ListValue blacklist
;
1700 blacklist
.Append(new base::StringValue("*"));
1702 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1703 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
1705 UpdateProviderPolicy(policies
);
1707 // AdBlock was automatically removed.
1708 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1710 // And can't be installed again, nor can good.crx.
1711 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1712 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1713 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1714 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1717 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSharedModules
) {
1718 // Verifies that shared_modules are not affected by the blacklist.
1720 const char kImporterId
[] = "pchakhniekfaeoddkifplhnfbffomabh";
1721 const char kSharedModuleId
[] = "nfgclafboonjbiafbllihiailjlhelpm";
1723 // Make sure that "import" and "export" are available to these extension IDs
1724 // by mocking the release channel.
1725 extensions::ScopedCurrentChannel
channel(version_info::Channel::DEV
);
1727 // Verify that the extensions are not installed initially.
1728 ExtensionService
* service
= extension_service();
1729 ASSERT_FALSE(service
->GetExtensionById(kImporterId
, true));
1730 ASSERT_FALSE(service
->GetExtensionById(kSharedModuleId
, true));
1732 // Mock the webstore update URL. This is where the shared module extension
1733 // will be installed from.
1734 base::FilePath update_xml_path
= base::FilePath(kTestExtensionsDir
)
1735 .AppendASCII("policy_shared_module")
1736 .AppendASCII("update.xml");
1737 GURL
update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path
));
1738 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1739 switches::kAppsGalleryUpdateURL
, update_xml_url
.spec());
1740 ui_test_utils::NavigateToURL(browser(), update_xml_url
);
1742 // Blacklist "*" but force-install the importer extension. The shared module
1743 // should be automatically installed too.
1744 base::ListValue blacklist
;
1745 blacklist
.AppendString("*");
1746 base::ListValue forcelist
;
1747 forcelist
.AppendString(
1748 base::StringPrintf("%s;%s", kImporterId
, update_xml_url
.spec().c_str()));
1750 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1751 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
1753 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1754 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, forcelist
.DeepCopy(),
1757 extensions::ExtensionRegistry
* registry
=
1758 extensions::ExtensionRegistry::Get(browser()->profile());
1759 extensions::TestExtensionRegistryObserver
observe_importer(
1760 registry
, kImporterId
);
1761 extensions::TestExtensionRegistryObserver
observe_shared_module(
1762 registry
, kSharedModuleId
);
1763 UpdateProviderPolicy(policies
);
1764 observe_importer
.WaitForExtensionLoaded();
1765 observe_shared_module
.WaitForExtensionLoaded();
1767 // Verify that both extensions got installed.
1768 const extensions::Extension
* importer
=
1769 service
->GetExtensionById(kImporterId
, true);
1770 ASSERT_TRUE(importer
);
1771 EXPECT_EQ(kImporterId
, importer
->id());
1772 const extensions::Extension
* shared_module
=
1773 service
->GetExtensionById(kSharedModuleId
, true);
1774 ASSERT_TRUE(shared_module
);
1775 EXPECT_EQ(kSharedModuleId
, shared_module
->id());
1776 EXPECT_TRUE(shared_module
->is_shared_module());
1778 // Verify the dependency.
1779 scoped_ptr
<extensions::ExtensionSet
> set
=
1780 service
->shared_module_service()->GetDependentExtensions(shared_module
);
1782 EXPECT_EQ(1u, set
->size());
1783 EXPECT_TRUE(set
->Contains(importer
->id()));
1785 std::vector
<extensions::SharedModuleInfo::ImportInfo
> imports
=
1786 extensions::SharedModuleInfo::GetImports(importer
);
1787 ASSERT_EQ(1u, imports
.size());
1788 EXPECT_EQ(kSharedModuleId
, imports
[0].extension_id
);
1791 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallWhitelist
) {
1792 // Verifies that the whitelist can open exceptions to the blacklist.
1793 ExtensionService
* service
= extension_service();
1794 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1795 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1796 base::ListValue blacklist
;
1797 blacklist
.Append(new base::StringValue("*"));
1798 base::ListValue whitelist
;
1799 whitelist
.Append(new base::StringValue(kGoodCrxId
));
1801 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1802 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
1804 policies
.Set(key::kExtensionInstallWhitelist
, POLICY_LEVEL_MANDATORY
,
1805 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, whitelist
.DeepCopy(),
1807 UpdateProviderPolicy(policies
);
1808 // "adblock.crx" is blacklisted.
1809 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1810 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1811 // "good.crx" has a whitelist exception.
1812 const extensions::Extension
* good
= InstallExtension(kGoodCrxName
);
1814 EXPECT_EQ(kGoodCrxId
, good
->id());
1815 EXPECT_EQ(good
, service
->GetExtensionById(kGoodCrxId
, true));
1816 // The user can also remove this extension.
1817 UninstallExtension(kGoodCrxId
, true);
1820 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallForcelist
) {
1821 // Verifies that extensions that are force-installed by policies are
1822 // installed and can't be uninstalled.
1823 ExtensionService
* service
= extension_service();
1824 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1826 // Extensions that are force-installed come from an update URL, which defaults
1827 // to the webstore. Use a mock URL for this test with an update manifest
1828 // that includes "good_v1.crx".
1829 base::FilePath path
=
1830 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1831 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1833 // Setting the forcelist extension should install "good_v1.crx".
1834 base::ListValue forcelist
;
1835 forcelist
.Append(new base::StringValue(
1836 base::StringPrintf("%s;%s", kGoodCrxId
, url
.spec().c_str())));
1838 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1839 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, forcelist
.DeepCopy(),
1841 content::WindowedNotificationObserver
observer(
1842 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1843 content::NotificationService::AllSources());
1844 UpdateProviderPolicy(policies
);
1846 // Note: Cannot check that the notification details match the expected
1847 // exception, since the details object has already been freed prior to
1848 // the completion of observer.Wait().
1850 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1852 // The user is not allowed to uninstall force-installed extensions.
1853 UninstallExtension(kGoodCrxId
, false);
1855 // The user is not allowed to load an unpacked extension with the
1856 // same ID as a force-installed extension.
1857 LoadUnpackedExtension(kGoodUnpackedExt
, false);
1859 // Loading other unpacked extensions are not blocked.
1860 LoadUnpackedExtension(kAppUnpackedExt
, true);
1862 const std::string old_version_number
=
1863 service
->GetExtensionById(kGoodCrxId
, true)->version()->GetString();
1865 base::FilePath test_path
;
1866 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1868 TestRequestInterceptor
interceptor(
1870 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1871 interceptor
.PushJobCallback(
1872 TestRequestInterceptor::FileJob(
1873 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1875 // Updating the force-installed extension.
1876 extensions::ExtensionUpdater
* updater
= service
->updater();
1877 extensions::ExtensionUpdater::CheckParams params
;
1878 params
.install_immediately
= true;
1879 content::WindowedNotificationObserver
update_observer(
1880 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1881 content::NotificationService::AllSources());
1882 updater
->CheckNow(params
);
1883 update_observer
.Wait();
1885 const base::Version
* new_version
=
1886 service
->GetExtensionById(kGoodCrxId
, true)->version();
1887 ASSERT_TRUE(new_version
->IsValid());
1888 base::Version
old_version(old_version_number
);
1889 ASSERT_TRUE(old_version
.IsValid());
1891 EXPECT_EQ(1, new_version
->CompareTo(old_version
));
1893 EXPECT_EQ(0u, interceptor
.GetPendingSize());
1895 // Wait until any background pages belonging to force-installed extensions
1896 // have been loaded.
1897 extensions::ProcessManager
* manager
=
1898 extensions::ProcessManager::Get(browser()->profile());
1899 extensions::ProcessManager::FrameSet all_frames
= manager
->GetAllFrames();
1900 for (extensions::ProcessManager::FrameSet::const_iterator iter
=
1902 iter
!= all_frames
.end();) {
1903 content::WebContents
* web_contents
=
1904 content::WebContents::FromRenderFrameHost(*iter
);
1905 ASSERT_TRUE(web_contents
);
1906 if (!web_contents
->IsLoading()) {
1909 WebContentsLoadedOrDestroyedWatcher(web_contents
).Wait();
1911 // Test activity may have modified the set of extension processes during
1912 // message processing, so re-start the iteration to catch added/removed
1914 all_frames
= manager
->GetAllFrames();
1915 iter
= all_frames
.begin();
1919 // Test policy-installed extensions are reloaded when killed.
1920 BackgroundContentsService::
1921 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1922 content::WindowedNotificationObserver
extension_crashed_observer(
1923 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
1924 content::NotificationService::AllSources());
1925 content::WindowedNotificationObserver
extension_loaded_observer(
1926 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1927 content::NotificationService::AllSources());
1928 extensions::ExtensionHost
* extension_host
=
1929 extensions::ProcessManager::Get(browser()->profile())
1930 ->GetBackgroundHostForExtension(kGoodCrxId
);
1931 extension_host
->render_process_host()->Shutdown(content::RESULT_CODE_KILLED
,
1933 extension_crashed_observer
.Wait();
1934 extension_loaded_observer
.Wait();
1937 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionRecommendedInstallationMode
) {
1938 // Verifies that extensions that are recommended-installed by policies are
1939 // installed, can be disabled but not uninstalled.
1940 ExtensionService
* service
= extension_service();
1941 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1943 base::FilePath path
=
1944 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1945 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1947 // Setting the forcelist extension should install "good_v1.crx".
1948 base::DictionaryValue dict_value
;
1949 dict_value
.SetString(std::string(kGoodCrxId
) + "." +
1950 extensions::schema_constants::kInstallationMode
,
1951 extensions::schema_constants::kNormalInstalled
);
1952 dict_value
.SetString(
1953 std::string(kGoodCrxId
) + "." + extensions::schema_constants::kUpdateUrl
,
1956 policies
.Set(key::kExtensionSettings
,
1957 POLICY_LEVEL_MANDATORY
,
1959 POLICY_SOURCE_CLOUD
,
1960 dict_value
.DeepCopy(),
1962 content::WindowedNotificationObserver
observer(
1963 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1964 content::NotificationService::AllSources());
1965 UpdateProviderPolicy(policies
);
1968 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1970 // The user is not allowed to uninstall recommended-installed extensions.
1971 UninstallExtension(kGoodCrxId
, false);
1973 // Explictly re-enables the extension.
1974 service
->EnableExtension(kGoodCrxId
);
1976 // But the user is allowed to disable them.
1977 EXPECT_TRUE(service
->IsExtensionEnabled(kGoodCrxId
));
1978 DisableExtension(kGoodCrxId
);
1979 EXPECT_FALSE(service
->IsExtensionEnabled(kGoodCrxId
));
1982 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionAllowedTypes
) {
1983 // Verifies that extensions are blocked if policy specifies an allowed types
1984 // list and the extension's type is not on that list.
1985 ExtensionService
* service
= extension_service();
1986 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1987 ASSERT_FALSE(service
->GetExtensionById(kHostedAppCrxId
, true));
1989 base::ListValue allowed_types
;
1990 allowed_types
.AppendString("hosted_app");
1992 policies
.Set(key::kExtensionAllowedTypes
, POLICY_LEVEL_MANDATORY
,
1993 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, allowed_types
.DeepCopy(),
1995 UpdateProviderPolicy(policies
);
1997 // "good.crx" is blocked.
1998 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1999 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
2001 // "hosted_app.crx" is of a whitelisted type.
2002 const extensions::Extension
* hosted_app
= InstallExtension(kHostedAppCrxName
);
2003 ASSERT_TRUE(hosted_app
);
2004 EXPECT_EQ(kHostedAppCrxId
, hosted_app
->id());
2005 EXPECT_EQ(hosted_app
, service
->GetExtensionById(kHostedAppCrxId
, true));
2007 // The user can remove the extension.
2008 UninstallExtension(kHostedAppCrxId
, true);
2011 // Checks that a click on an extension CRX download triggers the extension
2012 // installation prompt without further user interaction when the source is
2013 // whitelisted by policy.
2014 // Flaky on windows; http://crbug.com/295729 .
2016 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
2018 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
2020 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallSources
) {
2021 extensions::ScopedTestDialogAutoConfirm
auto_confirm(
2022 extensions::ScopedTestDialogAutoConfirm::ACCEPT
);
2024 const GURL
install_source_url(URLRequestMockHTTPJob::GetMockUrl(
2025 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
2026 const GURL
referrer_url(URLRequestMockHTTPJob::GetMockUrl(
2027 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
2029 base::ScopedTempDir download_directory
;
2030 ASSERT_TRUE(download_directory
.CreateUniqueTempDir());
2031 DownloadPrefs
* download_prefs
=
2032 DownloadPrefs::FromBrowserContext(browser()->profile());
2033 download_prefs
->SetDownloadPath(download_directory
.path());
2035 const GURL
download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
2036 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
2037 ui_test_utils::NavigateToURL(browser(), download_page_url
);
2039 // As long as the policy is not present, extensions are considered dangerous.
2040 content::DownloadTestObserverTerminal
download_observer(
2041 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
2042 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
);
2044 download_observer
.WaitForFinished();
2046 // Install the policy and trigger another download.
2047 base::ListValue install_sources
;
2048 install_sources
.AppendString(install_source_url
.spec());
2049 install_sources
.AppendString(referrer_url
.spec());
2051 policies
.Set(key::kExtensionInstallSources
, POLICY_LEVEL_MANDATORY
,
2052 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
,
2053 install_sources
.DeepCopy(), nullptr);
2054 UpdateProviderPolicy(policies
);
2056 content::WindowedNotificationObserver
observer(
2057 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2058 content::NotificationService::AllSources());
2061 // Note: Cannot check that the notification details match the expected
2062 // exception, since the details object has already been freed prior to
2063 // the completion of observer.Wait().
2065 // The first extension shouldn't be present, the second should be there.
2066 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId
, true));
2067 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId
, false));
2070 // Verifies that extensions with version older than the minimum version required
2071 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
2072 // policy changes as well as regular auto-updater scheduled updates.
2073 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequired
) {
2074 ExtensionService
* service
= extension_service();
2075 extensions::ExtensionRegistry
* registry
=
2076 extensions::ExtensionRegistry::Get(browser()->profile());
2077 extensions::ExtensionPrefs
* extension_prefs
=
2078 extensions::ExtensionPrefs::Get(browser()->profile());
2080 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2081 service
->updater()->StopTimerForTesting();
2083 // Setup interceptor for extension updates.
2084 base::FilePath test_path
;
2085 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2086 TestRequestInterceptor
interceptor(
2088 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2089 interceptor
.PushJobCallback(TestRequestInterceptor::BadRequestJob());
2090 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2091 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2093 // Install the extension.
2094 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2095 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2097 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2098 // version 1.0.0.0) should still be enabled.
2100 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2101 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.0");
2103 base::RunLoop().RunUntilIdle();
2105 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2107 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2108 // version 1.0.0.0) should now be disabled.
2109 EXPECT_EQ(2u, interceptor
.GetPendingSize());
2110 base::RunLoop service_request_run_loop
;
2111 interceptor
.AddRequestServicedCallback(
2112 service_request_run_loop
.QuitClosure());
2114 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2115 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2117 service_request_run_loop
.Run();
2118 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2120 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2121 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2122 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2124 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2125 // via the update URL in the manifest of the older version.
2126 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2128 content::WindowedNotificationObserver
update_observer(
2129 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2130 content::NotificationService::AllSources());
2131 service
->updater()->CheckSoon();
2132 update_observer
.Wait();
2134 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2136 // The extension should be auto-updated to newer version and re-enabled.
2137 EXPECT_EQ("1.0.0.1",
2138 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2139 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2142 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2144 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequiredAlt
) {
2145 ExtensionService
* service
= extension_service();
2146 extensions::ExtensionRegistry
* registry
=
2147 extensions::ExtensionRegistry::Get(browser()->profile());
2148 extensions::ExtensionPrefs
* extension_prefs
=
2149 extensions::ExtensionPrefs::Get(browser()->profile());
2151 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2152 service
->updater()->StopTimerForTesting();
2154 // Setup interceptor for extension updates.
2155 base::FilePath test_path
;
2156 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2157 TestRequestInterceptor
interceptor(
2159 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2160 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2161 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2163 // Set the policy to require an even higher minimum version this time.
2165 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2166 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.2");
2168 base::RunLoop().RunUntilIdle();
2170 // Install the 1.0.0.0 version, it should be installed but disabled.
2171 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2172 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2173 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2174 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2175 EXPECT_EQ("1.0.0.0",
2176 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2178 // An extension management policy update should trigger an update as well.
2179 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2181 content::WindowedNotificationObserver
update_observer(
2182 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2183 content::NotificationService::AllSources());
2185 // Set a higher minimum version, just intend to trigger a policy update.
2186 extensions::ExtensionManagementPolicyUpdater
management_policy(
2188 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.3");
2190 base::RunLoop().RunUntilIdle();
2191 update_observer
.Wait();
2193 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2195 // It should be updated to 1.0.0.1 but remain disabled.
2196 EXPECT_EQ("1.0.0.1",
2197 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2198 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2199 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2200 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2202 // Remove the minimum version requirement. The extension should be re-enabled.
2204 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2205 management_policy
.UnsetMinimumVersionRequired(kGoodCrxId
);
2207 base::RunLoop().RunUntilIdle();
2209 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2210 EXPECT_FALSE(extension_prefs
->HasDisableReason(
2211 kGoodCrxId
, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
));
2214 // Verifies that a force-installed extension which does not meet a subsequently
2215 // set minimum version requirement is handled well.
2216 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionForceInstalled
) {
2217 extensions::ExtensionRegistry
* registry
=
2218 extensions::ExtensionRegistry::Get(browser()->profile());
2219 extensions::ExtensionPrefs
* extension_prefs
=
2220 extensions::ExtensionPrefs::Get(browser()->profile());
2222 // Prepare the update URL for force installing.
2223 const base::FilePath path
=
2224 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
2225 const GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
2227 // Set policy to force-install the extension, it should be installed and
2229 content::WindowedNotificationObserver
install_observer(
2230 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2231 content::NotificationService::AllSources());
2232 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2234 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2235 management_policy
.SetIndividualExtensionAutoInstalled(kGoodCrxId
,
2238 base::RunLoop().RunUntilIdle();
2239 install_observer
.Wait();
2241 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2243 // Set policy a minimum version of "1.0.0.1", the extension now should be
2246 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2247 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2249 base::RunLoop().RunUntilIdle();
2250 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2251 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2252 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2253 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2256 IN_PROC_BROWSER_TEST_F(PolicyTest
, HomepageLocation
) {
2257 #if defined(OS_WIN) && defined(USE_ASH)
2258 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2259 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2260 switches::kAshBrowserTests
))
2264 // Verifies that the homepage can be configured with policies.
2265 // Set a default, and check that the home button navigates there.
2266 browser()->profile()->GetPrefs()->SetString(
2267 prefs::kHomePage
, chrome::kChromeUIPolicyURL
);
2268 browser()->profile()->GetPrefs()->SetBoolean(
2269 prefs::kHomePageIsNewTabPage
, false);
2270 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
),
2271 browser()->profile()->GetHomePage());
2272 content::WebContents
* contents
=
2273 browser()->tab_strip_model()->GetActiveWebContents();
2274 EXPECT_EQ(GURL(url::kAboutBlankURL
), contents
->GetURL());
2275 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2276 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
), contents
->GetURL());
2278 // Now override with policy.
2280 policies
.Set(key::kHomepageLocation
,
2281 POLICY_LEVEL_MANDATORY
,
2283 POLICY_SOURCE_CLOUD
,
2284 new base::StringValue(chrome::kChromeUICreditsURL
),
2286 UpdateProviderPolicy(policies
);
2287 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2288 content::WaitForLoadStop(contents
);
2289 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL
), contents
->GetURL());
2291 policies
.Set(key::kHomepageIsNewTabPage
,
2292 POLICY_LEVEL_MANDATORY
,
2294 POLICY_SOURCE_CLOUD
,
2295 new base::FundamentalValue(true),
2297 UpdateProviderPolicy(policies
);
2298 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2299 content::WaitForLoadStop(contents
);
2300 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL
), contents
->GetURL());
2303 IN_PROC_BROWSER_TEST_F(PolicyTest
, IncognitoEnabled
) {
2304 // Verifies that incognito windows can't be opened when disabled by policy.
2306 const BrowserList
* active_browser_list
=
2307 BrowserList::GetInstance(chrome::GetActiveDesktop());
2309 // Disable incognito via policy and verify that incognito windows can't be
2311 EXPECT_EQ(1u, active_browser_list
->size());
2312 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2314 policies
.Set(key::kIncognitoEnabled
,
2315 POLICY_LEVEL_MANDATORY
,
2317 POLICY_SOURCE_CLOUD
,
2318 new base::FundamentalValue(false),
2320 UpdateProviderPolicy(policies
);
2321 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2322 EXPECT_EQ(1u, active_browser_list
->size());
2323 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2325 // Enable via policy and verify that incognito windows can be opened.
2326 policies
.Set(key::kIncognitoEnabled
,
2327 POLICY_LEVEL_MANDATORY
,
2329 POLICY_SOURCE_CLOUD
,
2330 new base::FundamentalValue(true),
2332 UpdateProviderPolicy(policies
);
2333 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2334 EXPECT_EQ(2u, active_browser_list
->size());
2335 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2338 IN_PROC_BROWSER_TEST_F(PolicyTest
, Javascript
) {
2339 // Verifies that Javascript can be disabled.
2340 content::WebContents
* contents
=
2341 browser()->tab_strip_model()->GetActiveWebContents();
2342 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2343 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2344 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2345 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2347 // Disable Javascript via policy.
2349 policies
.Set(key::kJavascriptEnabled
,
2350 POLICY_LEVEL_MANDATORY
,
2352 POLICY_SOURCE_CLOUD
,
2353 new base::FundamentalValue(false),
2355 UpdateProviderPolicy(policies
);
2357 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2358 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2359 // Developer tools still work when javascript is disabled.
2360 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2361 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2362 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2363 // Javascript is always enabled for the internal pages.
2364 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL
));
2365 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2367 // The javascript content setting policy overrides the javascript policy.
2368 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2369 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2370 policies
.Set(key::kDefaultJavaScriptSetting
,
2371 POLICY_LEVEL_MANDATORY
,
2373 POLICY_SOURCE_CLOUD
,
2374 new base::FundamentalValue(CONTENT_SETTING_ALLOW
),
2376 UpdateProviderPolicy(policies
);
2377 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2378 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2381 IN_PROC_BROWSER_TEST_F(PolicyTest
, NetworkPrediction
) {
2382 PrefService
* prefs
= browser()->profile()->GetPrefs();
2384 // Enabled by default.
2385 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2387 // Disable by old, deprecated policy.
2389 policies
.Set(key::kDnsPrefetchingEnabled
,
2390 POLICY_LEVEL_MANDATORY
,
2392 POLICY_SOURCE_CLOUD
,
2393 new base::FundamentalValue(false),
2395 UpdateProviderPolicy(policies
);
2397 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs
));
2399 // Enabled by new policy, this should override old one.
2401 key::kNetworkPredictionOptions
,
2402 POLICY_LEVEL_MANDATORY
,
2404 POLICY_SOURCE_CLOUD
,
2405 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS
),
2407 UpdateProviderPolicy(policies
);
2409 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2412 IN_PROC_BROWSER_TEST_F(PolicyTest
, SavingBrowserHistoryDisabled
) {
2413 // Verifies that browsing history is not saved.
2415 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2416 POLICY_LEVEL_MANDATORY
,
2418 POLICY_SOURCE_CLOUD
,
2419 new base::FundamentalValue(true),
2421 UpdateProviderPolicy(policies
);
2422 GURL url
= ui_test_utils::GetTestUrl(
2423 base::FilePath(base::FilePath::kCurrentDirectory
),
2424 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2425 ui_test_utils::NavigateToURL(browser(), url
);
2426 // Verify that the navigation wasn't saved in the history.
2427 ui_test_utils::HistoryEnumerator
enumerator1(browser()->profile());
2428 EXPECT_EQ(0u, enumerator1
.urls().size());
2430 // Now flip the policy and try again.
2431 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2432 POLICY_LEVEL_MANDATORY
,
2434 POLICY_SOURCE_CLOUD
,
2435 new base::FundamentalValue(false),
2437 UpdateProviderPolicy(policies
);
2438 ui_test_utils::NavigateToURL(browser(), url
);
2439 // Verify that the navigation was saved in the history.
2440 ui_test_utils::HistoryEnumerator
enumerator2(browser()->profile());
2441 ASSERT_EQ(1u, enumerator2
.urls().size());
2442 EXPECT_EQ(url
, enumerator2
.urls()[0]);
2445 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2446 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_TranslateEnabled
) {
2447 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2448 if (TranslateService::IsTranslateBubbleEnabled())
2451 scoped_ptr
<test::CldDataHarness
> cld_data_scope
=
2452 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2453 ASSERT_NO_FATAL_FAILURE(cld_data_scope
->Init());
2455 // Verifies that translate can be forced enabled or disabled by policy.
2457 // Get the InfoBarService, and verify that there are no infobars on startup.
2458 content::WebContents
* contents
=
2459 browser()->tab_strip_model()->GetActiveWebContents();
2460 ASSERT_TRUE(contents
);
2461 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
2462 ASSERT_TRUE(infobar_service
);
2463 EXPECT_EQ(0u, infobar_service
->infobar_count());
2465 // Force enable the translate feature.
2467 policies
.Set(key::kTranslateEnabled
,
2468 POLICY_LEVEL_MANDATORY
,
2470 POLICY_SOURCE_CLOUD
,
2471 new base::FundamentalValue(true),
2473 UpdateProviderPolicy(policies
);
2474 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2475 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2476 // TranslateManager observes. This allows checking that an infobar is NOT
2477 // shown below, without polling for infobars for some indeterminate amount
2479 GURL url
= ui_test_utils::GetTestUrl(
2481 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2482 content::WindowedNotificationObserver
language_observer1(
2483 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2484 content::NotificationService::AllSources());
2485 ui_test_utils::NavigateToURL(browser(), url
);
2486 language_observer1
.Wait();
2488 // Verify the translation detected for this tab.
2489 ChromeTranslateClient
* chrome_translate_client
=
2490 ChromeTranslateClient::FromWebContents(contents
);
2491 ASSERT_TRUE(chrome_translate_client
);
2492 translate::LanguageState
& language_state
=
2493 chrome_translate_client
->GetLanguageState();
2494 EXPECT_EQ("fr", language_state
.original_language());
2495 EXPECT_TRUE(language_state
.page_needs_translation());
2496 EXPECT_FALSE(language_state
.translation_pending());
2497 EXPECT_FALSE(language_state
.translation_declined());
2498 EXPECT_FALSE(language_state
.IsPageTranslated());
2500 // Verify that the translate infobar showed up.
2501 ASSERT_EQ(1u, infobar_service
->infobar_count());
2502 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2503 translate::TranslateInfoBarDelegate
* translate_infobar_delegate
=
2504 infobar
->delegate()->AsTranslateInfoBarDelegate();
2505 ASSERT_TRUE(translate_infobar_delegate
);
2506 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE
,
2507 translate_infobar_delegate
->translate_step());
2508 EXPECT_EQ("fr", translate_infobar_delegate
->original_language_code());
2510 // Now force disable translate.
2511 infobar_service
->RemoveInfoBar(infobar
);
2512 EXPECT_EQ(0u, infobar_service
->infobar_count());
2513 policies
.Set(key::kTranslateEnabled
,
2514 POLICY_LEVEL_MANDATORY
,
2516 POLICY_SOURCE_CLOUD
,
2517 new base::FundamentalValue(false),
2519 UpdateProviderPolicy(policies
);
2520 // Navigating to the same URL now doesn't trigger an infobar.
2521 content::WindowedNotificationObserver
language_observer2(
2522 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2523 content::NotificationService::AllSources());
2524 ui_test_utils::NavigateToURL(browser(), url
);
2525 language_observer2
.Wait();
2526 EXPECT_EQ(0u, infobar_service
->infobar_count());
2529 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklist
) {
2530 // Checks that URLs can be blacklisted, and that exceptions can be made to
2533 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2534 // as URLRequestMockHTTPJobs.
2535 const char* kURLS
[] = {
2536 "http://aaa.com/empty.html",
2537 "http://bbb.com/empty.html",
2538 "http://sub.bbb.com/empty.html",
2539 "http://bbb.com/policy/blank.html",
2540 "http://bbb.com./policy/blank.html",
2544 BrowserThread::PostTaskAndReply(
2545 BrowserThread::IO
, FROM_HERE
,
2546 base::Bind(RedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2547 loop
.QuitClosure());
2551 // Verify that "bbb.com" opens before applying the blacklist.
2552 CheckCanOpenURL(browser(), kURLS
[1]);
2555 base::ListValue blacklist
;
2556 blacklist
.Append(new base::StringValue("bbb.com"));
2558 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2559 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
2561 UpdateProviderPolicy(policies
);
2562 FlushBlacklistPolicy();
2563 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2564 CheckCanOpenURL(browser(), kURLS
[0]);
2565 for (size_t i
= 1; i
< arraysize(kURLS
); ++i
)
2566 CheckURLIsBlocked(browser(), kURLS
[i
]);
2568 // Whitelist some sites of bbb.com.
2569 base::ListValue whitelist
;
2570 whitelist
.Append(new base::StringValue("sub.bbb.com"));
2571 whitelist
.Append(new base::StringValue("bbb.com/policy"));
2572 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2573 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, whitelist
.DeepCopy(),
2575 UpdateProviderPolicy(policies
);
2576 FlushBlacklistPolicy();
2577 CheckURLIsBlocked(browser(), kURLS
[1]);
2578 CheckCanOpenURL(browser(), kURLS
[2]);
2579 CheckCanOpenURL(browser(), kURLS
[3]);
2580 CheckCanOpenURL(browser(), kURLS
[4]);
2584 BrowserThread::PostTaskAndReply(
2585 BrowserThread::IO
, FROM_HERE
,
2586 base::Bind(UndoRedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2587 loop
.QuitClosure());
2592 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklistSubresources
) {
2593 // Checks that an image with a blacklisted URL is loaded, but an iframe with a
2594 // blacklisted URL is not.
2596 GURL main_url
= URLRequestMockHTTPJob::GetMockUrl(
2597 base::FilePath(FILE_PATH_LITERAL("policy/blacklist-subresources.html")));
2598 GURL image_url
= URLRequestMockHTTPJob::GetMockUrl(
2599 base::FilePath(FILE_PATH_LITERAL("policy/pixel.png")));
2600 GURL subframe_url
= URLRequestMockHTTPJob::GetMockUrl(
2601 base::FilePath(FILE_PATH_LITERAL("policy/blank.html")));
2603 // Set a blacklist containing the image and the iframe which are used by the
2605 base::ListValue blacklist
;
2606 blacklist
.Append(new base::StringValue(image_url
.spec().c_str()));
2607 blacklist
.Append(new base::StringValue(subframe_url
.spec().c_str()));
2609 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2610 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
2612 UpdateProviderPolicy(policies
);
2613 FlushBlacklistPolicy();
2615 std::string blacklisted_image_load_result
;
2616 ui_test_utils::NavigateToURL(browser(), main_url
);
2617 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2618 browser()->tab_strip_model()->GetActiveWebContents(),
2619 "window.domAutomationController.send(imageLoadResult)",
2620 &blacklisted_image_load_result
));
2621 EXPECT_EQ("success", blacklisted_image_load_result
);
2623 std::string blacklisted_iframe_load_result
;
2624 ui_test_utils::NavigateToURL(browser(), main_url
);
2625 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2626 browser()->tab_strip_model()->GetActiveWebContents(),
2627 "window.domAutomationController.send(iframeLoadResult)",
2628 &blacklisted_iframe_load_result
));
2629 EXPECT_EQ("error", blacklisted_iframe_load_result
);
2632 #if defined(OS_MACOSX)
2633 // http://crbug.com/339240
2634 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2636 #define MAYBE_FileURLBlacklist FileURLBlacklist
2638 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_FileURLBlacklist
) {
2639 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2640 // with URLblacklisting and URLwhitelisting.
2642 base::FilePath test_path
;
2643 PathService::Get(chrome::DIR_TEST_DATA
, &test_path
);
2644 const std::string base_path
= "file://" + test_path
.AsUTF8Unsafe() +"/";
2645 const std::string folder_path
= base_path
+ "apptest/";
2646 const std::string file_path1
= base_path
+ "title1.html";
2647 const std::string file_path2
= folder_path
+ "basic.html";
2649 CheckCanOpenURL(browser(), file_path1
.c_str());
2650 CheckCanOpenURL(browser(), file_path2
.c_str());
2652 // Set a blacklist for all the files.
2653 base::ListValue blacklist
;
2654 blacklist
.Append(new base::StringValue("file://*"));
2656 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2657 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
2659 UpdateProviderPolicy(policies
);
2660 FlushBlacklistPolicy();
2662 CheckURLIsBlocked(browser(), file_path1
.c_str());
2663 CheckURLIsBlocked(browser(), file_path2
.c_str());
2665 // Replace the URLblacklist with disabling the file scheme.
2666 blacklist
.Remove(base::StringValue("file://*"), NULL
);
2667 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2668 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
2670 UpdateProviderPolicy(policies
);
2671 FlushBlacklistPolicy();
2673 PrefService
* prefs
= browser()->profile()->GetPrefs();
2674 const base::ListValue
* list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2675 EXPECT_EQ(list_url
->Find(base::StringValue("file://*")),
2678 base::ListValue disabledscheme
;
2679 disabledscheme
.Append(new base::StringValue("file"));
2680 policies
.Set(key::kDisabledSchemes
, POLICY_LEVEL_MANDATORY
,
2681 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
,
2682 disabledscheme
.DeepCopy(), nullptr);
2683 UpdateProviderPolicy(policies
);
2684 FlushBlacklistPolicy();
2686 list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2687 EXPECT_NE(list_url
->Find(base::StringValue("file://*")),
2690 // Whitelist one folder and blacklist an another just inside.
2691 base::ListValue whitelist
;
2692 whitelist
.Append(new base::StringValue(base_path
));
2693 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2694 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, whitelist
.DeepCopy(),
2696 blacklist
.Append(new base::StringValue(folder_path
));
2697 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2698 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
2700 UpdateProviderPolicy(policies
);
2701 FlushBlacklistPolicy();
2703 CheckCanOpenURL(browser(), file_path1
.c_str());
2704 CheckURLIsBlocked(browser(), file_path2
.c_str());
2709 void GetSSLVersionFallbackMinOnIOThread(
2710 const scoped_refptr
<net::SSLConfigService
>& config_service
,
2711 uint16_t* version_fallback_min
) {
2712 net::SSLConfig config
;
2713 config_service
->GetSSLConfig(&config
);
2714 *version_fallback_min
= config
.version_fallback_min
;
2717 uint16_t GetSSLVersionFallbackMin(Profile
* profile
) {
2718 scoped_refptr
<net::SSLConfigService
> config_service(
2719 profile
->GetSSLConfigService());
2720 uint16_t version_fallback_min
;
2722 BrowserThread::PostTaskAndReply(
2723 BrowserThread::IO
, FROM_HERE
,
2724 base::Bind(&GetSSLVersionFallbackMinOnIOThread
, config_service
,
2725 base::Unretained(&version_fallback_min
)),
2726 loop
.QuitClosure());
2728 return version_fallback_min
;
2733 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionFallbackMin
) {
2734 PrefService
* prefs
= g_browser_process
->local_state();
2736 const std::string
new_value("tls1.2");
2737 const std::string
default_value(
2738 prefs
->GetString(prefs::kSSLVersionFallbackMin
));
2740 EXPECT_NE(default_value
, new_value
);
2741 EXPECT_NE(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2742 GetSSLVersionFallbackMin(browser()->profile()));
2745 policies
.Set(key::kSSLVersionFallbackMin
,
2746 POLICY_LEVEL_MANDATORY
,
2748 POLICY_SOURCE_CLOUD
,
2749 new base::StringValue(new_value
),
2751 UpdateProviderPolicy(policies
);
2753 EXPECT_EQ(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2754 GetSSLVersionFallbackMin(browser()->profile()));
2757 #if !defined(OS_MACOSX)
2758 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedBrowser
) {
2760 policies
.Set(key::kFullscreenAllowed
,
2761 POLICY_LEVEL_MANDATORY
,
2763 POLICY_SOURCE_CLOUD
,
2764 new base::FundamentalValue(false),
2766 UpdateProviderPolicy(policies
);
2768 BrowserWindow
* browser_window
= browser()->window();
2769 ASSERT_TRUE(browser_window
);
2771 EXPECT_FALSE(browser_window
->IsFullscreen());
2772 chrome::ToggleFullscreenMode(browser());
2773 EXPECT_FALSE(browser_window
->IsFullscreen());
2776 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedApp
) {
2778 policies
.Set(key::kFullscreenAllowed
,
2779 POLICY_LEVEL_MANDATORY
,
2781 POLICY_SOURCE_CLOUD
,
2782 new base::FundamentalValue(false),
2784 UpdateProviderPolicy(policies
);
2786 const extensions::Extension
* extension
=
2787 LoadUnpackedExtension(kUnpackedFullscreenAppName
, true);
2788 ASSERT_TRUE(extension
);
2790 // Launch an app that tries to open a fullscreen window.
2791 TestAddAppWindowObserver
add_window_observer(
2792 extensions::AppWindowRegistry::Get(browser()->profile()));
2793 OpenApplication(AppLaunchParams(browser()->profile(), extension
,
2794 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
,
2795 extensions::SOURCE_TEST
));
2796 extensions::AppWindow
* window
= add_window_observer
.WaitForAppWindow();
2797 ASSERT_TRUE(window
);
2799 // Verify that the window is not in fullscreen mode.
2800 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2802 // Verify that the window cannot be toggled into fullscreen mode via apps
2804 EXPECT_TRUE(content::ExecuteScript(
2805 window
->web_contents(),
2806 "chrome.app.window.current().fullscreen();"));
2807 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2809 // Verify that the window cannot be toggled into fullscreen mode from within
2810 // Chrome (e.g., using keyboard accelerators).
2811 window
->Fullscreen();
2812 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2816 #if defined(OS_CHROMEOS)
2818 // Flaky http://crbug.com/476964
2819 #if defined(MEMORY_SANITIZER)
2820 #define MAYBE_DisableScreenshotsFile DISABLED_DisableScreenshotsFile
2822 #define MAYBE_DisableScreenshotsFile DisableScreenshotsFile
2825 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_DisableScreenshotsFile
) {
2826 int screenshot_count
= CountScreenshots();
2828 // Make sure screenshots are counted correctly.
2829 TestScreenshotFile(true);
2830 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2832 // Check if trying to take a screenshot fails when disabled by policy.
2833 TestScreenshotFile(false);
2834 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2837 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableAudioOutput
) {
2838 // Set up the mock observer.
2839 chromeos::CrasAudioHandler
* audio_handler
= chromeos::CrasAudioHandler::Get();
2840 scoped_ptr
<TestAudioObserver
> test_observer(new TestAudioObserver
);
2841 audio_handler
->AddAudioObserver(test_observer
.get());
2843 bool prior_state
= audio_handler
->IsOutputMuted();
2844 // Make sure the audio is not muted and then toggle the policy and observe
2845 // if the output mute changed event is fired.
2846 audio_handler
->SetOutputMute(false);
2847 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2848 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2850 policies
.Set(key::kAudioOutputAllowed
,
2851 POLICY_LEVEL_MANDATORY
,
2853 POLICY_SOURCE_CLOUD
,
2854 new base::FundamentalValue(false),
2856 UpdateProviderPolicy(policies
);
2857 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2858 // This should not change the state now and should not trigger output mute
2860 audio_handler
->SetOutputMute(false);
2861 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2862 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2864 // Toggle back and observe if the output mute changed event is fired.
2865 policies
.Set(key::kAudioOutputAllowed
,
2866 POLICY_LEVEL_MANDATORY
,
2868 POLICY_SOURCE_CLOUD
,
2869 new base::FundamentalValue(true),
2871 UpdateProviderPolicy(policies
);
2872 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2873 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2874 audio_handler
->SetOutputMute(true);
2875 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2876 EXPECT_EQ(2, test_observer
->output_mute_changed_count());
2877 // Revert the prior state.
2878 audio_handler
->SetOutputMute(prior_state
);
2879 audio_handler
->RemoveAudioObserver(test_observer
.get());
2882 // Disabled, see http://crbug.com/315308.
2883 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_PRE_SessionLengthLimit
) {
2884 // Indicate that the session started 2 hours ago and no user activity has
2886 g_browser_process
->local_state()->SetInt64(
2887 prefs::kSessionStartTime
,
2888 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2889 .ToInternalValue());
2892 // Disabled, see http://crbug.com/315308.
2893 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_SessionLengthLimit
) {
2894 content::MockNotificationObserver observer
;
2895 content::NotificationRegistrar registrar
;
2896 registrar
.Add(&observer
,
2897 chrome::NOTIFICATION_APP_TERMINATING
,
2898 content::NotificationService::AllSources());
2900 // Set the session length limit to 3 hours. Verify that the session is not
2902 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2905 policies
.Set(key::kSessionLengthLimit
,
2906 POLICY_LEVEL_MANDATORY
,
2908 POLICY_SOURCE_CLOUD
,
2909 new base::FundamentalValue(kThreeHoursInMs
),
2911 UpdateProviderPolicy(policies
);
2912 base::RunLoop().RunUntilIdle();
2913 Mock::VerifyAndClearExpectations(&observer
);
2915 // Decrease the session length limit to 1 hour. Verify that the session is
2916 // terminated immediately.
2917 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2918 policies
.Set(key::kSessionLengthLimit
,
2919 POLICY_LEVEL_MANDATORY
,
2921 POLICY_SOURCE_CLOUD
,
2922 new base::FundamentalValue(kOneHourInMs
),
2924 UpdateProviderPolicy(policies
);
2925 base::RunLoop().RunUntilIdle();
2926 Mock::VerifyAndClearExpectations(&observer
);
2929 // Disabled, see http://crbug.com/315308.
2930 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2931 DISABLED_PRE_WaitForInitialUserActivityUsatisfied
) {
2932 // Indicate that the session started 2 hours ago and no user activity has
2934 g_browser_process
->local_state()->SetInt64(
2935 prefs::kSessionStartTime
,
2936 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2937 .ToInternalValue());
2940 // Disabled, see http://crbug.com/315308.
2941 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2942 DISABLED_WaitForInitialUserActivityUsatisfied
) {
2943 content::MockNotificationObserver observer
;
2944 content::NotificationRegistrar registrar
;
2945 registrar
.Add(&observer
,
2946 chrome::NOTIFICATION_APP_TERMINATING
,
2947 content::NotificationService::AllSources());
2949 // Require initial user activity.
2951 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2953 POLICY_SOURCE_CLOUD
,
2954 new base::FundamentalValue(true),
2956 UpdateProviderPolicy(policies
);
2957 base::RunLoop().RunUntilIdle();
2959 // Set the session length limit to 1 hour. Verify that the session is not
2961 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2963 policies
.Set(key::kSessionLengthLimit
,
2964 POLICY_LEVEL_MANDATORY
,
2966 POLICY_SOURCE_CLOUD
,
2967 new base::FundamentalValue(kOneHourInMs
),
2969 UpdateProviderPolicy(policies
);
2970 base::RunLoop().RunUntilIdle();
2971 Mock::VerifyAndClearExpectations(&observer
);
2974 // Disabled, see http://crbug.com/315308.
2975 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2976 DISABLED_PRE_WaitForInitialUserActivitySatisfied
) {
2977 // Indicate that initial user activity in this session occurred 2 hours ago.
2978 g_browser_process
->local_state()->SetInt64(
2979 prefs::kSessionStartTime
,
2980 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2981 .ToInternalValue());
2982 g_browser_process
->local_state()->SetBoolean(
2983 prefs::kSessionUserActivitySeen
,
2987 // Disabled, see http://crbug.com/315308.
2988 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2989 DISABLED_WaitForInitialUserActivitySatisfied
) {
2990 content::MockNotificationObserver observer
;
2991 content::NotificationRegistrar registrar
;
2992 registrar
.Add(&observer
,
2993 chrome::NOTIFICATION_APP_TERMINATING
,
2994 content::NotificationService::AllSources());
2996 // Require initial user activity and set the session length limit to 3 hours.
2997 // Verify that the session is not terminated.
2998 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
3001 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
3003 POLICY_SOURCE_CLOUD
,
3004 new base::FundamentalValue(true),
3006 policies
.Set(key::kSessionLengthLimit
,
3007 POLICY_LEVEL_MANDATORY
,
3009 POLICY_SOURCE_CLOUD
,
3010 new base::FundamentalValue(kThreeHoursInMs
),
3012 UpdateProviderPolicy(policies
);
3013 base::RunLoop().RunUntilIdle();
3014 Mock::VerifyAndClearExpectations(&observer
);
3016 // Decrease the session length limit to 1 hour. Verify that the session is
3017 // terminated immediately.
3018 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
3019 policies
.Set(key::kSessionLengthLimit
,
3020 POLICY_LEVEL_MANDATORY
,
3022 POLICY_SOURCE_CLOUD
,
3023 new base::FundamentalValue(kOneHourInMs
),
3025 UpdateProviderPolicy(policies
);
3026 base::RunLoop().RunUntilIdle();
3027 Mock::VerifyAndClearExpectations(&observer
);
3030 IN_PROC_BROWSER_TEST_F(PolicyTest
, LargeCursorEnabled
) {
3031 // Verifies that the large cursor accessibility feature can be controlled
3033 chromeos::AccessibilityManager
* accessibility_manager
=
3034 chromeos::AccessibilityManager::Get();
3036 // Manually enable the large cursor.
3037 accessibility_manager
->EnableLargeCursor(true);
3038 EXPECT_TRUE(accessibility_manager
->IsLargeCursorEnabled());
3040 // Verify that policy overrides the manual setting.
3042 policies
.Set(key::kLargeCursorEnabled
,
3043 POLICY_LEVEL_MANDATORY
,
3045 POLICY_SOURCE_CLOUD
,
3046 new base::FundamentalValue(false),
3048 UpdateProviderPolicy(policies
);
3049 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
3051 // Verify that the large cursor cannot be enabled manually anymore.
3052 accessibility_manager
->EnableLargeCursor(true);
3053 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
3056 IN_PROC_BROWSER_TEST_F(PolicyTest
, SpokenFeedbackEnabled
) {
3057 // Verifies that the spoken feedback accessibility feature can be controlled
3059 chromeos::AccessibilityManager
* accessibility_manager
=
3060 chromeos::AccessibilityManager::Get();
3062 // Manually enable spoken feedback.
3063 accessibility_manager
->EnableSpokenFeedback(
3064 true, ui::A11Y_NOTIFICATION_NONE
);
3065 EXPECT_TRUE(accessibility_manager
->IsSpokenFeedbackEnabled());
3067 // Verify that policy overrides the manual setting.
3069 policies
.Set(key::kSpokenFeedbackEnabled
,
3070 POLICY_LEVEL_MANDATORY
,
3072 POLICY_SOURCE_CLOUD
,
3073 new base::FundamentalValue(false),
3075 UpdateProviderPolicy(policies
);
3076 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
3078 // Verify that spoken feedback cannot be enabled manually anymore.
3079 accessibility_manager
->EnableSpokenFeedback(
3080 true, ui::A11Y_NOTIFICATION_NONE
);
3081 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
3084 IN_PROC_BROWSER_TEST_F(PolicyTest
, HighContrastEnabled
) {
3085 // Verifies that the high contrast mode accessibility feature can be
3086 // controlled through policy.
3087 chromeos::AccessibilityManager
* accessibility_manager
=
3088 chromeos::AccessibilityManager::Get();
3090 // Manually enable high contrast mode.
3091 accessibility_manager
->EnableHighContrast(true);
3092 EXPECT_TRUE(accessibility_manager
->IsHighContrastEnabled());
3094 // Verify that policy overrides the manual setting.
3096 policies
.Set(key::kHighContrastEnabled
,
3097 POLICY_LEVEL_MANDATORY
,
3099 POLICY_SOURCE_CLOUD
,
3100 new base::FundamentalValue(false),
3102 UpdateProviderPolicy(policies
);
3103 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3105 // Verify that high contrast mode cannot be enabled manually anymore.
3106 accessibility_manager
->EnableHighContrast(true);
3107 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3110 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeNone
) {
3111 // Verifies that the screen magnifier can be disabled through policy.
3112 chromeos::MagnificationManager
* magnification_manager
=
3113 chromeos::MagnificationManager::Get();
3115 // Manually enable the full-screen magnifier.
3116 magnification_manager
->SetMagnifierType(ui::MAGNIFIER_FULL
);
3117 magnification_manager
->SetMagnifierEnabled(true);
3118 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3119 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3121 // Verify that policy overrides the manual setting.
3123 policies
.Set(key::kScreenMagnifierType
,
3124 POLICY_LEVEL_MANDATORY
,
3126 POLICY_SOURCE_CLOUD
,
3127 new base::FundamentalValue(0),
3129 UpdateProviderPolicy(policies
);
3130 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3132 // Verify that the screen magnifier cannot be enabled manually anymore.
3133 magnification_manager
->SetMagnifierEnabled(true);
3134 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3137 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeFull
) {
3138 // Verifies that the full-screen magnifier can be enabled through policy.
3139 chromeos::MagnificationManager
* magnification_manager
=
3140 chromeos::MagnificationManager::Get();
3142 // Verify that the screen magnifier is initially disabled.
3143 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3145 // Verify that policy can enable the full-screen magnifier.
3147 policies
.Set(key::kScreenMagnifierType
,
3148 POLICY_LEVEL_MANDATORY
,
3150 POLICY_SOURCE_CLOUD
,
3151 new base::FundamentalValue(ui::MAGNIFIER_FULL
),
3153 UpdateProviderPolicy(policies
);
3154 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3155 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3157 // Verify that the screen magnifier cannot be disabled manually anymore.
3158 magnification_manager
->SetMagnifierEnabled(false);
3159 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3162 IN_PROC_BROWSER_TEST_F(PolicyTest
, AccessibilityVirtualKeyboardEnabled
) {
3163 // Verifies that the on-screen keyboard accessibility feature can be
3164 // controlled through policy.
3165 chromeos::AccessibilityManager
* accessibility_manager
=
3166 chromeos::AccessibilityManager::Get();
3168 // Manually enable the on-screen keyboard.
3169 accessibility_manager
->EnableVirtualKeyboard(true);
3170 EXPECT_TRUE(accessibility_manager
->IsVirtualKeyboardEnabled());
3172 // Verify that policy overrides the manual setting.
3174 policies
.Set(key::kVirtualKeyboardEnabled
,
3175 POLICY_LEVEL_MANDATORY
,
3177 POLICY_SOURCE_CLOUD
,
3178 new base::FundamentalValue(false),
3180 UpdateProviderPolicy(policies
);
3181 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3183 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3184 accessibility_manager
->EnableVirtualKeyboard(true);
3185 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3188 IN_PROC_BROWSER_TEST_F(PolicyTest
, VirtualKeyboardEnabled
) {
3189 // Verify keyboard disabled by default.
3190 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3191 // Verify keyboard can be toggled by default.
3192 keyboard::SetTouchKeyboardEnabled(true);
3193 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3194 keyboard::SetTouchKeyboardEnabled(false);
3195 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3197 // Verify enabling the policy takes effect immediately and that that user
3198 // cannot disable the keyboard..
3200 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3201 POLICY_LEVEL_MANDATORY
,
3203 POLICY_SOURCE_CLOUD
,
3204 new base::FundamentalValue(true),
3206 UpdateProviderPolicy(policies
);
3207 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3208 keyboard::SetTouchKeyboardEnabled(false);
3209 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3211 // Verify that disabling the policy takes effect immediately and that the user
3212 // cannot enable the keyboard.
3213 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3214 POLICY_LEVEL_MANDATORY
,
3216 POLICY_SOURCE_CLOUD
,
3217 new base::FundamentalValue(false),
3219 UpdateProviderPolicy(policies
);
3220 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3221 keyboard::SetTouchKeyboardEnabled(true);
3222 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3229 static const char* kRestoredURLs
[] = {
3230 "http://aaa.com/empty.html",
3231 "http://bbb.com/empty.html",
3234 bool IsNonSwitchArgument(const base::CommandLine::StringType
& s
) {
3235 return s
.empty() || s
[0] != '-';
3240 // Similar to PolicyTest but allows setting policies before the browser is
3241 // created. Each test parameter is a method that sets up the early policies
3242 // and stores the expected startup URLs in |expected_urls_|.
3243 class RestoreOnStartupPolicyTest
3244 : public PolicyTest
,
3245 public testing::WithParamInterface
<
3246 void (RestoreOnStartupPolicyTest::*)(void)> {
3248 RestoreOnStartupPolicyTest() {}
3249 virtual ~RestoreOnStartupPolicyTest() {}
3251 #if defined(OS_CHROMEOS)
3252 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
3253 // TODO(nkostylev): Investigate if we can remove this switch.
3254 command_line
->AppendSwitch(switches::kCreateBrowserOnStartupForTests
);
3255 PolicyTest::SetUpCommandLine(command_line
);
3259 void SetUpInProcessBrowserTestFixture() override
{
3260 PolicyTest::SetUpInProcessBrowserTestFixture();
3261 // Set early policies now, before the browser is created.
3262 (this->*(GetParam()))();
3264 // Remove the non-switch arguments, so that session restore kicks in for
3266 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
3267 base::CommandLine::StringVector argv
= command_line
->argv();
3268 argv
.erase(std::remove_if(++argv
.begin(), argv
.end(), IsNonSwitchArgument
),
3270 command_line
->InitFromArgv(argv
);
3271 ASSERT_TRUE(std::equal(argv
.begin(), argv
.end(),
3272 command_line
->argv().begin()));
3275 void SetUpOnMainThread() override
{
3276 BrowserThread::PostTask(
3280 RedirectHostsToTestData
, kRestoredURLs
, arraysize(kRestoredURLs
)));
3283 void HomepageIsNotNTP() {
3284 // Verifies that policy can set the startup pages to the homepage, when
3285 // the homepage is not the NTP.
3288 key::kRestoreOnStartup
,
3289 POLICY_LEVEL_MANDATORY
,
3291 POLICY_SOURCE_CLOUD
,
3292 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3294 policies
.Set(key::kHomepageIsNewTabPage
,
3295 POLICY_LEVEL_MANDATORY
,
3297 POLICY_SOURCE_CLOUD
,
3298 new base::FundamentalValue(false),
3300 policies
.Set(key::kHomepageLocation
,
3301 POLICY_LEVEL_MANDATORY
,
3303 POLICY_SOURCE_CLOUD
,
3304 new base::StringValue(kRestoredURLs
[1]),
3306 provider_
.UpdateChromePolicy(policies
);
3308 expected_urls_
.push_back(GURL(kRestoredURLs
[1]));
3311 void HomepageIsNTP() {
3312 // Verifies that policy can set the startup pages to the homepage, when
3313 // the homepage is the NTP.
3316 key::kRestoreOnStartup
,
3317 POLICY_LEVEL_MANDATORY
,
3319 POLICY_SOURCE_CLOUD
,
3320 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3322 policies
.Set(key::kHomepageIsNewTabPage
,
3323 POLICY_LEVEL_MANDATORY
,
3325 POLICY_SOURCE_CLOUD
,
3326 new base::FundamentalValue(true),
3328 provider_
.UpdateChromePolicy(policies
);
3330 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3334 // Verifies that policy can set the startup pages to a list of URLs.
3335 base::ListValue urls
;
3336 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
) {
3337 urls
.Append(new base::StringValue(kRestoredURLs
[i
]));
3338 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3341 policies
.Set(key::kRestoreOnStartup
,
3342 POLICY_LEVEL_MANDATORY
,
3344 POLICY_SOURCE_CLOUD
,
3345 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs
),
3348 key::kRestoreOnStartupURLs
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3349 POLICY_SOURCE_CLOUD
, urls
.DeepCopy(), nullptr);
3350 provider_
.UpdateChromePolicy(policies
);
3354 // Verifies that policy can set the startup page to the NTP.
3357 key::kRestoreOnStartup
,
3358 POLICY_LEVEL_MANDATORY
,
3360 POLICY_SOURCE_CLOUD
,
3361 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab
),
3363 provider_
.UpdateChromePolicy(policies
);
3364 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3368 // Verifies that policy can set the startup pages to the last session.
3370 policies
.Set(key::kRestoreOnStartup
,
3371 POLICY_LEVEL_MANDATORY
,
3373 POLICY_SOURCE_CLOUD
,
3374 new base::FundamentalValue(SessionStartupPref::kPrefValueLast
),
3376 provider_
.UpdateChromePolicy(policies
);
3377 // This should restore the tabs opened at PRE_RunTest below.
3378 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
)
3379 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3382 std::vector
<GURL
> expected_urls_
;
3385 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, PRE_RunTest
) {
3386 // Open some tabs to verify if they are restored after the browser restarts.
3387 // Most policy settings override this, except kPrefValueLast which enforces
3389 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs
[0]));
3390 for (size_t i
= 1; i
< arraysize(kRestoredURLs
); ++i
) {
3391 content::WindowedNotificationObserver
observer(
3392 content::NOTIFICATION_LOAD_STOP
,
3393 content::NotificationService::AllSources());
3394 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs
[i
]),
3395 ui::PAGE_TRANSITION_LINK
);
3400 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, RunTest
) {
3401 #if defined(OS_WIN) && defined(USE_ASH)
3402 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3403 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3404 switches::kAshBrowserTests
))
3408 TabStripModel
* model
= browser()->tab_strip_model();
3409 int size
= static_cast<int>(expected_urls_
.size());
3410 EXPECT_EQ(size
, model
->count());
3411 for (int i
= 0; i
< size
&& i
< model
->count(); ++i
) {
3412 EXPECT_EQ(expected_urls_
[i
], model
->GetWebContentsAt(i
)->GetURL());
3416 INSTANTIATE_TEST_CASE_P(
3417 RestoreOnStartupPolicyTestInstance
,
3418 RestoreOnStartupPolicyTest
,
3419 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP
,
3420 &RestoreOnStartupPolicyTest::HomepageIsNTP
,
3421 &RestoreOnStartupPolicyTest::ListOfURLs
,
3422 &RestoreOnStartupPolicyTest::NTP
,
3423 &RestoreOnStartupPolicyTest::Last
));
3425 // Similar to PolicyTest but sets a couple of policies before the browser is
3427 class PolicyStatisticsCollectorTest
: public PolicyTest
{
3429 PolicyStatisticsCollectorTest() {}
3430 ~PolicyStatisticsCollectorTest() override
{}
3432 void SetUpInProcessBrowserTestFixture() override
{
3433 PolicyTest::SetUpInProcessBrowserTestFixture();
3435 policies
.Set(key::kShowHomeButton
,
3436 POLICY_LEVEL_MANDATORY
,
3438 POLICY_SOURCE_CLOUD
,
3439 new base::FundamentalValue(true),
3441 policies
.Set(key::kBookmarkBarEnabled
,
3442 POLICY_LEVEL_MANDATORY
,
3444 POLICY_SOURCE_CLOUD
,
3445 new base::FundamentalValue(false),
3447 policies
.Set(key::kHomepageLocation
,
3448 POLICY_LEVEL_MANDATORY
,
3450 POLICY_SOURCE_CLOUD
,
3451 new base::StringValue("http://chromium.org"),
3453 provider_
.UpdateChromePolicy(policies
);
3457 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest
, Startup
) {
3458 // Verifies that policy usage histograms are collected at startup.
3460 // BrowserPolicyConnector::Init() has already been called. Make sure the
3461 // CompleteInitialization() task has executed as well.
3462 content::RunAllPendingInMessageLoop();
3464 GURL kAboutHistograms
= GURL(std::string(url::kAboutScheme
) +
3465 std::string(url::kStandardSchemeSeparator
) +
3466 std::string(content::kChromeUIHistogramHost
));
3467 ui_test_utils::NavigateToURL(browser(), kAboutHistograms
);
3468 content::WebContents
* contents
=
3469 browser()->tab_strip_model()->GetActiveWebContents();
3471 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3473 "var nodes = document.querySelectorAll('body > pre');"
3475 "for (var i = 0; i < nodes.length; ++i) {"
3476 " var text = nodes[i].innerHTML;"
3477 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3482 "domAutomationController.send(result);",
3484 ASSERT_FALSE(text
.empty());
3485 const std::string kExpectedLabel
=
3486 "Histogram: Enterprise.Policies recorded 3 samples";
3487 EXPECT_EQ(kExpectedLabel
, text
.substr(0, kExpectedLabel
.size()));
3488 // HomepageLocation has policy ID 1.
3489 EXPECT_NE(std::string::npos
, text
.find("<br>1 ---"));
3490 // ShowHomeButton has policy ID 35.
3491 EXPECT_NE(std::string::npos
, text
.find("<br>35 ---"));
3492 // BookmarkBarEnabled has policy ID 82.
3493 EXPECT_NE(std::string::npos
, text
.find("<br>82 ---"));
3496 class MediaStreamDevicesControllerBrowserTest
3497 : public PolicyTest
,
3498 public testing::WithParamInterface
<bool> {
3500 MediaStreamDevicesControllerBrowserTest()
3501 : request_url_allowed_via_whitelist_(false),
3502 request_url_("http://www.example.com/foo") {
3503 policy_value_
= GetParam();
3505 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3507 // Configure a given policy map. The |policy_name| is the name of either the
3508 // audio or video capture allow policy and must never be NULL.
3509 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3510 // policy is set. If non-NULL, the whitelist policy is set to contain either
3511 // the |allow_rule| (if non-NULL) or an "allow all" wildcard.
3512 void ConfigurePolicyMap(PolicyMap
* policies
, const char* policy_name
,
3513 const char* whitelist_policy
,
3514 const char* allow_rule
) {
3515 policies
->Set(policy_name
,
3516 POLICY_LEVEL_MANDATORY
,
3518 POLICY_SOURCE_CLOUD
,
3519 new base::FundamentalValue(policy_value_
),
3522 if (whitelist_policy
) {
3523 // Add an entry to the whitelist that allows the specified URL regardless
3524 // of the setting of kAudioCapturedAllowed.
3525 base::ListValue
* list
= new base::ListValue();
3527 list
->AppendString(allow_rule
);
3528 request_url_allowed_via_whitelist_
= true;
3530 list
->AppendString(ContentSettingsPattern::Wildcard().ToString());
3531 // We should ignore all wildcard entries in the whitelist, so even
3532 // though we've added an entry, it should be ignored and our expectation
3533 // is that the request has not been allowed via the whitelist.
3534 request_url_allowed_via_whitelist_
= false;
3536 policies
->Set(whitelist_policy
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3537 POLICY_SOURCE_CLOUD
, list
, nullptr);
3541 void Accept(const content::MediaStreamDevices
& devices
,
3542 content::MediaStreamRequestResult result
,
3543 scoped_ptr
<content::MediaStreamUI
> ui
) {
3544 if (policy_value_
|| request_url_allowed_via_whitelist_
) {
3545 ASSERT_EQ(1U, devices
.size());
3546 ASSERT_EQ("fake_dev", devices
[0].id
);
3548 ASSERT_EQ(0U, devices
.size());
3552 void FinishAudioTest() {
3553 content::MediaStreamRequest
request(0, 0, 0,
3554 request_url_
.GetOrigin(), false,
3555 content::MEDIA_DEVICE_ACCESS
,
3556 std::string(), std::string(),
3557 content::MEDIA_DEVICE_AUDIO_CAPTURE
,
3558 content::MEDIA_NO_SERVICE
);
3559 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3560 // and microphone permissions at the same time.
3561 MediaStreamDevicesController
controller(
3562 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3563 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3564 if (controller
.IsAskingForAudio())
3565 controller
.PermissionGranted();
3567 base::MessageLoop::current()->QuitWhenIdle();
3570 void FinishVideoTest() {
3571 content::MediaStreamRequest
request(0, 0, 0,
3572 request_url_
.GetOrigin(), false,
3573 content::MEDIA_DEVICE_ACCESS
,
3576 content::MEDIA_NO_SERVICE
,
3577 content::MEDIA_DEVICE_VIDEO_CAPTURE
);
3578 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3579 // and microphone permissions at the same time.
3580 MediaStreamDevicesController
controller(
3581 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3582 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3583 if (controller
.IsAskingForVideo())
3584 controller
.PermissionGranted();
3586 base::MessageLoop::current()->QuitWhenIdle();
3590 bool request_url_allowed_via_whitelist_
;
3592 static const char kExampleRequestPattern
[];
3596 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern
[] =
3597 "http://[*.]example.com/";
3599 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3600 AudioCaptureAllowed
) {
3601 content::MediaStreamDevices audio_devices
;
3602 content::MediaStreamDevice
fake_audio_device(
3603 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3604 audio_devices
.push_back(fake_audio_device
);
3607 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
, NULL
, NULL
);
3608 UpdateProviderPolicy(policies
);
3610 content::BrowserThread::PostTaskAndReply(
3611 content::BrowserThread::IO
, FROM_HERE
,
3612 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3613 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3615 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3618 base::MessageLoop::current()->Run();
3621 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3622 AudioCaptureAllowedUrls
) {
3623 content::MediaStreamDevices audio_devices
;
3624 content::MediaStreamDevice
fake_audio_device(
3625 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3626 audio_devices
.push_back(fake_audio_device
);
3628 const char* allow_pattern
[] = {
3629 kExampleRequestPattern
,
3630 // This will set an allow-all policy whitelist. Since we do not allow
3631 // setting an allow-all entry in the whitelist, this entry should be ignored
3632 // and therefore the request should be denied.
3636 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3638 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
,
3639 key::kAudioCaptureAllowedUrls
, allow_pattern
[i
]);
3640 UpdateProviderPolicy(policies
);
3642 content::BrowserThread::PostTaskAndReply(
3643 content::BrowserThread::IO
, FROM_HERE
,
3645 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3646 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3649 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3652 base::MessageLoop::current()->Run();
3656 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3657 VideoCaptureAllowed
) {
3658 content::MediaStreamDevices video_devices
;
3659 content::MediaStreamDevice
fake_video_device(
3660 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3661 video_devices
.push_back(fake_video_device
);
3664 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
, NULL
, NULL
);
3665 UpdateProviderPolicy(policies
);
3667 content::BrowserThread::PostTaskAndReply(
3668 content::BrowserThread::IO
, FROM_HERE
,
3669 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3670 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3672 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3675 base::MessageLoop::current()->Run();
3678 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3679 VideoCaptureAllowedUrls
) {
3680 content::MediaStreamDevices video_devices
;
3681 content::MediaStreamDevice
fake_video_device(
3682 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3683 video_devices
.push_back(fake_video_device
);
3685 const char* allow_pattern
[] = {
3686 kExampleRequestPattern
,
3687 // This will set an allow-all policy whitelist. Since we do not allow
3688 // setting an allow-all entry in the whitelist, this entry should be ignored
3689 // and therefore the request should be denied.
3693 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3695 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
,
3696 key::kVideoCaptureAllowedUrls
, allow_pattern
[i
]);
3697 UpdateProviderPolicy(policies
);
3699 content::BrowserThread::PostTaskAndReply(
3700 content::BrowserThread::IO
, FROM_HERE
,
3701 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3702 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3705 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3708 base::MessageLoop::current()->Run();
3712 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance
,
3713 MediaStreamDevicesControllerBrowserTest
,
3716 // Test that when extended reporting opt-in is disabled by policy, the
3717 // opt-in checkbox does not appear on SSL blocking pages.
3718 IN_PROC_BROWSER_TEST_F(PolicyTest
, SafeBrowsingExtendedReportingOptInAllowed
) {
3719 net::SpawnedTestServer
https_server_expired(
3720 net::SpawnedTestServer::TYPE_HTTPS
,
3721 net::SpawnedTestServer::SSLOptions(
3722 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3723 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3724 ASSERT_TRUE(https_server_expired
.Start());
3726 // Set the enterprise policy to disallow opt-in.
3727 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3729 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3731 policies
.Set(key::kSafeBrowsingExtendedReportingOptInAllowed
,
3732 POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
,
3733 new base::FundamentalValue(false), nullptr);
3734 UpdateProviderPolicy(policies
);
3736 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3738 // Navigate to an SSL error page.
3739 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3741 const content::InterstitialPage
* const interstitial
=
3742 content::InterstitialPage::GetInterstitialPage(
3743 browser()->tab_strip_model()->GetActiveWebContents());
3744 ASSERT_TRUE(interstitial
);
3745 ASSERT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3746 content::RenderViewHost
* const rvh
=
3747 interstitial
->GetMainFrame()->GetRenderViewHost();
3750 // Check that the checkbox is not visible.
3752 const std::string command
= base::StringPrintf(
3753 "var node = document.getElementById('extended-reporting-opt-in');"
3755 " window.domAutomationController.send(node.offsetWidth > 0 || "
3756 " node.offsetHeight > 0 ? %d : %d);"
3758 // The node should be present but not visible, so trigger an error
3759 // by sending false if it's not present.
3760 " window.domAutomationController.send(%d);"
3762 SecurityInterstitialPage::CMD_TEXT_FOUND
,
3763 SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
,
3764 SecurityInterstitialPage::CMD_ERROR
);
3765 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(rvh
, command
, &result
));
3766 EXPECT_EQ(SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
, result
);
3769 // Test that when SSL error overriding is allowed by policy (default), the
3770 // proceed link appears on SSL blocking pages.
3771 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingAllowed
) {
3772 net::SpawnedTestServer
https_server_expired(
3773 net::SpawnedTestServer::TYPE_HTTPS
,
3774 net::SpawnedTestServer::SSLOptions(
3775 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3776 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3777 ASSERT_TRUE(https_server_expired
.Start());
3779 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3781 // Policy should allow overriding by default.
3782 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3784 // Policy allows overriding - navigate to an SSL error page and expect the
3786 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3788 const content::InterstitialPage
* const interstitial
=
3789 content::InterstitialPage::GetInterstitialPage(
3790 browser()->tab_strip_model()->GetActiveWebContents());
3791 ASSERT_TRUE(interstitial
);
3792 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3794 // The interstitial should display the proceed link.
3795 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3796 interstitial
, "proceed-link"));
3799 // Test that when SSL error overriding is disallowed by policy, the
3800 // proceed link does not appear on SSL blocking pages and users should not
3801 // be able to proceed.
3802 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingDisallowed
) {
3803 net::SpawnedTestServer
https_server_expired(
3804 net::SpawnedTestServer::TYPE_HTTPS
,
3805 net::SpawnedTestServer::SSLOptions(
3806 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3807 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3808 ASSERT_TRUE(https_server_expired
.Start());
3810 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3811 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3813 // Disallowing the proceed link by setting the policy to |false|.
3815 policies
.Set(key::kSSLErrorOverrideAllowed
, POLICY_LEVEL_MANDATORY
,
3816 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
,
3817 new base::FundamentalValue(false), nullptr);
3818 UpdateProviderPolicy(policies
);
3820 // Policy should not allow overriding anymore.
3821 EXPECT_FALSE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3823 // Policy disallows overriding - navigate to an SSL error page and expect no
3825 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3826 const content::InterstitialPage
* const interstitial
=
3827 content::InterstitialPage::GetInterstitialPage(
3828 browser()->tab_strip_model()->GetActiveWebContents());
3829 ASSERT_TRUE(interstitial
);
3830 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3832 // The interstitial should not display the proceed link.
3833 EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3834 interstitial
, "proceed-link"));
3836 // The interstitial should not proceed, even if the command is sent in
3837 // some other way (e.g., via the keyboard shortcut).
3838 content::InterstitialPageDelegate
* interstitial_delegate
=
3839 content::InterstitialPage::GetInterstitialPage(
3840 browser()->tab_strip_model()->GetActiveWebContents())
3841 ->GetDelegateForTesting();
3842 ASSERT_EQ(SSLBlockingPage::kTypeForTesting
,
3843 interstitial_delegate
->GetTypeForTesting());
3844 SSLBlockingPage
* ssl_delegate
=
3845 static_cast<SSLBlockingPage
*>(interstitial_delegate
);
3846 ssl_delegate
->CommandReceived(
3847 base::IntToString(SecurityInterstitialPage::CMD_PROCEED
));
3848 EXPECT_TRUE(interstitial
);
3849 EXPECT_TRUE(browser()
3851 ->GetActiveWebContents()
3852 ->ShowingInterstitialPage());
3855 #if !defined(OS_CHROMEOS)
3856 // Similar to PolicyTest but sets the proper policy before the browser is
3858 class PolicyVariationsServiceTest
: public PolicyTest
{
3860 void SetUpInProcessBrowserTestFixture() override
{
3861 PolicyTest::SetUpInProcessBrowserTestFixture();
3863 policies
.Set(key::kVariationsRestrictParameter
,
3864 POLICY_LEVEL_MANDATORY
,
3866 POLICY_SOURCE_CLOUD
,
3867 new base::StringValue("restricted"),
3869 provider_
.UpdateChromePolicy(policies
);
3873 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest
, VariationsURLIsValid
) {
3874 const std::string default_variations_url
=
3875 variations::VariationsService::GetDefaultVariationsServerURLForTesting();
3877 // g_browser_process->variations_service() is null by default in Chromium
3878 // builds, so construct a VariationsService locally instead.
3879 scoped_ptr
<variations::VariationsService
> service
=
3880 variations::VariationsService::CreateForTesting(
3881 make_scoped_ptr(new ChromeVariationsServiceClient()),
3882 g_browser_process
->local_state());
3884 const GURL url
= service
->GetVariationsServerURL(
3885 g_browser_process
->local_state(), std::string());
3886 EXPECT_TRUE(base::StartsWith(url
.spec(), default_variations_url
,
3887 base::CompareCase::SENSITIVE
));
3889 EXPECT_TRUE(net::GetValueForKeyInQuery(url
, "restrict", &value
));
3890 EXPECT_EQ("restricted", value
);
3893 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistSelective
) {
3894 base::ListValue blacklist
;
3895 blacklist
.Append(new base::StringValue("host.name"));
3897 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3898 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
3900 UpdateProviderPolicy(policies
);
3902 PrefService
* prefs
= browser()->profile()->GetPrefs();
3903 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3904 prefs
, "host.name"));
3905 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3906 prefs
, "other.host.name"));
3909 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistWildcard
) {
3910 base::ListValue blacklist
;
3911 blacklist
.Append(new base::StringValue("*"));
3913 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3914 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
3916 UpdateProviderPolicy(policies
);
3918 PrefService
* prefs
= browser()->profile()->GetPrefs();
3919 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3920 prefs
, "host.name"));
3921 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3922 prefs
, "other.host.name"));
3925 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingWhitelist
) {
3926 base::ListValue blacklist
;
3927 blacklist
.Append(new base::StringValue("*"));
3928 base::ListValue whitelist
;
3929 whitelist
.Append(new base::StringValue("host.name"));
3931 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3932 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, blacklist
.DeepCopy(),
3934 policies
.Set(key::kNativeMessagingWhitelist
, POLICY_LEVEL_MANDATORY
,
3935 POLICY_SCOPE_USER
, POLICY_SOURCE_CLOUD
, whitelist
.DeepCopy(),
3937 UpdateProviderPolicy(policies
);
3939 PrefService
* prefs
= browser()->profile()->GetPrefs();
3940 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3941 prefs
, "host.name"));
3942 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3943 prefs
, "other.host.name"));
3946 #endif // !defined(CHROME_OS)
3949 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3950 // Sets the hardware acceleration mode policy before the browser is started.
3951 class HardwareAccelerationModePolicyTest
: public PolicyTest
{
3953 HardwareAccelerationModePolicyTest() {}
3955 void SetUpInProcessBrowserTestFixture() override
{
3956 PolicyTest::SetUpInProcessBrowserTestFixture();
3958 policies
.Set(key::kHardwareAccelerationModeEnabled
,
3959 POLICY_LEVEL_MANDATORY
,
3961 POLICY_SOURCE_CLOUD
,
3962 new base::FundamentalValue(false),
3964 provider_
.UpdateChromePolicy(policies
);
3968 IN_PROC_BROWSER_TEST_F(HardwareAccelerationModePolicyTest
,
3969 HardwareAccelerationDisabled
) {
3970 // Verifies that hardware acceleration can be disabled with policy.
3972 content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr));
3974 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3976 #if defined(OS_CHROMEOS)
3977 // Policy is only available in ChromeOS
3978 IN_PROC_BROWSER_TEST_F(PolicyTest
, UnifiedDesktopEnabledByDefault
) {
3979 // Verify that Unified Desktop can be enabled by policy
3980 ash::DisplayManager
*display_manager
=
3981 ash::Shell::GetInstance()->display_manager();
3983 // The policy description promises that Unified Desktop is not available
3984 // unless the policy is set (or a command line or an extension is used). If
3985 // this default behaviour changes, please change the description at
3986 // components/policy/resources/policy_templates.json.
3987 EXPECT_FALSE(display_manager
->unified_desktop_enabled());
3988 // Now set the policy and check that unified desktop is turned on.
3990 policies
.Set(key::kUnifiedDesktopEnabledByDefault
,
3991 POLICY_LEVEL_MANDATORY
,
3993 POLICY_SOURCE_CLOUD
,
3994 new base::FundamentalValue(true),
3996 UpdateProviderPolicy(policies
);
3997 EXPECT_TRUE(display_manager
->unified_desktop_enabled());
3998 policies
.Set(key::kUnifiedDesktopEnabledByDefault
,
3999 POLICY_LEVEL_MANDATORY
,
4001 POLICY_SOURCE_CLOUD
,
4002 new base::FundamentalValue(false),
4004 UpdateProviderPolicy(policies
);
4005 EXPECT_FALSE(display_manager
->unified_desktop_enabled());
4007 #endif // defined(OS_CHROMEOS)
4009 } // namespace policy