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.
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/memory/scoped_ptr.h"
19 #include "base/path_service.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/run_loop.h"
22 #include "base/strings/string16.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_util.h"
25 #include "base/strings/stringprintf.h"
26 #include "base/strings/utf_string_conversions.h"
27 #include "base/test/test_file_util.h"
28 #include "base/threading/sequenced_worker_pool.h"
29 #include "base/time/time.h"
30 #include "base/values.h"
31 #include "chrome/app/chrome_command_ids.h"
32 #include "chrome/browser/background/background_contents_service.h"
33 #include "chrome/browser/browser_process.h"
34 #include "chrome/browser/chrome_notification_types.h"
35 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
36 #include "chrome/browser/devtools/devtools_window_testing.h"
37 #include "chrome/browser/download/download_prefs.h"
38 #include "chrome/browser/extensions/api/messaging/message_service.h"
39 #include "chrome/browser/extensions/crx_installer.h"
40 #include "chrome/browser/extensions/extension_management_constants.h"
41 #include "chrome/browser/extensions/extension_management_test_util.h"
42 #include "chrome/browser/extensions/extension_service.h"
43 #include "chrome/browser/extensions/shared_module_service.h"
44 #include "chrome/browser/extensions/unpacked_installer.h"
45 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
46 #include "chrome/browser/extensions/updater/extension_updater.h"
47 #include "chrome/browser/infobars/infobar_service.h"
48 #include "chrome/browser/interstitials/security_interstitial_page.h"
49 #include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
50 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
51 #include "chrome/browser/media/media_stream_devices_controller.h"
52 #include "chrome/browser/metrics/variations/chrome_variations_service_client.h"
53 #include "chrome/browser/net/prediction_options.h"
54 #include "chrome/browser/net/url_request_mock_util.h"
55 #include "chrome/browser/plugins/plugin_prefs.h"
56 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
57 #include "chrome/browser/policy/profile_policy_connector.h"
58 #include "chrome/browser/policy/profile_policy_connector_factory.h"
59 #include "chrome/browser/prefs/session_startup_pref.h"
60 #include "chrome/browser/profiles/profile.h"
61 #include "chrome/browser/search/instant_service.h"
62 #include "chrome/browser/search/instant_service_factory.h"
63 #include "chrome/browser/search/search.h"
64 #include "chrome/browser/search_engines/template_url_service_factory.h"
65 #include "chrome/browser/ssl/ssl_blocking_page.h"
66 #include "chrome/browser/translate/chrome_translate_client.h"
67 #include "chrome/browser/translate/cld_data_harness.h"
68 #include "chrome/browser/translate/cld_data_harness_factory.h"
69 #include "chrome/browser/translate/translate_service.h"
70 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
71 #include "chrome/browser/ui/browser.h"
72 #include "chrome/browser/ui/browser_commands.h"
73 #include "chrome/browser/ui/browser_list.h"
74 #include "chrome/browser/ui/browser_tabstrip.h"
75 #include "chrome/browser/ui/browser_window.h"
76 #include "chrome/browser/ui/host_desktop.h"
77 #include "chrome/browser/ui/location_bar/location_bar.h"
78 #include "chrome/browser/ui/tabs/tab_strip_model.h"
79 #include "chrome/common/chrome_paths.h"
80 #include "chrome/common/chrome_switches.h"
81 #include "chrome/common/extensions/extension_constants.h"
82 #include "chrome/common/extensions/features/feature_channel.h"
83 #include "chrome/common/pref_names.h"
84 #include "chrome/common/url_constants.h"
85 #include "chrome/grit/generated_resources.h"
86 #include "chrome/test/base/in_process_browser_test.h"
87 #include "chrome/test/base/test_switches.h"
88 #include "chrome/test/base/ui_test_utils.h"
89 #include "components/content_settings/core/common/content_settings.h"
90 #include "components/content_settings/core/common/content_settings_pattern.h"
91 #include "components/infobars/core/infobar.h"
92 #include "components/omnibox/browser/autocomplete_controller.h"
93 #include "components/omnibox/browser/omnibox_edit_model.h"
94 #include "components/omnibox/browser/omnibox_view.h"
95 #include "components/policy/core/browser/browser_policy_connector.h"
96 #include "components/policy/core/common/external_data_fetcher.h"
97 #include "components/policy/core/common/mock_configuration_policy_provider.h"
98 #include "components/policy/core/common/policy_map.h"
99 #include "components/policy/core/common/policy_pref_names.h"
100 #include "components/policy/core/common/policy_service.h"
101 #include "components/policy/core/common/policy_service_impl.h"
102 #include "components/search/search.h"
103 #include "components/search_engines/template_url.h"
104 #include "components/search_engines/template_url_service.h"
105 #include "components/translate/core/browser/language_state.h"
106 #include "components/translate/core/browser/translate_infobar_delegate.h"
107 #include "components/variations/service/variations_service.h"
108 #include "components/version_info/version_info.h"
109 #include "content/public/browser/browser_child_process_host_iterator.h"
110 #include "content/public/browser/browser_context.h"
111 #include "content/public/browser/browser_thread.h"
112 #include "content/public/browser/child_process_data.h"
113 #include "content/public/browser/download_item.h"
114 #include "content/public/browser/download_manager.h"
115 #include "content/public/browser/gpu_data_manager.h"
116 #include "content/public/browser/interstitial_page.h"
117 #include "content/public/browser/notification_details.h"
118 #include "content/public/browser/notification_observer.h"
119 #include "content/public/browser/notification_registrar.h"
120 #include "content/public/browser/notification_service.h"
121 #include "content/public/browser/notification_source.h"
122 #include "content/public/browser/notification_types.h"
123 #include "content/public/browser/plugin_service.h"
124 #include "content/public/browser/render_frame_host.h"
125 #include "content/public/browser/render_process_host.h"
126 #include "content/public/browser/render_view_host.h"
127 #include "content/public/browser/web_contents.h"
128 #include "content/public/common/content_constants.h"
129 #include "content/public/common/content_paths.h"
130 #include "content/public/common/process_type.h"
131 #include "content/public/common/result_codes.h"
132 #include "content/public/common/url_constants.h"
133 #include "content/public/common/webplugininfo.h"
134 #include "content/public/test/browser_test_utils.h"
135 #include "content/public/test/download_test_observer.h"
136 #include "content/public/test/mock_notification_observer.h"
137 #include "content/public/test/test_navigation_observer.h"
138 #include "content/public/test/test_utils.h"
139 #include "extensions/browser/extension_dialog_auto_confirm.h"
140 #include "extensions/browser/extension_host.h"
141 #include "extensions/browser/extension_prefs.h"
142 #include "extensions/browser/extension_registry.h"
143 #include "extensions/browser/extension_system.h"
144 #include "extensions/browser/process_manager.h"
145 #include "extensions/browser/test_extension_registry_observer.h"
146 #include "extensions/browser/uninstall_reason.h"
147 #include "extensions/common/constants.h"
148 #include "extensions/common/extension.h"
149 #include "extensions/common/extension_set.h"
150 #include "extensions/common/manifest_handlers/shared_module_info.h"
151 #include "net/base/net_errors.h"
152 #include "net/base/net_util.h"
153 #include "net/base/url_util.h"
154 #include "net/http/http_stream_factory.h"
155 #include "net/ssl/ssl_config.h"
156 #include "net/ssl/ssl_config_service.h"
157 #include "net/test/spawned_test_server/spawned_test_server.h"
158 #include "net/test/url_request/url_request_failed_job.h"
159 #include "net/test/url_request/url_request_mock_http_job.h"
160 #include "net/url_request/url_request.h"
161 #include "net/url_request/url_request_filter.h"
162 #include "net/url_request/url_request_interceptor.h"
163 #include "policy/policy_constants.h"
164 #include "testing/gmock/include/gmock/gmock.h"
165 #include "testing/gtest/include/gtest/gtest.h"
166 #include "third_party/WebKit/public/web/WebInputEvent.h"
167 #include "ui/base/l10n/l10n_util.h"
168 #include "ui/base/page_transition_types.h"
169 #include "ui/base/resource/resource_bundle.h"
170 #include "url/gurl.h"
172 #if defined(OS_CHROMEOS)
173 #include "ash/accelerators/accelerator_controller.h"
174 #include "ash/accelerators/accelerator_table.h"
175 #include "ash/shell.h"
176 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
177 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
178 #include "chrome/browser/profiles/profile_manager.h"
179 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
180 #include "chromeos/audio/cras_audio_handler.h"
181 #include "ui/chromeos/accessibility_types.h"
182 #include "ui/keyboard/keyboard_util.h"
183 #include "ui/snapshot/screenshot_grabber.h"
186 #if !defined(OS_MACOSX)
187 #include "base/basictypes.h"
188 #include "base/compiler_specific.h"
189 #include "chrome/browser/ui/extensions/app_launch_params.h"
190 #include "chrome/browser/ui/extensions/application_launch.h"
191 #include "extensions/browser/app_window/app_window.h"
192 #include "extensions/browser/app_window/app_window_registry.h"
193 #include "extensions/browser/app_window/native_app_window.h"
194 #include "ui/base/window_open_disposition.h"
197 using content::BrowserThread
;
198 using net::URLRequestMockHTTPJob
;
200 using testing::Return
;
207 #if defined(OS_CHROMEOS)
208 const int kOneHourInMs
= 60 * 60 * 1000;
209 const int kThreeHoursInMs
= 180 * 60 * 1000;
212 const char kURL
[] = "http://example.com";
213 const char kCookieValue
[] = "converted=true";
214 // Assigned to Philip J. Fry to fix eventually.
215 const char kCookieOptions
[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
217 const base::FilePath::CharType kTestExtensionsDir
[] =
218 FILE_PATH_LITERAL("extensions");
219 const base::FilePath::CharType kGoodCrxName
[] = FILE_PATH_LITERAL("good.crx");
220 const base::FilePath::CharType kAdBlockCrxName
[] =
221 FILE_PATH_LITERAL("adblock.crx");
222 const base::FilePath::CharType kHostedAppCrxName
[] =
223 FILE_PATH_LITERAL("hosted_app.crx");
225 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
226 const char kAdBlockCrxId
[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
227 const char kHostedAppCrxId
[] = "kbmnembihfiondgfjekmnmcbddelicoi";
229 const base::FilePath::CharType kGood2CrxManifestName
[] =
230 FILE_PATH_LITERAL("good2_update_manifest.xml");
231 const base::FilePath::CharType kGoodV1CrxManifestName
[] =
232 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
233 const base::FilePath::CharType kGoodV1CrxName
[] =
234 FILE_PATH_LITERAL("good_v1.crx");
235 const base::FilePath::CharType kGoodUnpackedExt
[] =
236 FILE_PATH_LITERAL("good_unpacked");
237 const base::FilePath::CharType kAppUnpackedExt
[] =
238 FILE_PATH_LITERAL("app");
240 #if !defined(OS_MACOSX)
241 const base::FilePath::CharType kUnpackedFullscreenAppName
[] =
242 FILE_PATH_LITERAL("fullscreen_app");
243 #endif // !defined(OS_MACOSX)
245 // Filters requests to the hosts in |urls| and redirects them to the test data
246 // dir through URLRequestMockHTTPJobs.
247 void RedirectHostsToTestData(const char* const urls
[], size_t size
) {
248 // Map the given hosts to the test data dir.
249 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
250 base::FilePath base_path
;
251 PathService::Get(chrome::DIR_TEST_DATA
, &base_path
);
252 for (size_t i
= 0; i
< size
; ++i
) {
253 const GURL
url(urls
[i
]);
254 EXPECT_TRUE(url
.is_valid());
255 filter
->AddUrlInterceptor(url
,
256 URLRequestMockHTTPJob::CreateInterceptor(
257 base_path
, BrowserThread::GetBlockingPool()));
261 // Remove filters for requests to the hosts in |urls|.
262 void UndoRedirectHostsToTestData(const char* const urls
[], size_t size
) {
263 // Map the given hosts to the test data dir.
264 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
265 for (size_t i
= 0; i
< size
; ++i
) {
266 const GURL
url(urls
[i
]);
267 EXPECT_TRUE(url
.is_valid());
268 filter
->RemoveUrlHandler(url
);
272 // Fails requests using ERR_CONNECTION_RESET.
273 class FailedJobInterceptor
: public net::URLRequestInterceptor
{
275 FailedJobInterceptor() {}
276 ~FailedJobInterceptor() override
{}
278 // URLRequestInterceptor implementation:
279 net::URLRequestJob
* MaybeInterceptRequest(
280 net::URLRequest
* request
,
281 net::NetworkDelegate
* network_delegate
) const override
{
282 return new net::URLRequestFailedJob(request
, network_delegate
,
283 net::ERR_CONNECTION_RESET
);
287 DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor
);
290 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
291 class MakeRequestFail
{
293 // Sets up the filter on IO thread such that requests to |host| fail.
294 explicit MakeRequestFail(const std::string
& host
) : host_(host
) {
295 BrowserThread::PostTaskAndReply(
296 BrowserThread::IO
, FROM_HERE
,
297 base::Bind(MakeRequestFailOnIO
, host_
),
298 base::MessageLoop::QuitClosure());
299 content::RunMessageLoop();
302 BrowserThread::PostTaskAndReply(
303 BrowserThread::IO
, FROM_HERE
,
304 base::Bind(UndoMakeRequestFailOnIO
, host_
),
305 base::MessageLoop::QuitClosure());
306 content::RunMessageLoop();
310 // Filters requests to the |host| such that they fail. Run on IO thread.
311 static void MakeRequestFailOnIO(const std::string
& host
) {
312 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
313 filter
->AddHostnameInterceptor(
315 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
316 filter
->AddHostnameInterceptor(
318 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
321 // Remove filters for requests to the |host|. Run on IO thread.
322 static void UndoMakeRequestFailOnIO(const std::string
& host
) {
323 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
324 filter
->RemoveHostnameHandler("http", host
);
325 filter
->RemoveHostnameHandler("https", host
);
328 const std::string host_
;
331 // Verifies that the given url |spec| can be opened. This assumes that |spec|
332 // points at empty.html in the test data dir.
333 void CheckCanOpenURL(Browser
* browser
, const char* spec
) {
335 ui_test_utils::NavigateToURL(browser
, url
);
336 content::WebContents
* contents
=
337 browser
->tab_strip_model()->GetActiveWebContents();
338 EXPECT_EQ(url
, contents
->GetURL());
339 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
340 base::string16 title
=
341 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
342 EXPECT_NE(title
, contents
->GetTitle());
345 // Verifies that access to the given url |spec| is blocked.
346 void CheckURLIsBlocked(Browser
* browser
, const char* spec
) {
348 ui_test_utils::NavigateToURL(browser
, url
);
349 content::WebContents
* contents
=
350 browser
->tab_strip_model()->GetActiveWebContents();
351 EXPECT_EQ(url
, contents
->GetURL());
352 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
353 base::string16 title
=
354 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
355 EXPECT_EQ(title
, contents
->GetTitle());
357 // Verify that the expected error page is being displayed.
359 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
361 "var textContent = document.body.textContent;"
362 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
363 "domAutomationController.send(hasError);",
368 // Downloads a file named |file| and expects it to be saved to |dir|, which
370 void DownloadAndVerifyFile(
371 Browser
* browser
, const base::FilePath
& dir
, const base::FilePath
& file
) {
372 content::DownloadManager
* download_manager
=
373 content::BrowserContext::GetDownloadManager(browser
->profile());
374 content::DownloadTestObserverTerminal
observer(
376 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
377 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
378 base::FilePath downloaded
= dir
.Append(file
);
379 EXPECT_FALSE(base::PathExists(downloaded
));
380 ui_test_utils::NavigateToURL(browser
, url
);
381 observer
.WaitForFinished();
383 1u, observer
.NumDownloadsSeenInState(content::DownloadItem::COMPLETE
));
384 EXPECT_TRUE(base::PathExists(downloaded
));
385 base::FileEnumerator
enumerator(dir
, false, base::FileEnumerator::FILES
);
386 EXPECT_EQ(file
, enumerator
.Next().BaseName());
387 EXPECT_EQ(base::FilePath(), enumerator
.Next());
390 #if defined(OS_CHROMEOS)
391 int CountScreenshots() {
392 DownloadPrefs
* download_prefs
= DownloadPrefs::FromBrowserContext(
393 ProfileManager::GetActiveUserProfile());
394 base::FileEnumerator
enumerator(download_prefs
->DownloadPath(),
395 false, base::FileEnumerator::FILES
,
398 while (!enumerator
.Next().empty())
404 // Checks if WebGL is enabled in the given WebContents.
405 bool IsWebGLEnabled(content::WebContents
* contents
) {
407 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
409 "var canvas = document.createElement('canvas');"
410 "var context = canvas.getContext('webgl');"
411 "domAutomationController.send(context != null);",
416 bool IsJavascriptEnabled(content::WebContents
* contents
) {
417 scoped_ptr
<base::Value
> value
= content::ExecuteScriptAndGetValue(
418 contents
->GetMainFrame(), "123");
420 if (!value
->GetAsInteger(&result
))
421 EXPECT_EQ(base::Value::TYPE_NULL
, value
->GetType());
422 return result
== 123;
425 bool IsNetworkPredictionEnabled(PrefService
* prefs
) {
426 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs
);
429 void CopyPluginListAndQuit(std::vector
<content::WebPluginInfo
>* out
,
430 const std::vector
<content::WebPluginInfo
>& in
) {
432 base::MessageLoop::current()->QuitWhenIdle();
436 void CopyValueAndQuit(T
* out
, T in
) {
438 base::MessageLoop::current()->QuitWhenIdle();
441 void GetPluginList(std::vector
<content::WebPluginInfo
>* plugins
) {
442 content::PluginService
* service
= content::PluginService::GetInstance();
443 service
->GetPlugins(base::Bind(CopyPluginListAndQuit
, plugins
));
444 content::RunMessageLoop();
447 const content::WebPluginInfo
* GetFlashPlugin(
448 const std::vector
<content::WebPluginInfo
>& plugins
) {
449 const content::WebPluginInfo
* flash
= NULL
;
450 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
451 if (plugins
[i
].name
== base::ASCIIToUTF16(content::kFlashPluginName
)) {
456 #if defined(OFFICIAL_BUILD)
457 // Official builds bundle Flash.
461 LOG(INFO
) << "Test skipped because the Flash plugin couldn't be found.";
466 bool SetPluginEnabled(PluginPrefs
* plugin_prefs
,
467 const content::WebPluginInfo
* plugin
,
470 plugin_prefs
->EnablePlugin(enabled
, plugin
->path
,
471 base::Bind(CopyValueAndQuit
<bool>, &ok
));
472 content::RunMessageLoop();
476 int CountPluginsOnIOThread() {
478 for (content::BrowserChildProcessHostIterator iter
; !iter
.Done(); ++iter
) {
479 if (iter
.GetData().process_type
== content::PROCESS_TYPE_PLUGIN
||
480 iter
.GetData().process_type
== content::PROCESS_TYPE_PPAPI_PLUGIN
) {
489 BrowserThread::PostTaskAndReplyWithResult(
490 BrowserThread::IO
, FROM_HERE
,
491 base::Bind(CountPluginsOnIOThread
),
492 base::Bind(CopyValueAndQuit
<int>, &count
));
493 content::RunMessageLoop();
498 void FlushBlacklistPolicy() {
499 // Updates of the URLBlacklist are done on IO, after building the blacklist
500 // on the blocking pool, which is initiated from IO.
501 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
502 BrowserThread::GetBlockingPool()->FlushForTesting();
503 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
506 bool ContainsVisibleElement(content::WebContents
* contents
,
507 const std::string
& id
) {
509 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
511 "var elem = document.getElementById('" + id
+ "');"
512 "domAutomationController.send(!!elem && !elem.hidden);",
517 #if defined(OS_CHROMEOS)
518 class TestAudioObserver
: public chromeos::CrasAudioHandler::AudioObserver
{
520 TestAudioObserver() : output_mute_changed_count_(0) {
523 int output_mute_changed_count() const {
524 return output_mute_changed_count_
;
527 ~TestAudioObserver() override
{}
530 // chromeos::CrasAudioHandler::AudioObserver overrides.
531 void OnOutputMuteChanged(bool /* mute_on */,
532 bool /* system_adjust */) override
{
533 ++output_mute_changed_count_
;
537 int output_mute_changed_count_
;
539 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver
);
543 // This class waits until either a load stops or the WebContents is destroyed.
544 class WebContentsLoadedOrDestroyedWatcher
545 : public content::WebContentsObserver
{
547 explicit WebContentsLoadedOrDestroyedWatcher(
548 content::WebContents
* web_contents
);
549 ~WebContentsLoadedOrDestroyedWatcher() override
;
551 // Waits until the WebContents's load is done or until it is destroyed.
554 // Overridden WebContentsObserver methods.
555 void WebContentsDestroyed() override
;
556 void DidStopLoading() override
;
559 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
561 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher
);
564 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
565 content::WebContents
* web_contents
)
566 : content::WebContentsObserver(web_contents
),
567 message_loop_runner_(new content::MessageLoopRunner
) {
570 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
572 void WebContentsLoadedOrDestroyedWatcher::Wait() {
573 message_loop_runner_
->Run();
576 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
577 message_loop_runner_
->Quit();
580 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
581 message_loop_runner_
->Quit();
584 #if !defined(OS_MACOSX)
586 // Observer used to wait for the creation of a new app window.
587 class TestAddAppWindowObserver
588 : public extensions::AppWindowRegistry::Observer
{
590 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry
* registry
);
591 ~TestAddAppWindowObserver() override
;
593 // extensions::AppWindowRegistry::Observer:
594 void OnAppWindowAdded(extensions::AppWindow
* app_window
) override
;
596 extensions::AppWindow
* WaitForAppWindow();
599 extensions::AppWindowRegistry
* registry_
; // Not owned.
600 extensions::AppWindow
* window_
; // Not owned.
601 base::RunLoop run_loop_
;
603 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver
);
606 TestAddAppWindowObserver::TestAddAppWindowObserver(
607 extensions::AppWindowRegistry
* registry
)
608 : registry_(registry
), window_(NULL
) {
609 registry_
->AddObserver(this);
612 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
613 registry_
->RemoveObserver(this);
616 void TestAddAppWindowObserver::OnAppWindowAdded(
617 extensions::AppWindow
* app_window
) {
618 window_
= app_window
;
622 extensions::AppWindow
* TestAddAppWindowObserver::WaitForAppWindow() {
631 class PolicyTest
: public InProcessBrowserTest
{
634 ~PolicyTest() override
{}
636 void SetUp() override
{
637 test_extension_cache_
.reset(new extensions::ExtensionCacheFake());
638 InProcessBrowserTest::SetUp();
641 void SetUpInProcessBrowserTestFixture() override
{
642 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
643 EXPECT_CALL(provider_
, IsInitializationComplete(_
))
644 .WillRepeatedly(Return(true));
645 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_
);
648 void SetUpOnMainThread() override
{
649 BrowserThread::PostTask(
650 BrowserThread::IO
, FROM_HERE
,
651 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled
, true));
652 if (extension_service()->updater()) {
653 extension_service()->updater()->SetExtensionCacheForTesting(
654 test_extension_cache_
.get());
658 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
659 // instead of chrome::DIR_TEST_DATA.
660 void ServeContentTestData() {
661 base::FilePath root_http
;
662 PathService::Get(content::DIR_TEST_DATA
, &root_http
);
663 BrowserThread::PostTaskAndReply(
664 BrowserThread::IO
, FROM_HERE
,
665 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers
, root_http
,
666 make_scoped_refptr(BrowserThread::GetBlockingPool())),
667 base::MessageLoop::current()->QuitWhenIdleClosure());
668 content::RunMessageLoop();
671 void SetScreenshotPolicy(bool enabled
) {
673 policies
.Set(key::kDisableScreenshots
,
674 POLICY_LEVEL_MANDATORY
,
676 new base::FundamentalValue(!enabled
),
678 UpdateProviderPolicy(policies
);
681 #if defined(OS_CHROMEOS)
682 class QuitMessageLoopAfterScreenshot
: public ui::ScreenshotGrabberObserver
{
684 void OnScreenshotCompleted(
685 ScreenshotGrabberObserver::Result screenshot_result
,
686 const base::FilePath
& screenshot_path
) override
{
687 BrowserThread::PostTaskAndReply(BrowserThread::IO
,
689 base::Bind(base::DoNothing
),
690 base::MessageLoop::QuitClosure());
693 ~QuitMessageLoopAfterScreenshot() override
{}
696 void TestScreenshotFile(bool enabled
) {
697 // AddObserver is an ash-specific method, so just replace the screenshot
698 // grabber with one we've created here.
699 scoped_ptr
<ChromeScreenshotGrabber
> chrome_screenshot_grabber(
700 new ChromeScreenshotGrabber
);
701 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
702 // is tied to the test instead.
703 chrome_screenshot_grabber
->screenshot_grabber()->AddObserver(&observer_
);
704 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
705 chrome_screenshot_grabber
.Pass());
707 SetScreenshotPolicy(enabled
);
708 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
709 ash::TAKE_SCREENSHOT
);
711 content::RunMessageLoop();
712 static_cast<ChromeScreenshotGrabber
*>(ash::Shell::GetInstance()
713 ->accelerator_controller()
714 ->screenshot_delegate())
715 ->screenshot_grabber()
716 ->RemoveObserver(&observer_
);
720 ExtensionService
* extension_service() {
721 extensions::ExtensionSystem
* system
=
722 extensions::ExtensionSystem::Get(browser()->profile());
723 return system
->extension_service();
726 const extensions::Extension
* InstallExtension(
727 const base::FilePath::StringType
& name
) {
728 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
729 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
730 scoped_refptr
<extensions::CrxInstaller
> installer
=
731 extensions::CrxInstaller::CreateSilent(extension_service());
732 installer
->set_allow_silent_install(true);
733 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
734 installer
->set_creation_flags(extensions::Extension::FROM_WEBSTORE
);
736 content::WindowedNotificationObserver
observer(
737 extensions::NOTIFICATION_CRX_INSTALLER_DONE
,
738 content::NotificationService::AllSources());
739 installer
->InstallCrx(extension_path
);
741 content::Details
<const extensions::Extension
> details
= observer
.details();
742 return details
.ptr();
745 const extensions::Extension
* LoadUnpackedExtension(
746 const base::FilePath::StringType
& name
, bool expect_success
) {
747 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
748 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
749 scoped_refptr
<extensions::UnpackedInstaller
> installer
=
750 extensions::UnpackedInstaller::Create(extension_service());
751 content::WindowedNotificationObserver
observer(
752 expect_success
? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
753 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR
,
754 content::NotificationService::AllSources());
755 installer
->Load(extension_path
);
758 extensions::ExtensionRegistry
* registry
=
759 extensions::ExtensionRegistry::Get(browser()->profile());
760 for (const scoped_refptr
<const extensions::Extension
>& extension
:
761 registry
->enabled_extensions()) {
762 if (extension
->path() == extension_path
)
763 return extension
.get();
768 void UninstallExtension(const std::string
& id
, bool expect_success
) {
769 if (expect_success
) {
770 extensions::TestExtensionRegistryObserver
observer(
771 extensions::ExtensionRegistry::Get(browser()->profile()));
772 extension_service()->UninstallExtension(
773 id
, extensions::UNINSTALL_REASON_FOR_TESTING
,
774 base::Bind(&base::DoNothing
), NULL
);
775 observer
.WaitForExtensionUninstalled();
777 content::WindowedNotificationObserver
observer(
778 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
779 content::NotificationService::AllSources());
780 extension_service()->UninstallExtension(
782 extensions::UNINSTALL_REASON_FOR_TESTING
,
783 base::Bind(&base::DoNothing
),
789 void DisableExtension(const std::string
& id
) {
790 extensions::TestExtensionRegistryObserver
observer(
791 extensions::ExtensionRegistry::Get(browser()->profile()));
792 extension_service()->DisableExtension(id
,
793 extensions::Extension::DISABLE_NONE
);
794 observer
.WaitForExtensionUnloaded();
797 void UpdateProviderPolicy(const PolicyMap
& policy
) {
798 provider_
.UpdateChromePolicy(policy
);
799 DCHECK(base::MessageLoop::current());
804 // Sends a mouse click at the given coordinates to the current renderer.
805 void PerformClick(int x
, int y
) {
806 content::WebContents
* contents
=
807 browser()->tab_strip_model()->GetActiveWebContents();
808 blink::WebMouseEvent click_event
;
809 click_event
.type
= blink::WebInputEvent::MouseDown
;
810 click_event
.button
= blink::WebMouseEvent::ButtonLeft
;
811 click_event
.clickCount
= 1;
814 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
815 click_event
.type
= blink::WebInputEvent::MouseUp
;
816 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
819 void SetPolicy(PolicyMap
* policies
, const char* key
, base::Value
* value
) {
822 POLICY_LEVEL_MANDATORY
,
827 policies
->Erase(key
);
831 void ApplySafeSearchPolicy(base::FundamentalValue
* legacy_safe_search
,
832 base::FundamentalValue
* google_safe_search
,
833 base::FundamentalValue
* youtube_safety_mode
) {
835 SetPolicy(&policies
, key::kForceSafeSearch
, legacy_safe_search
);
836 SetPolicy(&policies
, key::kForceGoogleSafeSearch
, google_safe_search
);
837 SetPolicy(&policies
, key::kForceYouTubeSafetyMode
, youtube_safety_mode
);
838 UpdateProviderPolicy(policies
);
841 void CheckSafeSearch(bool expect_safe_search
) {
842 content::WebContents
* web_contents
=
843 browser()->tab_strip_model()->GetActiveWebContents();
844 content::TestNavigationObserver
observer(web_contents
);
845 chrome::FocusLocationBar(browser());
846 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
847 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
848 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
850 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
852 std::string
expected_url("http://google.com/");
853 if (expect_safe_search
) {
854 expected_url
+= "?" + std::string(chrome::kSafeSearchSafeParameter
) +
855 "&" + chrome::kSafeSearchSsuiParameter
;
857 EXPECT_EQ(GURL(expected_url
), web_contents
->GetURL());
860 MockConfigurationPolicyProvider provider_
;
861 scoped_ptr
<extensions::ExtensionCacheFake
> test_extension_cache_
;
862 #if defined(OS_CHROMEOS)
863 QuitMessageLoopAfterScreenshot observer_
;
868 // This policy only exists on Windows.
870 // Sets the locale policy before the browser is started.
871 class LocalePolicyTest
: public PolicyTest
{
873 LocalePolicyTest() {}
874 ~LocalePolicyTest() override
{}
876 void SetUpInProcessBrowserTestFixture() override
{
877 PolicyTest::SetUpInProcessBrowserTestFixture();
879 policies
.Set(key::kApplicationLocaleValue
,
880 POLICY_LEVEL_MANDATORY
,
882 new base::StringValue("fr"),
884 provider_
.UpdateChromePolicy(policies
);
885 // The "en-US" ResourceBundle is always loaded before this step for tests,
886 // but in this test we want the browser to load the bundle as it
888 ResourceBundle::CleanupSharedInstance();
892 IN_PROC_BROWSER_TEST_F(LocalePolicyTest
, ApplicationLocaleValue
) {
893 // Verifies that the default locale can be overridden with policy.
894 EXPECT_EQ("fr", g_browser_process
->GetApplicationLocale());
895 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
896 base::string16 french_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
897 base::string16 title
;
898 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title
));
899 EXPECT_EQ(french_title
, title
);
901 // Make sure this is really French and differs from the English title.
903 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
904 EXPECT_EQ("en-US", loaded
);
905 base::string16 english_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
906 EXPECT_NE(french_title
, english_title
);
910 IN_PROC_BROWSER_TEST_F(PolicyTest
, BookmarkBarEnabled
) {
911 #if defined(OS_WIN) && defined(USE_ASH)
912 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
913 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
914 switches::kAshBrowserTests
))
918 // Verifies that the bookmarks bar can be forced to always or never show up.
920 // Test starts in about:blank.
921 PrefService
* prefs
= browser()->profile()->GetPrefs();
922 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
923 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
924 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
927 policies
.Set(key::kBookmarkBarEnabled
,
928 POLICY_LEVEL_MANDATORY
,
930 new base::FundamentalValue(true),
932 UpdateProviderPolicy(policies
);
933 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
934 EXPECT_TRUE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
935 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
937 // The NTP has special handling of the bookmark bar.
938 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
939 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
941 policies
.Set(key::kBookmarkBarEnabled
,
942 POLICY_LEVEL_MANDATORY
,
944 new base::FundamentalValue(false),
946 UpdateProviderPolicy(policies
);
947 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
948 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
949 // The bookmark bar is hidden in the NTP when disabled by policy.
950 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
953 UpdateProviderPolicy(policies
);
954 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
955 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
956 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
957 EXPECT_EQ(BookmarkBar::DETACHED
, browser()->bookmark_bar_state());
960 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_PRE_DefaultCookiesSetting
) {
961 // Verifies that cookies are deleted on shutdown. This test is split in 3
962 // parts because it spans 2 browser restarts.
964 Profile
* profile
= browser()->profile();
966 // No cookies at startup.
967 EXPECT_TRUE(content::GetCookies(profile
, url
).empty());
969 std::string value
= std::string(kCookieValue
) + std::string(kCookieOptions
);
970 EXPECT_TRUE(content::SetCookie(profile
, url
, value
));
971 // Verify it was set.
972 EXPECT_EQ(kCookieValue
, GetCookies(profile
, url
));
975 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_DefaultCookiesSetting
) {
976 // Verify that the cookie persists across restarts.
977 EXPECT_EQ(kCookieValue
, GetCookies(browser()->profile(), GURL(kURL
)));
978 // Now set the policy and the cookie should be gone after another restart.
980 policies
.Set(key::kDefaultCookiesSetting
,
981 POLICY_LEVEL_MANDATORY
,
983 new base::FundamentalValue(4),
985 UpdateProviderPolicy(policies
);
988 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultCookiesSetting
) {
989 // Verify that the cookie is gone.
990 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL
)).empty());
993 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultSearchProvider
) {
994 MakeRequestFail
make_request_fail("search.example");
996 // Verifies that a default search is made using the provider configured via
997 // policy. Also checks that default search can be completely disabled.
998 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
999 const std::string
kSearchURL("http://search.example/search?q={searchTerms}");
1000 const std::string
kAlternateURL0(
1001 "http://search.example/search#q={searchTerms}");
1002 const std::string
kAlternateURL1("http://search.example/#q={searchTerms}");
1003 const std::string
kSearchTermsReplacementKey("zekey");
1004 const std::string
kImageURL("http://test.com/searchbyimage/upload");
1005 const std::string
kImageURLPostParams(
1006 "image_content=content,image_url=http://test.com/test.png");
1007 const std::string
kNewTabURL("http://search.example/newtab");
1009 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1010 browser()->profile());
1011 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1012 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1013 ASSERT_TRUE(default_search
);
1014 EXPECT_NE(kKeyword
, default_search
->keyword());
1015 EXPECT_NE(kSearchURL
, default_search
->url());
1017 default_search
->alternate_urls().size() == 2 &&
1018 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1019 default_search
->alternate_urls()[1] == kAlternateURL1
&&
1020 default_search
->search_terms_replacement_key() ==
1021 kSearchTermsReplacementKey
&&
1022 default_search
->image_url() == kImageURL
&&
1023 default_search
->image_url_post_params() == kImageURLPostParams
&&
1024 default_search
->new_tab_url() == kNewTabURL
);
1026 // Override the default search provider using policies.
1028 policies
.Set(key::kDefaultSearchProviderEnabled
,
1029 POLICY_LEVEL_MANDATORY
,
1031 new base::FundamentalValue(true),
1033 policies
.Set(key::kDefaultSearchProviderKeyword
,
1034 POLICY_LEVEL_MANDATORY
,
1036 new base::StringValue(kKeyword
),
1038 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1039 POLICY_LEVEL_MANDATORY
,
1041 new base::StringValue(kSearchURL
),
1043 base::ListValue
* alternate_urls
= new base::ListValue();
1044 alternate_urls
->AppendString(kAlternateURL0
);
1045 alternate_urls
->AppendString(kAlternateURL1
);
1046 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1047 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1048 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1049 POLICY_LEVEL_MANDATORY
,
1051 new base::StringValue(kSearchTermsReplacementKey
),
1053 policies
.Set(key::kDefaultSearchProviderImageURL
,
1054 POLICY_LEVEL_MANDATORY
,
1056 new base::StringValue(kImageURL
),
1058 policies
.Set(key::kDefaultSearchProviderImageURLPostParams
,
1059 POLICY_LEVEL_MANDATORY
,
1061 new base::StringValue(kImageURLPostParams
),
1063 policies
.Set(key::kDefaultSearchProviderNewTabURL
,
1064 POLICY_LEVEL_MANDATORY
,
1066 new base::StringValue(kNewTabURL
),
1068 UpdateProviderPolicy(policies
);
1069 default_search
= service
->GetDefaultSearchProvider();
1070 ASSERT_TRUE(default_search
);
1071 EXPECT_EQ(kKeyword
, default_search
->keyword());
1072 EXPECT_EQ(kSearchURL
, default_search
->url());
1073 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1074 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1075 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1076 EXPECT_EQ(kSearchTermsReplacementKey
,
1077 default_search
->search_terms_replacement_key());
1078 EXPECT_EQ(kImageURL
, default_search
->image_url());
1079 EXPECT_EQ(kImageURLPostParams
, default_search
->image_url_post_params());
1080 EXPECT_EQ(kNewTabURL
, default_search
->new_tab_url());
1082 // Verify that searching from the omnibox uses kSearchURL.
1083 chrome::FocusLocationBar(browser());
1084 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1085 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "stuff to search for");
1086 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1087 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1088 content::WebContents
* web_contents
=
1089 browser()->tab_strip_model()->GetActiveWebContents();
1090 GURL
expected("http://search.example/search?q=stuff+to+search+for");
1091 EXPECT_EQ(expected
, web_contents
->GetURL());
1093 // Verify that searching from the omnibox can be disabled.
1094 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1095 policies
.Set(key::kDefaultSearchProviderEnabled
,
1096 POLICY_LEVEL_MANDATORY
,
1098 new base::FundamentalValue(false),
1100 EXPECT_TRUE(service
->GetDefaultSearchProvider());
1101 UpdateProviderPolicy(policies
);
1102 EXPECT_FALSE(service
->GetDefaultSearchProvider());
1103 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "should not work");
1104 // This means that submitting won't trigger any action.
1105 EXPECT_FALSE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1106 EXPECT_EQ(GURL(url::kAboutBlankURL
), web_contents
->GetURL());
1109 IN_PROC_BROWSER_TEST_F(PolicyTest
, PolicyPreprocessing
) {
1110 // Add an individual proxy policy value.
1112 policies
.Set(key::kProxyServerMode
,
1113 POLICY_LEVEL_MANDATORY
,
1115 new base::FundamentalValue(3),
1117 UpdateProviderPolicy(policies
);
1119 // It should be removed and replaced with a dictionary.
1121 scoped_ptr
<base::DictionaryValue
> expected_value(new base::DictionaryValue
);
1122 expected_value
->SetInteger(key::kProxyServerMode
, 3);
1123 expected
.Set(key::kProxySettings
,
1124 POLICY_LEVEL_MANDATORY
,
1126 expected_value
.release(),
1129 // Check both the browser and the profile.
1130 const PolicyMap
& actual_from_browser
=
1131 g_browser_process
->browser_policy_connector()
1132 ->GetPolicyService()
1133 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1134 EXPECT_TRUE(expected
.Equals(actual_from_browser
));
1135 const PolicyMap
& actual_from_profile
=
1136 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1138 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1139 EXPECT_TRUE(expected
.Equals(actual_from_profile
));
1142 IN_PROC_BROWSER_TEST_F(PolicyTest
, ForceSafeSearch
) {
1143 // Makes the requests fail since all we want to check is that the redirection
1144 // is done properly.
1145 MakeRequestFail
make_request_fail("google.com");
1147 // Verifies that requests to Google Search engine with the SafeSearch
1148 // enabled set the safe=active&ssui=on parameters at the end of the query.
1149 // First check that nothing happens.
1150 CheckSafeSearch(false);
1152 // Go over all combinations of (undefined,true,false) for the three policies.
1153 for (int i
= 0; i
< 3 * 3 * 3; i
++) {
1155 int google
= (i
/ 3) % 3;
1156 int youtube
= i
/ (3 * 3);
1158 // Override the default SafeSearch setting using policies.
1159 ApplySafeSearchPolicy(
1160 legacy
== 0 ? nullptr : new base::FundamentalValue(legacy
== 1),
1161 google
== 0 ? nullptr : new base::FundamentalValue(google
== 1),
1162 youtube
== 0 ? nullptr : new base::FundamentalValue(youtube
== 1));
1164 // The legacy policy should only have an effect if both google and youtube
1166 bool legacy_in_effect
= (google
== 0 && youtube
== 0 && legacy
!= 0);
1167 bool legacy_enabled
= legacy_in_effect
&& legacy
== 1;
1169 PrefService
* prefs
= browser()->profile()->GetPrefs();
1170 EXPECT_EQ(google
!= 0 || legacy_in_effect
,
1171 prefs
->IsManagedPreference(prefs::kForceGoogleSafeSearch
));
1172 EXPECT_EQ(google
== 1 || legacy_enabled
,
1173 prefs
->GetBoolean(prefs::kForceGoogleSafeSearch
));
1175 EXPECT_EQ(youtube
!= 0 || legacy_in_effect
,
1176 prefs
->IsManagedPreference(prefs::kForceYouTubeSafetyMode
));
1177 EXPECT_EQ(youtube
== 1 || legacy_enabled
,
1178 prefs
->GetBoolean(prefs::kForceYouTubeSafetyMode
));
1180 CheckSafeSearch(google
== 1 || legacy_enabled
);
1184 IN_PROC_BROWSER_TEST_F(PolicyTest
, ReplaceSearchTerms
) {
1185 MakeRequestFail
make_request_fail("search.example");
1187 search::EnableQueryExtractionForTesting();
1189 // Verifies that a default search is made using the provider configured via
1190 // policy. Also checks that default search can be completely disabled.
1191 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1192 const std::string
kSearchURL("https://www.google.com/search?q={searchTerms}");
1193 const std::string
kInstantURL("http://does/not/exist");
1194 const std::string
kAlternateURL0(
1195 "https://www.google.com/search#q={searchTerms}");
1196 const std::string
kAlternateURL1("https://www.google.com/#q={searchTerms}");
1197 const std::string
kSearchTermsReplacementKey(
1198 "{google:instantExtendedEnabledKey}");
1200 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1201 browser()->profile());
1202 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1203 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1204 ASSERT_TRUE(default_search
);
1205 EXPECT_NE(kKeyword
, default_search
->keyword());
1206 EXPECT_NE(kSearchURL
, default_search
->url());
1207 EXPECT_NE(kInstantURL
, default_search
->instant_url());
1209 default_search
->alternate_urls().size() == 2 &&
1210 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1211 default_search
->alternate_urls()[1] == kAlternateURL1
);
1213 // Override the default search provider using policies.
1215 policies
.Set(key::kDefaultSearchProviderEnabled
,
1216 POLICY_LEVEL_MANDATORY
,
1218 new base::FundamentalValue(true),
1220 policies
.Set(key::kDefaultSearchProviderKeyword
,
1221 POLICY_LEVEL_MANDATORY
,
1223 new base::StringValue(kKeyword
),
1225 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1226 POLICY_LEVEL_MANDATORY
,
1228 new base::StringValue(kSearchURL
),
1230 policies
.Set(key::kDefaultSearchProviderInstantURL
,
1231 POLICY_LEVEL_MANDATORY
,
1233 new base::StringValue(kInstantURL
),
1235 base::ListValue
* alternate_urls
= new base::ListValue();
1236 alternate_urls
->AppendString(kAlternateURL0
);
1237 alternate_urls
->AppendString(kAlternateURL1
);
1238 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1239 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1240 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1241 POLICY_LEVEL_MANDATORY
,
1243 new base::StringValue(kSearchTermsReplacementKey
),
1245 UpdateProviderPolicy(policies
);
1246 default_search
= service
->GetDefaultSearchProvider();
1247 ASSERT_TRUE(default_search
);
1248 EXPECT_EQ(kKeyword
, default_search
->keyword());
1249 EXPECT_EQ(kSearchURL
, default_search
->url());
1250 EXPECT_EQ(kInstantURL
, default_search
->instant_url());
1251 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1252 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1253 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1255 // Query terms replacement requires that the renderer process be a recognized
1256 // Instant renderer. Fake it.
1257 InstantService
* instant_service
=
1258 InstantServiceFactory::GetForProfile(browser()->profile());
1259 instant_service
->AddInstantProcess(browser()->tab_strip_model()->
1260 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1262 // Verify that searching from the omnibox does search term replacement with
1263 // first URL pattern.
1264 chrome::FocusLocationBar(browser());
1265 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1266 OmniboxView
* omnibox_view
= location_bar
->GetOmniboxView();
1267 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1268 "https://www.google.com/?espv=1#q=foobar");
1270 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1271 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1273 // Verify that not using espv=1 does not do search term replacement.
1274 chrome::FocusLocationBar(browser());
1275 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1276 "https://www.google.com/?q=foobar");
1278 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1279 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1280 omnibox_view
->GetText());
1282 // Verify that searching from the omnibox does search term replacement with
1283 // second URL pattern.
1284 chrome::FocusLocationBar(browser());
1285 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1286 "https://www.google.com/search?espv=1#q=banana");
1288 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1289 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view
->GetText());
1291 // Verify that searching from the omnibox does search term replacement with
1292 // standard search URL pattern.
1293 chrome::FocusLocationBar(browser());
1294 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1295 "https://www.google.com/search?q=tractor+parts&espv=1");
1297 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1298 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view
->GetText());
1300 // Verify that searching from the omnibox prioritizes hash over query.
1301 chrome::FocusLocationBar(browser());
1302 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1303 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1305 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1306 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1309 IN_PROC_BROWSER_TEST_F(PolicyTest
, Disable3DAPIs
) {
1310 // This test assumes Gpu access.
1311 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
))
1314 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1315 // WebGL is enabled by default.
1316 content::WebContents
* contents
=
1317 browser()->tab_strip_model()->GetActiveWebContents();
1318 EXPECT_TRUE(IsWebGLEnabled(contents
));
1319 // Disable with a policy.
1321 policies
.Set(key::kDisable3DAPIs
,
1322 POLICY_LEVEL_MANDATORY
,
1324 new base::FundamentalValue(true),
1326 UpdateProviderPolicy(policies
);
1327 // Crash and reload the tab to get a new renderer.
1328 content::CrashTab(contents
);
1329 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1330 EXPECT_FALSE(IsWebGLEnabled(contents
));
1331 // Enable with a policy.
1332 policies
.Set(key::kDisable3DAPIs
,
1333 POLICY_LEVEL_MANDATORY
,
1335 new base::FundamentalValue(false),
1337 UpdateProviderPolicy(policies
);
1338 content::CrashTab(contents
);
1339 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1340 EXPECT_TRUE(IsWebGLEnabled(contents
));
1343 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableSpdy
) {
1344 // Verifies that SPDY can be disable by policy.
1345 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1347 policies
.Set(key::kDisableSpdy
,
1348 POLICY_LEVEL_MANDATORY
,
1350 new base::FundamentalValue(true),
1352 UpdateProviderPolicy(policies
);
1353 content::RunAllPendingInMessageLoop();
1354 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1355 // Verify that it can be force-enabled too.
1356 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy
, true);
1357 policies
.Set(key::kDisableSpdy
,
1358 POLICY_LEVEL_MANDATORY
,
1360 new base::FundamentalValue(false),
1362 UpdateProviderPolicy(policies
);
1363 content::RunAllPendingInMessageLoop();
1364 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1367 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPlugins
) {
1368 // Verifies that plugins can be forced to be disabled by policy.
1370 // Verify that the Flash plugin exists and that it can be enabled and disabled
1372 std::vector
<content::WebPluginInfo
> plugins
;
1373 GetPluginList(&plugins
);
1374 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1377 PluginPrefs
* plugin_prefs
=
1378 PluginPrefs::GetForProfile(browser()->profile()).get();
1379 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1380 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1381 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1382 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1383 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1385 // Now disable it with a policy.
1386 base::ListValue disabled_plugins
;
1387 disabled_plugins
.Append(new base::StringValue("*Flash*"));
1389 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1390 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1391 UpdateProviderPolicy(policies
);
1392 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1393 // The user shouldn't be able to enable it.
1394 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1395 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1398 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPluginsExceptions
) {
1399 // Verifies that plugins with an exception in the blacklist can be enabled.
1401 // Verify that the Flash plugin exists and that it can be enabled and disabled
1403 std::vector
<content::WebPluginInfo
> plugins
;
1404 GetPluginList(&plugins
);
1405 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1408 PluginPrefs
* plugin_prefs
=
1409 PluginPrefs::GetForProfile(browser()->profile()).get();
1410 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1412 // Disable all plugins.
1413 base::ListValue disabled_plugins
;
1414 disabled_plugins
.Append(new base::StringValue("*"));
1416 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1417 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1418 UpdateProviderPolicy(policies
);
1419 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1420 // The user shouldn't be able to enable it.
1421 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1422 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1424 // Now open an exception for flash.
1425 base::ListValue disabled_plugins_exceptions
;
1426 disabled_plugins_exceptions
.Append(new base::StringValue("*Flash*"));
1427 policies
.Set(key::kDisabledPluginsExceptions
, POLICY_LEVEL_MANDATORY
,
1428 POLICY_SCOPE_USER
, disabled_plugins_exceptions
.DeepCopy(), NULL
);
1429 UpdateProviderPolicy(policies
);
1430 // It should revert to the user's preference automatically.
1431 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1432 // And the user should be able to disable and enable again.
1433 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1434 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1435 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1436 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1439 IN_PROC_BROWSER_TEST_F(PolicyTest
, EnabledPlugins
) {
1440 // Verifies that a plugin can be force-installed with a policy.
1441 std::vector
<content::WebPluginInfo
> plugins
;
1442 GetPluginList(&plugins
);
1443 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1446 PluginPrefs
* plugin_prefs
=
1447 PluginPrefs::GetForProfile(browser()->profile()).get();
1448 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1450 // The user disables it and then a policy forces it to be enabled.
1451 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1452 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1453 base::ListValue plugin_list
;
1454 plugin_list
.Append(new base::StringValue(content::kFlashPluginName
));
1456 policies
.Set(key::kEnabledPlugins
, POLICY_LEVEL_MANDATORY
,
1457 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1458 UpdateProviderPolicy(policies
);
1459 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1460 // The user can't disable it anymore.
1461 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, false));
1462 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1464 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1465 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1466 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1467 UpdateProviderPolicy(policies
);
1468 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1471 IN_PROC_BROWSER_TEST_F(PolicyTest
, AlwaysAuthorizePlugins
) {
1472 // Verifies that dangerous plugins can be always authorized to run with
1475 // Verify that the test page exists. It is only present in checkouts with
1477 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1478 base::FilePath(FILE_PATH_LITERAL("plugin")),
1479 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1481 "Test skipped because plugin/quicktime.html test file wasn't found.";
1485 ServeContentTestData();
1486 // No plugins at startup.
1487 EXPECT_EQ(0, CountPlugins());
1489 content::WebContents
* contents
=
1490 browser()->tab_strip_model()->GetActiveWebContents();
1491 ASSERT_TRUE(contents
);
1492 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
1493 ASSERT_TRUE(infobar_service
);
1494 EXPECT_EQ(0u, infobar_service
->infobar_count());
1496 base::FilePath
path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1497 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1498 ui_test_utils::NavigateToURL(browser(), url
);
1499 // This should have triggered the dangerous plugin infobar.
1500 ASSERT_EQ(1u, infobar_service
->infobar_count());
1502 infobar_service
->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1503 // And the plugin isn't running.
1504 EXPECT_EQ(0, CountPlugins());
1506 // Now set a policy to always authorize this.
1508 policies
.Set(key::kAlwaysAuthorizePlugins
,
1509 POLICY_LEVEL_MANDATORY
,
1511 new base::FundamentalValue(true),
1513 UpdateProviderPolicy(policies
);
1514 // Reloading the page shouldn't trigger the infobar this time.
1515 ui_test_utils::NavigateToURL(browser(), url
);
1516 EXPECT_EQ(0u, infobar_service
->infobar_count());
1517 // And the plugin started automatically.
1518 EXPECT_EQ(1, CountPlugins());
1521 IN_PROC_BROWSER_TEST_F(PolicyTest
, DeveloperToolsDisabled
) {
1522 // Verifies that access to the developer tools can be disabled.
1525 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1526 content::WebContents
* contents
=
1527 browser()->tab_strip_model()->GetActiveWebContents();
1528 DevToolsWindow
* devtools_window
=
1529 DevToolsWindow::GetInstanceForInspectedWebContents(contents
);
1530 EXPECT_TRUE(devtools_window
);
1532 // Disable devtools via policy.
1534 policies
.Set(key::kDeveloperToolsDisabled
,
1535 POLICY_LEVEL_MANDATORY
,
1537 new base::FundamentalValue(true),
1539 content::WindowedNotificationObserver
close_observer(
1540 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
1541 content::Source
<content::WebContents
>(
1542 DevToolsWindowTesting::Get(devtools_window
)->main_web_contents()));
1543 UpdateProviderPolicy(policies
);
1544 // wait for devtools close
1545 close_observer
.Wait();
1546 // The existing devtools window should have closed.
1547 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1548 // And it's not possible to open it again.
1549 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1550 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1553 // TODO(samarth): remove along with rest of NTP4 code.
1554 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_WebStoreIconHidden
) {
1555 #if defined(OS_WIN) && defined(USE_ASH)
1556 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1557 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1558 switches::kAshBrowserTests
))
1562 // Verifies that the web store icons can be hidden from the new tab page.
1564 // Open new tab page and look for the web store icons.
1565 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1566 content::WebContents
* contents
=
1567 browser()->tab_strip_model()->GetActiveWebContents();
1569 #if !defined(OS_CHROMEOS)
1570 // Look for web store's app ID in the apps page.
1571 EXPECT_TRUE(ContainsVisibleElement(contents
,
1572 "ahfgeienlihckogmohjhadlkjgocpleb"));
1575 // The next NTP has no footer.
1576 if (ContainsVisibleElement(contents
, "footer"))
1577 EXPECT_TRUE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1579 // Turn off the web store icons.
1581 policies
.Set(key::kHideWebStoreIcon
,
1582 POLICY_LEVEL_MANDATORY
,
1584 new base::FundamentalValue(true),
1586 UpdateProviderPolicy(policies
);
1588 // The web store icons should now be hidden.
1589 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1590 EXPECT_FALSE(ContainsVisibleElement(contents
,
1591 "ahfgeienlihckogmohjhadlkjgocpleb"));
1592 EXPECT_FALSE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1595 IN_PROC_BROWSER_TEST_F(PolicyTest
, DownloadDirectory
) {
1596 // Verifies that the download directory can be forced by policy.
1598 // Set the initial download directory.
1599 base::ScopedTempDir initial_dir
;
1600 ASSERT_TRUE(initial_dir
.CreateUniqueTempDir());
1601 browser()->profile()->GetPrefs()->SetFilePath(
1602 prefs::kDownloadDefaultDirectory
, initial_dir
.path());
1603 // Don't prompt for the download location during this test.
1604 browser()->profile()->GetPrefs()->SetBoolean(
1605 prefs::kPromptForDownload
, false);
1607 // Verify that downloads end up on the default directory.
1608 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1609 DownloadAndVerifyFile(browser(), initial_dir
.path(), file
);
1610 base::DieFileDie(initial_dir
.path().Append(file
), false);
1612 // Override the download directory with the policy and verify a download.
1613 base::ScopedTempDir forced_dir
;
1614 ASSERT_TRUE(forced_dir
.CreateUniqueTempDir());
1616 policies
.Set(key::kDownloadDirectory
,
1617 POLICY_LEVEL_MANDATORY
,
1619 new base::StringValue(forced_dir
.path().value()),
1621 UpdateProviderPolicy(policies
);
1622 DownloadAndVerifyFile(browser(), forced_dir
.path(), file
);
1623 // Verify that the first download location wasn't affected.
1624 EXPECT_FALSE(base::PathExists(initial_dir
.path().Append(file
)));
1627 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSelective
) {
1628 // Verifies that blacklisted extensions can't be installed.
1629 ExtensionService
* service
= extension_service();
1630 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1631 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1632 base::ListValue blacklist
;
1633 blacklist
.Append(new base::StringValue(kGoodCrxId
));
1635 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1636 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1637 UpdateProviderPolicy(policies
);
1639 // "good.crx" is blacklisted.
1640 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1641 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1643 // "adblock.crx" is not.
1644 const extensions::Extension
* adblock
= InstallExtension(kAdBlockCrxName
);
1645 ASSERT_TRUE(adblock
);
1646 EXPECT_EQ(kAdBlockCrxId
, adblock
->id());
1648 service
->GetExtensionById(kAdBlockCrxId
, true));
1651 // Flaky on windows; http://crbug.com/307994.
1653 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1655 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1657 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallBlacklistWildcard
) {
1658 // Verify that a wildcard blacklist takes effect.
1659 EXPECT_TRUE(InstallExtension(kAdBlockCrxName
));
1660 ExtensionService
* service
= extension_service();
1661 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1662 ASSERT_TRUE(service
->GetExtensionById(kAdBlockCrxId
, true));
1663 base::ListValue blacklist
;
1664 blacklist
.Append(new base::StringValue("*"));
1666 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1667 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1668 UpdateProviderPolicy(policies
);
1670 // AdBlock was automatically removed.
1671 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1673 // And can't be installed again, nor can good.crx.
1674 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1675 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1676 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1677 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1680 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSharedModules
) {
1681 // Verifies that shared_modules are not affected by the blacklist.
1683 const char kImporterId
[] = "pchakhniekfaeoddkifplhnfbffomabh";
1684 const char kSharedModuleId
[] = "nfgclafboonjbiafbllihiailjlhelpm";
1686 // Make sure that "import" and "export" are available to these extension IDs
1687 // by mocking the release channel.
1688 extensions::ScopedCurrentChannel
channel(version_info::Channel::DEV
);
1690 // Verify that the extensions are not installed initially.
1691 ExtensionService
* service
= extension_service();
1692 ASSERT_FALSE(service
->GetExtensionById(kImporterId
, true));
1693 ASSERT_FALSE(service
->GetExtensionById(kSharedModuleId
, true));
1695 // Mock the webstore update URL. This is where the shared module extension
1696 // will be installed from.
1697 base::FilePath update_xml_path
= base::FilePath(kTestExtensionsDir
)
1698 .AppendASCII("policy_shared_module")
1699 .AppendASCII("update.xml");
1700 GURL
update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path
));
1701 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1702 switches::kAppsGalleryUpdateURL
, update_xml_url
.spec());
1703 ui_test_utils::NavigateToURL(browser(), update_xml_url
);
1705 // Blacklist "*" but force-install the importer extension. The shared module
1706 // should be automatically installed too.
1707 base::ListValue blacklist
;
1708 blacklist
.AppendString("*");
1709 base::ListValue forcelist
;
1710 forcelist
.AppendString(
1711 base::StringPrintf("%s;%s", kImporterId
, update_xml_url
.spec().c_str()));
1713 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1714 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1715 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1716 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1718 extensions::ExtensionRegistry
* registry
=
1719 extensions::ExtensionRegistry::Get(browser()->profile());
1720 extensions::TestExtensionRegistryObserver
observe_importer(
1721 registry
, kImporterId
);
1722 extensions::TestExtensionRegistryObserver
observe_shared_module(
1723 registry
, kSharedModuleId
);
1724 UpdateProviderPolicy(policies
);
1725 observe_importer
.WaitForExtensionLoaded();
1726 observe_shared_module
.WaitForExtensionLoaded();
1728 // Verify that both extensions got installed.
1729 const extensions::Extension
* importer
=
1730 service
->GetExtensionById(kImporterId
, true);
1731 ASSERT_TRUE(importer
);
1732 EXPECT_EQ(kImporterId
, importer
->id());
1733 const extensions::Extension
* shared_module
=
1734 service
->GetExtensionById(kSharedModuleId
, true);
1735 ASSERT_TRUE(shared_module
);
1736 EXPECT_EQ(kSharedModuleId
, shared_module
->id());
1737 EXPECT_TRUE(shared_module
->is_shared_module());
1739 // Verify the dependency.
1740 scoped_ptr
<extensions::ExtensionSet
> set
=
1741 service
->shared_module_service()->GetDependentExtensions(shared_module
);
1743 EXPECT_EQ(1u, set
->size());
1744 EXPECT_TRUE(set
->Contains(importer
->id()));
1746 std::vector
<extensions::SharedModuleInfo::ImportInfo
> imports
=
1747 extensions::SharedModuleInfo::GetImports(importer
);
1748 ASSERT_EQ(1u, imports
.size());
1749 EXPECT_EQ(kSharedModuleId
, imports
[0].extension_id
);
1752 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallWhitelist
) {
1753 // Verifies that the whitelist can open exceptions to the blacklist.
1754 ExtensionService
* service
= extension_service();
1755 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1756 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1757 base::ListValue blacklist
;
1758 blacklist
.Append(new base::StringValue("*"));
1759 base::ListValue whitelist
;
1760 whitelist
.Append(new base::StringValue(kGoodCrxId
));
1762 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1763 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1764 policies
.Set(key::kExtensionInstallWhitelist
, POLICY_LEVEL_MANDATORY
,
1765 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
1766 UpdateProviderPolicy(policies
);
1767 // "adblock.crx" is blacklisted.
1768 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1769 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1770 // "good.crx" has a whitelist exception.
1771 const extensions::Extension
* good
= InstallExtension(kGoodCrxName
);
1773 EXPECT_EQ(kGoodCrxId
, good
->id());
1774 EXPECT_EQ(good
, service
->GetExtensionById(kGoodCrxId
, true));
1775 // The user can also remove this extension.
1776 UninstallExtension(kGoodCrxId
, true);
1779 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallForcelist
) {
1780 // Verifies that extensions that are force-installed by policies are
1781 // installed and can't be uninstalled.
1782 ExtensionService
* service
= extension_service();
1783 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1785 // Extensions that are force-installed come from an update URL, which defaults
1786 // to the webstore. Use a mock URL for this test with an update manifest
1787 // that includes "good_v1.crx".
1788 base::FilePath path
=
1789 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1790 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1792 // Setting the forcelist extension should install "good_v1.crx".
1793 base::ListValue forcelist
;
1794 forcelist
.Append(new base::StringValue(
1795 base::StringPrintf("%s;%s", kGoodCrxId
, url
.spec().c_str())));
1797 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1798 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1799 content::WindowedNotificationObserver
observer(
1800 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1801 content::NotificationService::AllSources());
1802 UpdateProviderPolicy(policies
);
1804 // Note: Cannot check that the notification details match the expected
1805 // exception, since the details object has already been freed prior to
1806 // the completion of observer.Wait().
1808 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1810 // The user is not allowed to uninstall force-installed extensions.
1811 UninstallExtension(kGoodCrxId
, false);
1813 // The user is not allowed to load an unpacked extension with the
1814 // same ID as a force-installed extension.
1815 LoadUnpackedExtension(kGoodUnpackedExt
, false);
1817 // Loading other unpacked extensions are not blocked.
1818 LoadUnpackedExtension(kAppUnpackedExt
, true);
1820 const std::string old_version_number
=
1821 service
->GetExtensionById(kGoodCrxId
, true)->version()->GetString();
1823 base::FilePath test_path
;
1824 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1826 TestRequestInterceptor
interceptor(
1828 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1829 interceptor
.PushJobCallback(
1830 TestRequestInterceptor::FileJob(
1831 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1833 // Updating the force-installed extension.
1834 extensions::ExtensionUpdater
* updater
= service
->updater();
1835 extensions::ExtensionUpdater::CheckParams params
;
1836 params
.install_immediately
= true;
1837 content::WindowedNotificationObserver
update_observer(
1838 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1839 content::NotificationService::AllSources());
1840 updater
->CheckNow(params
);
1841 update_observer
.Wait();
1843 const base::Version
* new_version
=
1844 service
->GetExtensionById(kGoodCrxId
, true)->version();
1845 ASSERT_TRUE(new_version
->IsValid());
1846 base::Version
old_version(old_version_number
);
1847 ASSERT_TRUE(old_version
.IsValid());
1849 EXPECT_EQ(1, new_version
->CompareTo(old_version
));
1851 EXPECT_EQ(0u, interceptor
.GetPendingSize());
1853 // Wait until any background pages belonging to force-installed extensions
1854 // have been loaded.
1855 extensions::ProcessManager
* manager
=
1856 extensions::ProcessManager::Get(browser()->profile());
1857 extensions::ProcessManager::FrameSet all_frames
= manager
->GetAllFrames();
1858 for (extensions::ProcessManager::FrameSet::const_iterator iter
=
1860 iter
!= all_frames
.end();) {
1861 content::WebContents
* web_contents
=
1862 content::WebContents::FromRenderFrameHost(*iter
);
1863 ASSERT_TRUE(web_contents
);
1864 if (!web_contents
->IsLoading()) {
1867 WebContentsLoadedOrDestroyedWatcher(web_contents
).Wait();
1869 // Test activity may have modified the set of extension processes during
1870 // message processing, so re-start the iteration to catch added/removed
1872 all_frames
= manager
->GetAllFrames();
1873 iter
= all_frames
.begin();
1877 // Test policy-installed extensions are reloaded when killed.
1878 BackgroundContentsService::
1879 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1880 content::WindowedNotificationObserver
extension_crashed_observer(
1881 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
1882 content::NotificationService::AllSources());
1883 content::WindowedNotificationObserver
extension_loaded_observer(
1884 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1885 content::NotificationService::AllSources());
1886 extensions::ExtensionHost
* extension_host
=
1887 extensions::ProcessManager::Get(browser()->profile())
1888 ->GetBackgroundHostForExtension(kGoodCrxId
);
1889 extension_host
->render_process_host()->Shutdown(content::RESULT_CODE_KILLED
,
1891 extension_crashed_observer
.Wait();
1892 extension_loaded_observer
.Wait();
1895 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionRecommendedInstallationMode
) {
1896 // Verifies that extensions that are recommended-installed by policies are
1897 // installed, can be disabled but not uninstalled.
1898 ExtensionService
* service
= extension_service();
1899 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1901 base::FilePath path
=
1902 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1903 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1905 // Setting the forcelist extension should install "good_v1.crx".
1906 base::DictionaryValue dict_value
;
1907 dict_value
.SetString(std::string(kGoodCrxId
) + "." +
1908 extensions::schema_constants::kInstallationMode
,
1909 extensions::schema_constants::kNormalInstalled
);
1910 dict_value
.SetString(
1911 std::string(kGoodCrxId
) + "." + extensions::schema_constants::kUpdateUrl
,
1914 policies
.Set(key::kExtensionSettings
,
1915 POLICY_LEVEL_MANDATORY
,
1917 dict_value
.DeepCopy(),
1919 content::WindowedNotificationObserver
observer(
1920 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1921 content::NotificationService::AllSources());
1922 UpdateProviderPolicy(policies
);
1925 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1927 // The user is not allowed to uninstall recommended-installed extensions.
1928 UninstallExtension(kGoodCrxId
, false);
1930 // Explictly re-enables the extension.
1931 service
->EnableExtension(kGoodCrxId
);
1933 // But the user is allowed to disable them.
1934 EXPECT_TRUE(service
->IsExtensionEnabled(kGoodCrxId
));
1935 DisableExtension(kGoodCrxId
);
1936 EXPECT_FALSE(service
->IsExtensionEnabled(kGoodCrxId
));
1939 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionAllowedTypes
) {
1940 // Verifies that extensions are blocked if policy specifies an allowed types
1941 // list and the extension's type is not on that list.
1942 ExtensionService
* service
= extension_service();
1943 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1944 ASSERT_FALSE(service
->GetExtensionById(kHostedAppCrxId
, true));
1946 base::ListValue allowed_types
;
1947 allowed_types
.AppendString("hosted_app");
1949 policies
.Set(key::kExtensionAllowedTypes
, POLICY_LEVEL_MANDATORY
,
1950 POLICY_SCOPE_USER
, allowed_types
.DeepCopy(), NULL
);
1951 UpdateProviderPolicy(policies
);
1953 // "good.crx" is blocked.
1954 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1955 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1957 // "hosted_app.crx" is of a whitelisted type.
1958 const extensions::Extension
* hosted_app
= InstallExtension(kHostedAppCrxName
);
1959 ASSERT_TRUE(hosted_app
);
1960 EXPECT_EQ(kHostedAppCrxId
, hosted_app
->id());
1961 EXPECT_EQ(hosted_app
, service
->GetExtensionById(kHostedAppCrxId
, true));
1963 // The user can remove the extension.
1964 UninstallExtension(kHostedAppCrxId
, true);
1967 // Checks that a click on an extension CRX download triggers the extension
1968 // installation prompt without further user interaction when the source is
1969 // whitelisted by policy.
1970 // Flaky on windows; http://crbug.com/295729 .
1972 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1974 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1976 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallSources
) {
1977 extensions::ScopedTestDialogAutoConfirm
auto_confirm(
1978 extensions::ScopedTestDialogAutoConfirm::ACCEPT
);
1980 const GURL
install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1981 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1982 const GURL
referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1983 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1985 base::ScopedTempDir download_directory
;
1986 ASSERT_TRUE(download_directory
.CreateUniqueTempDir());
1987 DownloadPrefs
* download_prefs
=
1988 DownloadPrefs::FromBrowserContext(browser()->profile());
1989 download_prefs
->SetDownloadPath(download_directory
.path());
1991 const GURL
download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1992 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1993 ui_test_utils::NavigateToURL(browser(), download_page_url
);
1995 // As long as the policy is not present, extensions are considered dangerous.
1996 content::DownloadTestObserverTerminal
download_observer(
1997 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1998 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
);
2000 download_observer
.WaitForFinished();
2002 // Install the policy and trigger another download.
2003 base::ListValue install_sources
;
2004 install_sources
.AppendString(install_source_url
.spec());
2005 install_sources
.AppendString(referrer_url
.spec());
2007 policies
.Set(key::kExtensionInstallSources
, POLICY_LEVEL_MANDATORY
,
2008 POLICY_SCOPE_USER
, install_sources
.DeepCopy(), NULL
);
2009 UpdateProviderPolicy(policies
);
2011 content::WindowedNotificationObserver
observer(
2012 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2013 content::NotificationService::AllSources());
2016 // Note: Cannot check that the notification details match the expected
2017 // exception, since the details object has already been freed prior to
2018 // the completion of observer.Wait().
2020 // The first extension shouldn't be present, the second should be there.
2021 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId
, true));
2022 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId
, false));
2025 // Verifies that extensions with version older than the minimum version required
2026 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
2027 // policy changes as well as regular auto-updater scheduled updates.
2028 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequired
) {
2029 ExtensionService
* service
= extension_service();
2030 extensions::ExtensionRegistry
* registry
=
2031 extensions::ExtensionRegistry::Get(browser()->profile());
2032 extensions::ExtensionPrefs
* extension_prefs
=
2033 extensions::ExtensionPrefs::Get(browser()->profile());
2035 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2036 service
->updater()->StopTimerForTesting();
2038 // Setup interceptor for extension updates.
2039 base::FilePath test_path
;
2040 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2041 TestRequestInterceptor
interceptor(
2043 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2044 interceptor
.PushJobCallback(TestRequestInterceptor::BadRequestJob());
2045 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2046 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2048 // Install the extension.
2049 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2050 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2052 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2053 // version 1.0.0.0) should still be enabled.
2055 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2056 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.0");
2058 base::RunLoop().RunUntilIdle();
2060 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2062 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2063 // version 1.0.0.0) should now be disabled.
2064 EXPECT_EQ(2u, interceptor
.GetPendingSize());
2065 base::RunLoop service_request_run_loop
;
2066 interceptor
.AddRequestServicedCallback(
2067 service_request_run_loop
.QuitClosure());
2069 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2070 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2072 service_request_run_loop
.Run();
2073 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2075 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2076 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2077 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2079 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2080 // via the update URL in the manifest of the older version.
2081 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2083 content::WindowedNotificationObserver
update_observer(
2084 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2085 content::NotificationService::AllSources());
2086 service
->updater()->CheckSoon();
2087 update_observer
.Wait();
2089 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2091 // The extension should be auto-updated to newer version and re-enabled.
2092 EXPECT_EQ("1.0.0.1",
2093 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2094 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2097 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2099 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequiredAlt
) {
2100 ExtensionService
* service
= extension_service();
2101 extensions::ExtensionRegistry
* registry
=
2102 extensions::ExtensionRegistry::Get(browser()->profile());
2103 extensions::ExtensionPrefs
* extension_prefs
=
2104 extensions::ExtensionPrefs::Get(browser()->profile());
2106 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2107 service
->updater()->StopTimerForTesting();
2109 // Setup interceptor for extension updates.
2110 base::FilePath test_path
;
2111 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2112 TestRequestInterceptor
interceptor(
2114 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2115 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2116 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2118 // Set the policy to require an even higher minimum version this time.
2120 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2121 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.2");
2123 base::RunLoop().RunUntilIdle();
2125 // Install the 1.0.0.0 version, it should be installed but disabled.
2126 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2127 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2128 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2129 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2130 EXPECT_EQ("1.0.0.0",
2131 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2133 // An extension management policy update should trigger an update as well.
2134 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2136 content::WindowedNotificationObserver
update_observer(
2137 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2138 content::NotificationService::AllSources());
2140 // Set a higher minimum version, just intend to trigger a policy update.
2141 extensions::ExtensionManagementPolicyUpdater
management_policy(
2143 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.3");
2145 base::RunLoop().RunUntilIdle();
2146 update_observer
.Wait();
2148 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2150 // It should be updated to 1.0.0.1 but remain disabled.
2151 EXPECT_EQ("1.0.0.1",
2152 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2153 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2154 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2155 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2157 // Remove the minimum version requirement. The extension should be re-enabled.
2159 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2160 management_policy
.UnsetMinimumVersionRequired(kGoodCrxId
);
2162 base::RunLoop().RunUntilIdle();
2164 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2165 EXPECT_FALSE(extension_prefs
->HasDisableReason(
2166 kGoodCrxId
, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
));
2169 // Verifies that a force-installed extension which does not meet a subsequently
2170 // set minimum version requirement is handled well.
2171 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionForceInstalled
) {
2172 extensions::ExtensionRegistry
* registry
=
2173 extensions::ExtensionRegistry::Get(browser()->profile());
2174 extensions::ExtensionPrefs
* extension_prefs
=
2175 extensions::ExtensionPrefs::Get(browser()->profile());
2177 // Prepare the update URL for force installing.
2178 const base::FilePath path
=
2179 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
2180 const GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
2182 // Set policy to force-install the extension, it should be installed and
2184 content::WindowedNotificationObserver
install_observer(
2185 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2186 content::NotificationService::AllSources());
2187 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2189 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2190 management_policy
.SetIndividualExtensionAutoInstalled(kGoodCrxId
,
2193 base::RunLoop().RunUntilIdle();
2194 install_observer
.Wait();
2196 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2198 // Set policy a minimum version of "1.0.0.1", the extension now should be
2201 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2202 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2204 base::RunLoop().RunUntilIdle();
2205 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2206 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2207 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2208 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2211 IN_PROC_BROWSER_TEST_F(PolicyTest
, HomepageLocation
) {
2212 #if defined(OS_WIN) && defined(USE_ASH)
2213 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2214 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2215 switches::kAshBrowserTests
))
2219 // Verifies that the homepage can be configured with policies.
2220 // Set a default, and check that the home button navigates there.
2221 browser()->profile()->GetPrefs()->SetString(
2222 prefs::kHomePage
, chrome::kChromeUIPolicyURL
);
2223 browser()->profile()->GetPrefs()->SetBoolean(
2224 prefs::kHomePageIsNewTabPage
, false);
2225 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
),
2226 browser()->profile()->GetHomePage());
2227 content::WebContents
* contents
=
2228 browser()->tab_strip_model()->GetActiveWebContents();
2229 EXPECT_EQ(GURL(url::kAboutBlankURL
), contents
->GetURL());
2230 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2231 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
), contents
->GetURL());
2233 // Now override with policy.
2235 policies
.Set(key::kHomepageLocation
,
2236 POLICY_LEVEL_MANDATORY
,
2238 new base::StringValue(chrome::kChromeUICreditsURL
),
2240 UpdateProviderPolicy(policies
);
2241 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2242 content::WaitForLoadStop(contents
);
2243 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL
), contents
->GetURL());
2245 policies
.Set(key::kHomepageIsNewTabPage
,
2246 POLICY_LEVEL_MANDATORY
,
2248 new base::FundamentalValue(true),
2250 UpdateProviderPolicy(policies
);
2251 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2252 content::WaitForLoadStop(contents
);
2253 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL
), contents
->GetURL());
2256 IN_PROC_BROWSER_TEST_F(PolicyTest
, IncognitoEnabled
) {
2257 // Verifies that incognito windows can't be opened when disabled by policy.
2259 const BrowserList
* active_browser_list
=
2260 BrowserList::GetInstance(chrome::GetActiveDesktop());
2262 // Disable incognito via policy and verify that incognito windows can't be
2264 EXPECT_EQ(1u, active_browser_list
->size());
2265 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2267 policies
.Set(key::kIncognitoEnabled
,
2268 POLICY_LEVEL_MANDATORY
,
2270 new base::FundamentalValue(false),
2272 UpdateProviderPolicy(policies
);
2273 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2274 EXPECT_EQ(1u, active_browser_list
->size());
2275 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2277 // Enable via policy and verify that incognito windows can be opened.
2278 policies
.Set(key::kIncognitoEnabled
,
2279 POLICY_LEVEL_MANDATORY
,
2281 new base::FundamentalValue(true),
2283 UpdateProviderPolicy(policies
);
2284 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2285 EXPECT_EQ(2u, active_browser_list
->size());
2286 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2289 IN_PROC_BROWSER_TEST_F(PolicyTest
, Javascript
) {
2290 // Verifies that Javascript can be disabled.
2291 content::WebContents
* contents
=
2292 browser()->tab_strip_model()->GetActiveWebContents();
2293 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2294 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2295 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2296 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2298 // Disable Javascript via policy.
2300 policies
.Set(key::kJavascriptEnabled
,
2301 POLICY_LEVEL_MANDATORY
,
2303 new base::FundamentalValue(false),
2305 UpdateProviderPolicy(policies
);
2307 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2308 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2309 // Developer tools still work when javascript is disabled.
2310 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2311 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2312 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2313 // Javascript is always enabled for the internal pages.
2314 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL
));
2315 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2317 // The javascript content setting policy overrides the javascript policy.
2318 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2319 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2320 policies
.Set(key::kDefaultJavaScriptSetting
,
2321 POLICY_LEVEL_MANDATORY
,
2323 new base::FundamentalValue(CONTENT_SETTING_ALLOW
),
2325 UpdateProviderPolicy(policies
);
2326 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2327 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2330 IN_PROC_BROWSER_TEST_F(PolicyTest
, NetworkPrediction
) {
2331 PrefService
* prefs
= browser()->profile()->GetPrefs();
2333 // Enabled by default.
2334 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2336 // Disable by old, deprecated policy.
2338 policies
.Set(key::kDnsPrefetchingEnabled
,
2339 POLICY_LEVEL_MANDATORY
,
2341 new base::FundamentalValue(false),
2343 UpdateProviderPolicy(policies
);
2345 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs
));
2347 // Enabled by new policy, this should override old one.
2349 key::kNetworkPredictionOptions
,
2350 POLICY_LEVEL_MANDATORY
,
2352 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS
),
2354 UpdateProviderPolicy(policies
);
2356 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2359 IN_PROC_BROWSER_TEST_F(PolicyTest
, SavingBrowserHistoryDisabled
) {
2360 // Verifies that browsing history is not saved.
2362 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2363 POLICY_LEVEL_MANDATORY
,
2365 new base::FundamentalValue(true),
2367 UpdateProviderPolicy(policies
);
2368 GURL url
= ui_test_utils::GetTestUrl(
2369 base::FilePath(base::FilePath::kCurrentDirectory
),
2370 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2371 ui_test_utils::NavigateToURL(browser(), url
);
2372 // Verify that the navigation wasn't saved in the history.
2373 ui_test_utils::HistoryEnumerator
enumerator1(browser()->profile());
2374 EXPECT_EQ(0u, enumerator1
.urls().size());
2376 // Now flip the policy and try again.
2377 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2378 POLICY_LEVEL_MANDATORY
,
2380 new base::FundamentalValue(false),
2382 UpdateProviderPolicy(policies
);
2383 ui_test_utils::NavigateToURL(browser(), url
);
2384 // Verify that the navigation was saved in the history.
2385 ui_test_utils::HistoryEnumerator
enumerator2(browser()->profile());
2386 ASSERT_EQ(1u, enumerator2
.urls().size());
2387 EXPECT_EQ(url
, enumerator2
.urls()[0]);
2390 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2391 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_TranslateEnabled
) {
2392 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2393 if (TranslateService::IsTranslateBubbleEnabled())
2396 scoped_ptr
<test::CldDataHarness
> cld_data_scope
=
2397 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2398 ASSERT_NO_FATAL_FAILURE(cld_data_scope
->Init());
2400 // Verifies that translate can be forced enabled or disabled by policy.
2402 // Get the InfoBarService, and verify that there are no infobars on startup.
2403 content::WebContents
* contents
=
2404 browser()->tab_strip_model()->GetActiveWebContents();
2405 ASSERT_TRUE(contents
);
2406 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
2407 ASSERT_TRUE(infobar_service
);
2408 EXPECT_EQ(0u, infobar_service
->infobar_count());
2410 // Force enable the translate feature.
2412 policies
.Set(key::kTranslateEnabled
,
2413 POLICY_LEVEL_MANDATORY
,
2415 new base::FundamentalValue(true),
2417 UpdateProviderPolicy(policies
);
2418 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2419 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2420 // TranslateManager observes. This allows checking that an infobar is NOT
2421 // shown below, without polling for infobars for some indeterminate amount
2423 GURL url
= ui_test_utils::GetTestUrl(
2425 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2426 content::WindowedNotificationObserver
language_observer1(
2427 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2428 content::NotificationService::AllSources());
2429 ui_test_utils::NavigateToURL(browser(), url
);
2430 language_observer1
.Wait();
2432 // Verify the translation detected for this tab.
2433 ChromeTranslateClient
* chrome_translate_client
=
2434 ChromeTranslateClient::FromWebContents(contents
);
2435 ASSERT_TRUE(chrome_translate_client
);
2436 translate::LanguageState
& language_state
=
2437 chrome_translate_client
->GetLanguageState();
2438 EXPECT_EQ("fr", language_state
.original_language());
2439 EXPECT_TRUE(language_state
.page_needs_translation());
2440 EXPECT_FALSE(language_state
.translation_pending());
2441 EXPECT_FALSE(language_state
.translation_declined());
2442 EXPECT_FALSE(language_state
.IsPageTranslated());
2444 // Verify that the translate infobar showed up.
2445 ASSERT_EQ(1u, infobar_service
->infobar_count());
2446 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2447 translate::TranslateInfoBarDelegate
* translate_infobar_delegate
=
2448 infobar
->delegate()->AsTranslateInfoBarDelegate();
2449 ASSERT_TRUE(translate_infobar_delegate
);
2450 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE
,
2451 translate_infobar_delegate
->translate_step());
2452 EXPECT_EQ("fr", translate_infobar_delegate
->original_language_code());
2454 // Now force disable translate.
2455 infobar_service
->RemoveInfoBar(infobar
);
2456 EXPECT_EQ(0u, infobar_service
->infobar_count());
2457 policies
.Set(key::kTranslateEnabled
,
2458 POLICY_LEVEL_MANDATORY
,
2460 new base::FundamentalValue(false),
2462 UpdateProviderPolicy(policies
);
2463 // Navigating to the same URL now doesn't trigger an infobar.
2464 content::WindowedNotificationObserver
language_observer2(
2465 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2466 content::NotificationService::AllSources());
2467 ui_test_utils::NavigateToURL(browser(), url
);
2468 language_observer2
.Wait();
2469 EXPECT_EQ(0u, infobar_service
->infobar_count());
2472 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklist
) {
2473 // Checks that URLs can be blacklisted, and that exceptions can be made to
2476 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2477 // as URLRequestMockHTTPJobs.
2478 const char* kURLS
[] = {
2479 "http://aaa.com/empty.html",
2480 "http://bbb.com/empty.html",
2481 "http://sub.bbb.com/empty.html",
2482 "http://bbb.com/policy/blank.html",
2483 "http://bbb.com./policy/blank.html",
2487 BrowserThread::PostTaskAndReply(
2488 BrowserThread::IO
, FROM_HERE
,
2489 base::Bind(RedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2490 loop
.QuitClosure());
2494 // Verify that "bbb.com" opens before applying the blacklist.
2495 CheckCanOpenURL(browser(), kURLS
[1]);
2498 base::ListValue blacklist
;
2499 blacklist
.Append(new base::StringValue("bbb.com"));
2501 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2502 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2503 UpdateProviderPolicy(policies
);
2504 FlushBlacklistPolicy();
2505 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2506 CheckCanOpenURL(browser(), kURLS
[0]);
2507 for (size_t i
= 1; i
< arraysize(kURLS
); ++i
)
2508 CheckURLIsBlocked(browser(), kURLS
[i
]);
2510 // Whitelist some sites of bbb.com.
2511 base::ListValue whitelist
;
2512 whitelist
.Append(new base::StringValue("sub.bbb.com"));
2513 whitelist
.Append(new base::StringValue("bbb.com/policy"));
2514 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2515 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2516 UpdateProviderPolicy(policies
);
2517 FlushBlacklistPolicy();
2518 CheckURLIsBlocked(browser(), kURLS
[1]);
2519 CheckCanOpenURL(browser(), kURLS
[2]);
2520 CheckCanOpenURL(browser(), kURLS
[3]);
2521 CheckCanOpenURL(browser(), kURLS
[4]);
2525 BrowserThread::PostTaskAndReply(
2526 BrowserThread::IO
, FROM_HERE
,
2527 base::Bind(UndoRedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2528 loop
.QuitClosure());
2533 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklistSubresources
) {
2534 // Checks that an image with a blacklisted URL is loaded, but an iframe with a
2535 // blacklisted URL is not.
2537 GURL main_url
= URLRequestMockHTTPJob::GetMockUrl(
2538 base::FilePath(FILE_PATH_LITERAL("policy/blacklist-subresources.html")));
2539 GURL image_url
= URLRequestMockHTTPJob::GetMockUrl(
2540 base::FilePath(FILE_PATH_LITERAL("policy/pixel.png")));
2541 GURL subframe_url
= URLRequestMockHTTPJob::GetMockUrl(
2542 base::FilePath(FILE_PATH_LITERAL("policy/blank.html")));
2544 // Set a blacklist containing the image and the iframe which are used by the
2546 base::ListValue blacklist
;
2547 blacklist
.Append(new base::StringValue(image_url
.spec().c_str()));
2548 blacklist
.Append(new base::StringValue(subframe_url
.spec().c_str()));
2550 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2551 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2552 UpdateProviderPolicy(policies
);
2553 FlushBlacklistPolicy();
2555 std::string blacklisted_image_load_result
;
2556 ui_test_utils::NavigateToURL(browser(), main_url
);
2557 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2558 browser()->tab_strip_model()->GetActiveWebContents(),
2559 "window.domAutomationController.send(imageLoadResult)",
2560 &blacklisted_image_load_result
));
2561 EXPECT_EQ("success", blacklisted_image_load_result
);
2563 std::string blacklisted_iframe_load_result
;
2564 ui_test_utils::NavigateToURL(browser(), main_url
);
2565 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2566 browser()->tab_strip_model()->GetActiveWebContents(),
2567 "window.domAutomationController.send(iframeLoadResult)",
2568 &blacklisted_iframe_load_result
));
2569 EXPECT_EQ("error", blacklisted_iframe_load_result
);
2572 #if defined(OS_MACOSX)
2573 // http://crbug.com/339240
2574 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2576 #define MAYBE_FileURLBlacklist FileURLBlacklist
2578 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_FileURLBlacklist
) {
2579 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2580 // with URLblacklisting and URLwhitelisting.
2582 base::FilePath test_path
;
2583 PathService::Get(chrome::DIR_TEST_DATA
, &test_path
);
2584 const std::string base_path
= "file://" + test_path
.AsUTF8Unsafe() +"/";
2585 const std::string folder_path
= base_path
+ "apptest/";
2586 const std::string file_path1
= base_path
+ "title1.html";
2587 const std::string file_path2
= folder_path
+ "basic.html";
2589 CheckCanOpenURL(browser(), file_path1
.c_str());
2590 CheckCanOpenURL(browser(), file_path2
.c_str());
2592 // Set a blacklist for all the files.
2593 base::ListValue blacklist
;
2594 blacklist
.Append(new base::StringValue("file://*"));
2596 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2597 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2598 UpdateProviderPolicy(policies
);
2599 FlushBlacklistPolicy();
2601 CheckURLIsBlocked(browser(), file_path1
.c_str());
2602 CheckURLIsBlocked(browser(), file_path2
.c_str());
2604 // Replace the URLblacklist with disabling the file scheme.
2605 blacklist
.Remove(base::StringValue("file://*"), NULL
);
2606 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2607 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2608 UpdateProviderPolicy(policies
);
2609 FlushBlacklistPolicy();
2611 PrefService
* prefs
= browser()->profile()->GetPrefs();
2612 const base::ListValue
* list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2613 EXPECT_EQ(list_url
->Find(base::StringValue("file://*")),
2616 base::ListValue disabledscheme
;
2617 disabledscheme
.Append(new base::StringValue("file"));
2618 policies
.Set(key::kDisabledSchemes
, POLICY_LEVEL_MANDATORY
,
2619 POLICY_SCOPE_USER
, disabledscheme
.DeepCopy(), NULL
);
2620 UpdateProviderPolicy(policies
);
2621 FlushBlacklistPolicy();
2623 list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2624 EXPECT_NE(list_url
->Find(base::StringValue("file://*")),
2627 // Whitelist one folder and blacklist an another just inside.
2628 base::ListValue whitelist
;
2629 whitelist
.Append(new base::StringValue(base_path
));
2630 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2631 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2632 blacklist
.Append(new base::StringValue(folder_path
));
2633 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2634 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2635 UpdateProviderPolicy(policies
);
2636 FlushBlacklistPolicy();
2638 CheckCanOpenURL(browser(), file_path1
.c_str());
2639 CheckURLIsBlocked(browser(), file_path2
.c_str());
2644 void GetSSLVersionFallbackMinOnIOThread(
2645 const scoped_refptr
<net::SSLConfigService
>& config_service
,
2646 uint16_t* version_fallback_min
) {
2647 net::SSLConfig config
;
2648 config_service
->GetSSLConfig(&config
);
2649 *version_fallback_min
= config
.version_fallback_min
;
2652 uint16_t GetSSLVersionFallbackMin(Profile
* profile
) {
2653 scoped_refptr
<net::SSLConfigService
> config_service(
2654 profile
->GetSSLConfigService());
2655 uint16_t version_fallback_min
;
2657 BrowserThread::PostTaskAndReply(
2658 BrowserThread::IO
, FROM_HERE
,
2659 base::Bind(&GetSSLVersionFallbackMinOnIOThread
, config_service
,
2660 base::Unretained(&version_fallback_min
)),
2661 loop
.QuitClosure());
2663 return version_fallback_min
;
2668 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionFallbackMin
) {
2669 PrefService
* prefs
= g_browser_process
->local_state();
2671 const std::string
new_value("tls1.2");
2672 const std::string
default_value(
2673 prefs
->GetString(prefs::kSSLVersionFallbackMin
));
2675 EXPECT_NE(default_value
, new_value
);
2676 EXPECT_NE(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2677 GetSSLVersionFallbackMin(browser()->profile()));
2680 policies
.Set(key::kSSLVersionFallbackMin
,
2681 POLICY_LEVEL_MANDATORY
,
2683 new base::StringValue(new_value
),
2685 UpdateProviderPolicy(policies
);
2687 EXPECT_EQ(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2688 GetSSLVersionFallbackMin(browser()->profile()));
2691 #if !defined(OS_MACOSX)
2692 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedBrowser
) {
2694 policies
.Set(key::kFullscreenAllowed
,
2695 POLICY_LEVEL_MANDATORY
,
2697 new base::FundamentalValue(false),
2699 UpdateProviderPolicy(policies
);
2701 BrowserWindow
* browser_window
= browser()->window();
2702 ASSERT_TRUE(browser_window
);
2704 EXPECT_FALSE(browser_window
->IsFullscreen());
2705 chrome::ToggleFullscreenMode(browser());
2706 EXPECT_FALSE(browser_window
->IsFullscreen());
2709 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedApp
) {
2711 policies
.Set(key::kFullscreenAllowed
,
2712 POLICY_LEVEL_MANDATORY
,
2714 new base::FundamentalValue(false),
2716 UpdateProviderPolicy(policies
);
2718 const extensions::Extension
* extension
=
2719 LoadUnpackedExtension(kUnpackedFullscreenAppName
, true);
2720 ASSERT_TRUE(extension
);
2722 // Launch an app that tries to open a fullscreen window.
2723 TestAddAppWindowObserver
add_window_observer(
2724 extensions::AppWindowRegistry::Get(browser()->profile()));
2725 OpenApplication(AppLaunchParams(browser()->profile(), extension
,
2726 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
,
2727 extensions::SOURCE_TEST
));
2728 extensions::AppWindow
* window
= add_window_observer
.WaitForAppWindow();
2729 ASSERT_TRUE(window
);
2731 // Verify that the window is not in fullscreen mode.
2732 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2734 // Verify that the window cannot be toggled into fullscreen mode via apps
2736 EXPECT_TRUE(content::ExecuteScript(
2737 window
->web_contents(),
2738 "chrome.app.window.current().fullscreen();"));
2739 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2741 // Verify that the window cannot be toggled into fullscreen mode from within
2742 // Chrome (e.g., using keyboard accelerators).
2743 window
->Fullscreen();
2744 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2748 #if defined(OS_CHROMEOS)
2750 // Flaky http://crbug.com/476964
2751 #if defined(MEMORY_SANITIZER)
2752 #define MAYBE_DisableScreenshotsFile DISABLED_DisableScreenshotsFile
2754 #define MAYBE_DisableScreenshotsFile DisableScreenshotsFile
2757 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_DisableScreenshotsFile
) {
2758 int screenshot_count
= CountScreenshots();
2760 // Make sure screenshots are counted correctly.
2761 TestScreenshotFile(true);
2762 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2764 // Check if trying to take a screenshot fails when disabled by policy.
2765 TestScreenshotFile(false);
2766 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2769 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableAudioOutput
) {
2770 // Set up the mock observer.
2771 chromeos::CrasAudioHandler
* audio_handler
= chromeos::CrasAudioHandler::Get();
2772 scoped_ptr
<TestAudioObserver
> test_observer(new TestAudioObserver
);
2773 audio_handler
->AddAudioObserver(test_observer
.get());
2775 bool prior_state
= audio_handler
->IsOutputMuted();
2776 // Make sure the audio is not muted and then toggle the policy and observe
2777 // if the output mute changed event is fired.
2778 audio_handler
->SetOutputMute(false);
2779 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2780 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2782 policies
.Set(key::kAudioOutputAllowed
,
2783 POLICY_LEVEL_MANDATORY
,
2785 new base::FundamentalValue(false),
2787 UpdateProviderPolicy(policies
);
2788 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2789 // This should not change the state now and should not trigger output mute
2791 audio_handler
->SetOutputMute(false);
2792 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2793 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2795 // Toggle back and observe if the output mute changed event is fired.
2796 policies
.Set(key::kAudioOutputAllowed
,
2797 POLICY_LEVEL_MANDATORY
,
2799 new base::FundamentalValue(true),
2801 UpdateProviderPolicy(policies
);
2802 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2803 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2804 audio_handler
->SetOutputMute(true);
2805 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2806 EXPECT_EQ(2, test_observer
->output_mute_changed_count());
2807 // Revert the prior state.
2808 audio_handler
->SetOutputMute(prior_state
);
2809 audio_handler
->RemoveAudioObserver(test_observer
.get());
2812 // Disabled, see http://crbug.com/315308.
2813 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_PRE_SessionLengthLimit
) {
2814 // Indicate that the session started 2 hours ago and no user activity has
2816 g_browser_process
->local_state()->SetInt64(
2817 prefs::kSessionStartTime
,
2818 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2819 .ToInternalValue());
2822 // Disabled, see http://crbug.com/315308.
2823 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_SessionLengthLimit
) {
2824 content::MockNotificationObserver observer
;
2825 content::NotificationRegistrar registrar
;
2826 registrar
.Add(&observer
,
2827 chrome::NOTIFICATION_APP_TERMINATING
,
2828 content::NotificationService::AllSources());
2830 // Set the session length limit to 3 hours. Verify that the session is not
2832 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2835 policies
.Set(key::kSessionLengthLimit
,
2836 POLICY_LEVEL_MANDATORY
,
2838 new base::FundamentalValue(kThreeHoursInMs
),
2840 UpdateProviderPolicy(policies
);
2841 base::RunLoop().RunUntilIdle();
2842 Mock::VerifyAndClearExpectations(&observer
);
2844 // Decrease the session length limit to 1 hour. Verify that the session is
2845 // terminated immediately.
2846 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2847 policies
.Set(key::kSessionLengthLimit
,
2848 POLICY_LEVEL_MANDATORY
,
2850 new base::FundamentalValue(kOneHourInMs
),
2852 UpdateProviderPolicy(policies
);
2853 base::RunLoop().RunUntilIdle();
2854 Mock::VerifyAndClearExpectations(&observer
);
2857 // Disabled, see http://crbug.com/315308.
2858 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2859 DISABLED_PRE_WaitForInitialUserActivityUsatisfied
) {
2860 // Indicate that the session started 2 hours ago and no user activity has
2862 g_browser_process
->local_state()->SetInt64(
2863 prefs::kSessionStartTime
,
2864 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2865 .ToInternalValue());
2868 // Disabled, see http://crbug.com/315308.
2869 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2870 DISABLED_WaitForInitialUserActivityUsatisfied
) {
2871 content::MockNotificationObserver observer
;
2872 content::NotificationRegistrar registrar
;
2873 registrar
.Add(&observer
,
2874 chrome::NOTIFICATION_APP_TERMINATING
,
2875 content::NotificationService::AllSources());
2877 // Require initial user activity.
2879 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2881 new base::FundamentalValue(true),
2883 UpdateProviderPolicy(policies
);
2884 base::RunLoop().RunUntilIdle();
2886 // Set the session length limit to 1 hour. Verify that the session is not
2888 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2890 policies
.Set(key::kSessionLengthLimit
,
2891 POLICY_LEVEL_MANDATORY
,
2893 new base::FundamentalValue(kOneHourInMs
),
2895 UpdateProviderPolicy(policies
);
2896 base::RunLoop().RunUntilIdle();
2897 Mock::VerifyAndClearExpectations(&observer
);
2900 // Disabled, see http://crbug.com/315308.
2901 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2902 DISABLED_PRE_WaitForInitialUserActivitySatisfied
) {
2903 // Indicate that initial user activity in this session occurred 2 hours ago.
2904 g_browser_process
->local_state()->SetInt64(
2905 prefs::kSessionStartTime
,
2906 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2907 .ToInternalValue());
2908 g_browser_process
->local_state()->SetBoolean(
2909 prefs::kSessionUserActivitySeen
,
2913 // Disabled, see http://crbug.com/315308.
2914 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2915 DISABLED_WaitForInitialUserActivitySatisfied
) {
2916 content::MockNotificationObserver observer
;
2917 content::NotificationRegistrar registrar
;
2918 registrar
.Add(&observer
,
2919 chrome::NOTIFICATION_APP_TERMINATING
,
2920 content::NotificationService::AllSources());
2922 // Require initial user activity and set the session length limit to 3 hours.
2923 // Verify that the session is not terminated.
2924 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2927 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2929 new base::FundamentalValue(true),
2931 policies
.Set(key::kSessionLengthLimit
,
2932 POLICY_LEVEL_MANDATORY
,
2934 new base::FundamentalValue(kThreeHoursInMs
),
2936 UpdateProviderPolicy(policies
);
2937 base::RunLoop().RunUntilIdle();
2938 Mock::VerifyAndClearExpectations(&observer
);
2940 // Decrease the session length limit to 1 hour. Verify that the session is
2941 // terminated immediately.
2942 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2943 policies
.Set(key::kSessionLengthLimit
,
2944 POLICY_LEVEL_MANDATORY
,
2946 new base::FundamentalValue(kOneHourInMs
),
2948 UpdateProviderPolicy(policies
);
2949 base::RunLoop().RunUntilIdle();
2950 Mock::VerifyAndClearExpectations(&observer
);
2953 IN_PROC_BROWSER_TEST_F(PolicyTest
, LargeCursorEnabled
) {
2954 // Verifies that the large cursor accessibility feature can be controlled
2956 chromeos::AccessibilityManager
* accessibility_manager
=
2957 chromeos::AccessibilityManager::Get();
2959 // Manually enable the large cursor.
2960 accessibility_manager
->EnableLargeCursor(true);
2961 EXPECT_TRUE(accessibility_manager
->IsLargeCursorEnabled());
2963 // Verify that policy overrides the manual setting.
2965 policies
.Set(key::kLargeCursorEnabled
,
2966 POLICY_LEVEL_MANDATORY
,
2968 new base::FundamentalValue(false),
2970 UpdateProviderPolicy(policies
);
2971 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2973 // Verify that the large cursor cannot be enabled manually anymore.
2974 accessibility_manager
->EnableLargeCursor(true);
2975 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2978 IN_PROC_BROWSER_TEST_F(PolicyTest
, SpokenFeedbackEnabled
) {
2979 // Verifies that the spoken feedback accessibility feature can be controlled
2981 chromeos::AccessibilityManager
* accessibility_manager
=
2982 chromeos::AccessibilityManager::Get();
2984 // Manually enable spoken feedback.
2985 accessibility_manager
->EnableSpokenFeedback(
2986 true, ui::A11Y_NOTIFICATION_NONE
);
2987 EXPECT_TRUE(accessibility_manager
->IsSpokenFeedbackEnabled());
2989 // Verify that policy overrides the manual setting.
2991 policies
.Set(key::kSpokenFeedbackEnabled
,
2992 POLICY_LEVEL_MANDATORY
,
2994 new base::FundamentalValue(false),
2996 UpdateProviderPolicy(policies
);
2997 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2999 // Verify that spoken feedback cannot be enabled manually anymore.
3000 accessibility_manager
->EnableSpokenFeedback(
3001 true, ui::A11Y_NOTIFICATION_NONE
);
3002 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
3005 IN_PROC_BROWSER_TEST_F(PolicyTest
, HighContrastEnabled
) {
3006 // Verifies that the high contrast mode accessibility feature can be
3007 // controlled through policy.
3008 chromeos::AccessibilityManager
* accessibility_manager
=
3009 chromeos::AccessibilityManager::Get();
3011 // Manually enable high contrast mode.
3012 accessibility_manager
->EnableHighContrast(true);
3013 EXPECT_TRUE(accessibility_manager
->IsHighContrastEnabled());
3015 // Verify that policy overrides the manual setting.
3017 policies
.Set(key::kHighContrastEnabled
,
3018 POLICY_LEVEL_MANDATORY
,
3020 new base::FundamentalValue(false),
3022 UpdateProviderPolicy(policies
);
3023 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3025 // Verify that high contrast mode cannot be enabled manually anymore.
3026 accessibility_manager
->EnableHighContrast(true);
3027 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3030 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeNone
) {
3031 // Verifies that the screen magnifier can be disabled through policy.
3032 chromeos::MagnificationManager
* magnification_manager
=
3033 chromeos::MagnificationManager::Get();
3035 // Manually enable the full-screen magnifier.
3036 magnification_manager
->SetMagnifierType(ui::MAGNIFIER_FULL
);
3037 magnification_manager
->SetMagnifierEnabled(true);
3038 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3039 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3041 // Verify that policy overrides the manual setting.
3043 policies
.Set(key::kScreenMagnifierType
,
3044 POLICY_LEVEL_MANDATORY
,
3046 new base::FundamentalValue(0),
3048 UpdateProviderPolicy(policies
);
3049 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3051 // Verify that the screen magnifier cannot be enabled manually anymore.
3052 magnification_manager
->SetMagnifierEnabled(true);
3053 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3056 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeFull
) {
3057 // Verifies that the full-screen magnifier can be enabled through policy.
3058 chromeos::MagnificationManager
* magnification_manager
=
3059 chromeos::MagnificationManager::Get();
3061 // Verify that the screen magnifier is initially disabled.
3062 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3064 // Verify that policy can enable the full-screen magnifier.
3066 policies
.Set(key::kScreenMagnifierType
,
3067 POLICY_LEVEL_MANDATORY
,
3069 new base::FundamentalValue(ui::MAGNIFIER_FULL
),
3071 UpdateProviderPolicy(policies
);
3072 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3073 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3075 // Verify that the screen magnifier cannot be disabled manually anymore.
3076 magnification_manager
->SetMagnifierEnabled(false);
3077 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3080 IN_PROC_BROWSER_TEST_F(PolicyTest
, AccessibilityVirtualKeyboardEnabled
) {
3081 // Verifies that the on-screen keyboard accessibility feature can be
3082 // controlled through policy.
3083 chromeos::AccessibilityManager
* accessibility_manager
=
3084 chromeos::AccessibilityManager::Get();
3086 // Manually enable the on-screen keyboard.
3087 accessibility_manager
->EnableVirtualKeyboard(true);
3088 EXPECT_TRUE(accessibility_manager
->IsVirtualKeyboardEnabled());
3090 // Verify that policy overrides the manual setting.
3092 policies
.Set(key::kVirtualKeyboardEnabled
,
3093 POLICY_LEVEL_MANDATORY
,
3095 new base::FundamentalValue(false),
3097 UpdateProviderPolicy(policies
);
3098 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3100 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3101 accessibility_manager
->EnableVirtualKeyboard(true);
3102 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3105 IN_PROC_BROWSER_TEST_F(PolicyTest
, VirtualKeyboardEnabled
) {
3106 // Verify keyboard disabled by default.
3107 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3108 // Verify keyboard can be toggled by default.
3109 keyboard::SetTouchKeyboardEnabled(true);
3110 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3111 keyboard::SetTouchKeyboardEnabled(false);
3112 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3114 // Verify enabling the policy takes effect immediately and that that user
3115 // cannot disable the keyboard..
3117 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3118 POLICY_LEVEL_MANDATORY
,
3120 new base::FundamentalValue(true),
3122 UpdateProviderPolicy(policies
);
3123 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3124 keyboard::SetTouchKeyboardEnabled(false);
3125 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3127 // Verify that disabling the policy takes effect immediately and that the user
3128 // cannot enable the keyboard.
3129 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3130 POLICY_LEVEL_MANDATORY
,
3132 new base::FundamentalValue(false),
3134 UpdateProviderPolicy(policies
);
3135 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3136 keyboard::SetTouchKeyboardEnabled(true);
3137 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3144 static const char* kRestoredURLs
[] = {
3145 "http://aaa.com/empty.html",
3146 "http://bbb.com/empty.html",
3149 bool IsNonSwitchArgument(const base::CommandLine::StringType
& s
) {
3150 return s
.empty() || s
[0] != '-';
3155 // Similar to PolicyTest but allows setting policies before the browser is
3156 // created. Each test parameter is a method that sets up the early policies
3157 // and stores the expected startup URLs in |expected_urls_|.
3158 class RestoreOnStartupPolicyTest
3159 : public PolicyTest
,
3160 public testing::WithParamInterface
<
3161 void (RestoreOnStartupPolicyTest::*)(void)> {
3163 RestoreOnStartupPolicyTest() {}
3164 virtual ~RestoreOnStartupPolicyTest() {}
3166 #if defined(OS_CHROMEOS)
3167 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
3168 // TODO(nkostylev): Investigate if we can remove this switch.
3169 command_line
->AppendSwitch(switches::kCreateBrowserOnStartupForTests
);
3170 PolicyTest::SetUpCommandLine(command_line
);
3174 void SetUpInProcessBrowserTestFixture() override
{
3175 PolicyTest::SetUpInProcessBrowserTestFixture();
3176 // Set early policies now, before the browser is created.
3177 (this->*(GetParam()))();
3179 // Remove the non-switch arguments, so that session restore kicks in for
3181 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
3182 base::CommandLine::StringVector argv
= command_line
->argv();
3183 argv
.erase(std::remove_if(++argv
.begin(), argv
.end(), IsNonSwitchArgument
),
3185 command_line
->InitFromArgv(argv
);
3186 ASSERT_TRUE(std::equal(argv
.begin(), argv
.end(),
3187 command_line
->argv().begin()));
3190 void SetUpOnMainThread() override
{
3191 BrowserThread::PostTask(
3195 RedirectHostsToTestData
, kRestoredURLs
, arraysize(kRestoredURLs
)));
3198 void HomepageIsNotNTP() {
3199 // Verifies that policy can set the startup pages to the homepage, when
3200 // the homepage is not the NTP.
3203 key::kRestoreOnStartup
,
3204 POLICY_LEVEL_MANDATORY
,
3206 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3208 policies
.Set(key::kHomepageIsNewTabPage
,
3209 POLICY_LEVEL_MANDATORY
,
3211 new base::FundamentalValue(false),
3213 policies
.Set(key::kHomepageLocation
,
3214 POLICY_LEVEL_MANDATORY
,
3216 new base::StringValue(kRestoredURLs
[1]),
3218 provider_
.UpdateChromePolicy(policies
);
3220 expected_urls_
.push_back(GURL(kRestoredURLs
[1]));
3223 void HomepageIsNTP() {
3224 // Verifies that policy can set the startup pages to the homepage, when
3225 // the homepage is the NTP.
3228 key::kRestoreOnStartup
,
3229 POLICY_LEVEL_MANDATORY
,
3231 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3233 policies
.Set(key::kHomepageIsNewTabPage
,
3234 POLICY_LEVEL_MANDATORY
,
3236 new base::FundamentalValue(true),
3238 provider_
.UpdateChromePolicy(policies
);
3240 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3244 // Verifies that policy can set the startup pages to a list of URLs.
3245 base::ListValue urls
;
3246 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
) {
3247 urls
.Append(new base::StringValue(kRestoredURLs
[i
]));
3248 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3251 policies
.Set(key::kRestoreOnStartup
,
3252 POLICY_LEVEL_MANDATORY
,
3254 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs
),
3257 key::kRestoreOnStartupURLs
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3258 urls
.DeepCopy(), NULL
);
3259 provider_
.UpdateChromePolicy(policies
);
3263 // Verifies that policy can set the startup page to the NTP.
3266 key::kRestoreOnStartup
,
3267 POLICY_LEVEL_MANDATORY
,
3269 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab
),
3271 provider_
.UpdateChromePolicy(policies
);
3272 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3276 // Verifies that policy can set the startup pages to the last session.
3278 policies
.Set(key::kRestoreOnStartup
,
3279 POLICY_LEVEL_MANDATORY
,
3281 new base::FundamentalValue(SessionStartupPref::kPrefValueLast
),
3283 provider_
.UpdateChromePolicy(policies
);
3284 // This should restore the tabs opened at PRE_RunTest below.
3285 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
)
3286 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3289 std::vector
<GURL
> expected_urls_
;
3292 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, PRE_RunTest
) {
3293 // Open some tabs to verify if they are restored after the browser restarts.
3294 // Most policy settings override this, except kPrefValueLast which enforces
3296 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs
[0]));
3297 for (size_t i
= 1; i
< arraysize(kRestoredURLs
); ++i
) {
3298 content::WindowedNotificationObserver
observer(
3299 content::NOTIFICATION_LOAD_STOP
,
3300 content::NotificationService::AllSources());
3301 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs
[i
]),
3302 ui::PAGE_TRANSITION_LINK
);
3307 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, RunTest
) {
3308 #if defined(OS_WIN) && defined(USE_ASH)
3309 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3310 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3311 switches::kAshBrowserTests
))
3315 TabStripModel
* model
= browser()->tab_strip_model();
3316 int size
= static_cast<int>(expected_urls_
.size());
3317 EXPECT_EQ(size
, model
->count());
3318 for (int i
= 0; i
< size
&& i
< model
->count(); ++i
) {
3319 EXPECT_EQ(expected_urls_
[i
], model
->GetWebContentsAt(i
)->GetURL());
3323 INSTANTIATE_TEST_CASE_P(
3324 RestoreOnStartupPolicyTestInstance
,
3325 RestoreOnStartupPolicyTest
,
3326 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP
,
3327 &RestoreOnStartupPolicyTest::HomepageIsNTP
,
3328 &RestoreOnStartupPolicyTest::ListOfURLs
,
3329 &RestoreOnStartupPolicyTest::NTP
,
3330 &RestoreOnStartupPolicyTest::Last
));
3332 // Similar to PolicyTest but sets a couple of policies before the browser is
3334 class PolicyStatisticsCollectorTest
: public PolicyTest
{
3336 PolicyStatisticsCollectorTest() {}
3337 ~PolicyStatisticsCollectorTest() override
{}
3339 void SetUpInProcessBrowserTestFixture() override
{
3340 PolicyTest::SetUpInProcessBrowserTestFixture();
3342 policies
.Set(key::kShowHomeButton
,
3343 POLICY_LEVEL_MANDATORY
,
3345 new base::FundamentalValue(true),
3347 policies
.Set(key::kBookmarkBarEnabled
,
3348 POLICY_LEVEL_MANDATORY
,
3350 new base::FundamentalValue(false),
3352 policies
.Set(key::kHomepageLocation
,
3353 POLICY_LEVEL_MANDATORY
,
3355 new base::StringValue("http://chromium.org"),
3357 provider_
.UpdateChromePolicy(policies
);
3361 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest
, Startup
) {
3362 // Verifies that policy usage histograms are collected at startup.
3364 // BrowserPolicyConnector::Init() has already been called. Make sure the
3365 // CompleteInitialization() task has executed as well.
3366 content::RunAllPendingInMessageLoop();
3368 GURL kAboutHistograms
= GURL(std::string(url::kAboutScheme
) +
3369 std::string(url::kStandardSchemeSeparator
) +
3370 std::string(content::kChromeUIHistogramHost
));
3371 ui_test_utils::NavigateToURL(browser(), kAboutHistograms
);
3372 content::WebContents
* contents
=
3373 browser()->tab_strip_model()->GetActiveWebContents();
3375 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3377 "var nodes = document.querySelectorAll('body > pre');"
3379 "for (var i = 0; i < nodes.length; ++i) {"
3380 " var text = nodes[i].innerHTML;"
3381 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3386 "domAutomationController.send(result);",
3388 ASSERT_FALSE(text
.empty());
3389 const std::string kExpectedLabel
=
3390 "Histogram: Enterprise.Policies recorded 3 samples";
3391 EXPECT_EQ(kExpectedLabel
, text
.substr(0, kExpectedLabel
.size()));
3392 // HomepageLocation has policy ID 1.
3393 EXPECT_NE(std::string::npos
, text
.find("<br>1 ---"));
3394 // ShowHomeButton has policy ID 35.
3395 EXPECT_NE(std::string::npos
, text
.find("<br>35 ---"));
3396 // BookmarkBarEnabled has policy ID 82.
3397 EXPECT_NE(std::string::npos
, text
.find("<br>82 ---"));
3400 class MediaStreamDevicesControllerBrowserTest
3401 : public PolicyTest
,
3402 public testing::WithParamInterface
<bool> {
3404 MediaStreamDevicesControllerBrowserTest()
3405 : request_url_allowed_via_whitelist_(false),
3406 request_url_("http://www.example.com/foo") {
3407 policy_value_
= GetParam();
3409 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3411 // Configure a given policy map. The |policy_name| is the name of either the
3412 // audio or video capture allow policy and must never be NULL.
3413 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3414 // policy is set. If non-NULL, the whitelist policy is set to contain either
3415 // the |allow_rule| (if non-NULL) or an "allow all" wildcard.
3416 void ConfigurePolicyMap(PolicyMap
* policies
, const char* policy_name
,
3417 const char* whitelist_policy
,
3418 const char* allow_rule
) {
3419 policies
->Set(policy_name
,
3420 POLICY_LEVEL_MANDATORY
,
3422 new base::FundamentalValue(policy_value_
),
3425 if (whitelist_policy
) {
3426 // Add an entry to the whitelist that allows the specified URL regardless
3427 // of the setting of kAudioCapturedAllowed.
3428 base::ListValue
* list
= new base::ListValue();
3430 list
->AppendString(allow_rule
);
3431 request_url_allowed_via_whitelist_
= true;
3433 list
->AppendString(ContentSettingsPattern::Wildcard().ToString());
3434 // We should ignore all wildcard entries in the whitelist, so even
3435 // though we've added an entry, it should be ignored and our expectation
3436 // is that the request has not been allowed via the whitelist.
3437 request_url_allowed_via_whitelist_
= false;
3439 policies
->Set(whitelist_policy
, POLICY_LEVEL_MANDATORY
,
3440 POLICY_SCOPE_USER
, list
, NULL
);
3444 void Accept(const content::MediaStreamDevices
& devices
,
3445 content::MediaStreamRequestResult result
,
3446 scoped_ptr
<content::MediaStreamUI
> ui
) {
3447 if (policy_value_
|| request_url_allowed_via_whitelist_
) {
3448 ASSERT_EQ(1U, devices
.size());
3449 ASSERT_EQ("fake_dev", devices
[0].id
);
3451 ASSERT_EQ(0U, devices
.size());
3455 void FinishAudioTest() {
3456 content::MediaStreamRequest
request(0, 0, 0,
3457 request_url_
.GetOrigin(), false,
3458 content::MEDIA_DEVICE_ACCESS
,
3459 std::string(), std::string(),
3460 content::MEDIA_DEVICE_AUDIO_CAPTURE
,
3461 content::MEDIA_NO_SERVICE
);
3462 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3463 // and microphone permissions at the same time.
3464 MediaStreamDevicesController
controller(
3465 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3466 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3467 if (controller
.IsAskingForAudio())
3468 controller
.PermissionGranted();
3470 base::MessageLoop::current()->QuitWhenIdle();
3473 void FinishVideoTest() {
3474 content::MediaStreamRequest
request(0, 0, 0,
3475 request_url_
.GetOrigin(), false,
3476 content::MEDIA_DEVICE_ACCESS
,
3479 content::MEDIA_NO_SERVICE
,
3480 content::MEDIA_DEVICE_VIDEO_CAPTURE
);
3481 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3482 // and microphone permissions at the same time.
3483 MediaStreamDevicesController
controller(
3484 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3485 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3486 if (controller
.IsAskingForVideo())
3487 controller
.PermissionGranted();
3489 base::MessageLoop::current()->QuitWhenIdle();
3493 bool request_url_allowed_via_whitelist_
;
3495 static const char kExampleRequestPattern
[];
3499 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern
[] =
3500 "http://[*.]example.com/";
3502 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3503 AudioCaptureAllowed
) {
3504 content::MediaStreamDevices audio_devices
;
3505 content::MediaStreamDevice
fake_audio_device(
3506 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3507 audio_devices
.push_back(fake_audio_device
);
3510 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
, NULL
, NULL
);
3511 UpdateProviderPolicy(policies
);
3513 content::BrowserThread::PostTaskAndReply(
3514 content::BrowserThread::IO
, FROM_HERE
,
3515 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3516 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3518 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3521 base::MessageLoop::current()->Run();
3524 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3525 AudioCaptureAllowedUrls
) {
3526 content::MediaStreamDevices audio_devices
;
3527 content::MediaStreamDevice
fake_audio_device(
3528 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3529 audio_devices
.push_back(fake_audio_device
);
3531 const char* allow_pattern
[] = {
3532 kExampleRequestPattern
,
3533 // This will set an allow-all policy whitelist. Since we do not allow
3534 // setting an allow-all entry in the whitelist, this entry should be ignored
3535 // and therefore the request should be denied.
3539 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3541 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
,
3542 key::kAudioCaptureAllowedUrls
, allow_pattern
[i
]);
3543 UpdateProviderPolicy(policies
);
3545 content::BrowserThread::PostTaskAndReply(
3546 content::BrowserThread::IO
, FROM_HERE
,
3548 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3549 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3552 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3555 base::MessageLoop::current()->Run();
3559 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3560 VideoCaptureAllowed
) {
3561 content::MediaStreamDevices video_devices
;
3562 content::MediaStreamDevice
fake_video_device(
3563 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3564 video_devices
.push_back(fake_video_device
);
3567 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
, NULL
, NULL
);
3568 UpdateProviderPolicy(policies
);
3570 content::BrowserThread::PostTaskAndReply(
3571 content::BrowserThread::IO
, FROM_HERE
,
3572 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3573 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3575 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3578 base::MessageLoop::current()->Run();
3581 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3582 VideoCaptureAllowedUrls
) {
3583 content::MediaStreamDevices video_devices
;
3584 content::MediaStreamDevice
fake_video_device(
3585 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3586 video_devices
.push_back(fake_video_device
);
3588 const char* allow_pattern
[] = {
3589 kExampleRequestPattern
,
3590 // This will set an allow-all policy whitelist. Since we do not allow
3591 // setting an allow-all entry in the whitelist, this entry should be ignored
3592 // and therefore the request should be denied.
3596 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3598 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
,
3599 key::kVideoCaptureAllowedUrls
, allow_pattern
[i
]);
3600 UpdateProviderPolicy(policies
);
3602 content::BrowserThread::PostTaskAndReply(
3603 content::BrowserThread::IO
, FROM_HERE
,
3604 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3605 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3608 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3611 base::MessageLoop::current()->Run();
3615 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance
,
3616 MediaStreamDevicesControllerBrowserTest
,
3619 // Test that when extended reporting opt-in is disabled by policy, the
3620 // opt-in checkbox does not appear on SSL blocking pages.
3621 IN_PROC_BROWSER_TEST_F(PolicyTest
, SafeBrowsingExtendedReportingOptInAllowed
) {
3622 net::SpawnedTestServer
https_server_expired(
3623 net::SpawnedTestServer::TYPE_HTTPS
,
3624 net::SpawnedTestServer::SSLOptions(
3625 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3626 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3627 ASSERT_TRUE(https_server_expired
.Start());
3629 // Set the enterprise policy to disallow opt-in.
3630 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3632 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3634 policies
.Set(key::kSafeBrowsingExtendedReportingOptInAllowed
,
3635 POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3636 new base::FundamentalValue(false), NULL
);
3637 UpdateProviderPolicy(policies
);
3639 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3641 // Navigate to an SSL error page.
3642 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3644 const content::InterstitialPage
* const interstitial
=
3645 content::InterstitialPage::GetInterstitialPage(
3646 browser()->tab_strip_model()->GetActiveWebContents());
3647 ASSERT_TRUE(interstitial
);
3648 ASSERT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3649 content::RenderViewHost
* const rvh
=
3650 interstitial
->GetMainFrame()->GetRenderViewHost();
3653 // Check that the checkbox is not visible.
3655 const std::string command
= base::StringPrintf(
3656 "var node = document.getElementById('extended-reporting-opt-in');"
3658 " window.domAutomationController.send(node.offsetWidth > 0 || "
3659 " node.offsetHeight > 0 ? %d : %d);"
3661 // The node should be present but not visible, so trigger an error
3662 // by sending false if it's not present.
3663 " window.domAutomationController.send(%d);"
3665 SecurityInterstitialPage::CMD_TEXT_FOUND
,
3666 SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
,
3667 SecurityInterstitialPage::CMD_ERROR
);
3668 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(rvh
, command
, &result
));
3669 EXPECT_EQ(SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
, result
);
3672 // Test that when SSL error overriding is allowed by policy (default), the
3673 // proceed link appears on SSL blocking pages.
3674 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingAllowed
) {
3675 net::SpawnedTestServer
https_server_expired(
3676 net::SpawnedTestServer::TYPE_HTTPS
,
3677 net::SpawnedTestServer::SSLOptions(
3678 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3679 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3680 ASSERT_TRUE(https_server_expired
.Start());
3682 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3684 // Policy should allow overriding by default.
3685 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3687 // Policy allows overriding - navigate to an SSL error page and expect the
3689 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3691 const content::InterstitialPage
* const interstitial
=
3692 content::InterstitialPage::GetInterstitialPage(
3693 browser()->tab_strip_model()->GetActiveWebContents());
3694 ASSERT_TRUE(interstitial
);
3695 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3697 // The interstitial should display the proceed link.
3698 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3699 interstitial
, "proceed-link"));
3702 // Test that when SSL error overriding is disallowed by policy, the
3703 // proceed link does not appear on SSL blocking pages and users should not
3704 // be able to proceed.
3705 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingDisallowed
) {
3706 net::SpawnedTestServer
https_server_expired(
3707 net::SpawnedTestServer::TYPE_HTTPS
,
3708 net::SpawnedTestServer::SSLOptions(
3709 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3710 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3711 ASSERT_TRUE(https_server_expired
.Start());
3713 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3714 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3716 // Disallowing the proceed link by setting the policy to |false|.
3718 policies
.Set(key::kSSLErrorOverrideAllowed
, POLICY_LEVEL_MANDATORY
,
3719 POLICY_SCOPE_USER
, new base::FundamentalValue(false), NULL
);
3720 UpdateProviderPolicy(policies
);
3722 // Policy should not allow overriding anymore.
3723 EXPECT_FALSE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3725 // Policy disallows overriding - navigate to an SSL error page and expect no
3727 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3728 const content::InterstitialPage
* const interstitial
=
3729 content::InterstitialPage::GetInterstitialPage(
3730 browser()->tab_strip_model()->GetActiveWebContents());
3731 ASSERT_TRUE(interstitial
);
3732 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3734 // The interstitial should not display the proceed link.
3735 EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3736 interstitial
, "proceed-link"));
3738 // The interstitial should not proceed, even if the command is sent in
3739 // some other way (e.g., via the keyboard shortcut).
3740 content::InterstitialPageDelegate
* interstitial_delegate
=
3741 content::InterstitialPage::GetInterstitialPage(
3742 browser()->tab_strip_model()->GetActiveWebContents())
3743 ->GetDelegateForTesting();
3744 ASSERT_EQ(SSLBlockingPage::kTypeForTesting
,
3745 interstitial_delegate
->GetTypeForTesting());
3746 SSLBlockingPage
* ssl_delegate
=
3747 static_cast<SSLBlockingPage
*>(interstitial_delegate
);
3748 ssl_delegate
->CommandReceived(
3749 base::IntToString(SecurityInterstitialPage::CMD_PROCEED
));
3750 EXPECT_TRUE(interstitial
);
3751 EXPECT_TRUE(browser()
3753 ->GetActiveWebContents()
3754 ->ShowingInterstitialPage());
3757 #if !defined(OS_CHROMEOS)
3758 // Similar to PolicyTest but sets the proper policy before the browser is
3760 class PolicyVariationsServiceTest
: public PolicyTest
{
3762 void SetUpInProcessBrowserTestFixture() override
{
3763 PolicyTest::SetUpInProcessBrowserTestFixture();
3765 policies
.Set(key::kVariationsRestrictParameter
,
3766 POLICY_LEVEL_MANDATORY
,
3768 new base::StringValue("restricted"),
3770 provider_
.UpdateChromePolicy(policies
);
3774 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest
, VariationsURLIsValid
) {
3775 const std::string default_variations_url
=
3776 variations::VariationsService::GetDefaultVariationsServerURLForTesting();
3778 // g_browser_process->variations_service() is null by default in Chromium
3779 // builds, so construct a VariationsService locally instead.
3780 scoped_ptr
<variations::VariationsService
> service
=
3781 variations::VariationsService::CreateForTesting(
3782 make_scoped_ptr(new ChromeVariationsServiceClient()),
3783 g_browser_process
->local_state());
3785 const GURL url
= service
->GetVariationsServerURL(
3786 g_browser_process
->local_state(), std::string());
3787 EXPECT_TRUE(base::StartsWith(url
.spec(), default_variations_url
,
3788 base::CompareCase::SENSITIVE
));
3790 EXPECT_TRUE(net::GetValueForKeyInQuery(url
, "restrict", &value
));
3791 EXPECT_EQ("restricted", value
);
3794 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistSelective
) {
3795 base::ListValue blacklist
;
3796 blacklist
.Append(new base::StringValue("host.name"));
3798 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3799 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3800 UpdateProviderPolicy(policies
);
3802 PrefService
* prefs
= browser()->profile()->GetPrefs();
3803 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3804 prefs
, "host.name"));
3805 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3806 prefs
, "other.host.name"));
3809 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistWildcard
) {
3810 base::ListValue blacklist
;
3811 blacklist
.Append(new base::StringValue("*"));
3813 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3814 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3815 UpdateProviderPolicy(policies
);
3817 PrefService
* prefs
= browser()->profile()->GetPrefs();
3818 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3819 prefs
, "host.name"));
3820 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3821 prefs
, "other.host.name"));
3824 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingWhitelist
) {
3825 base::ListValue blacklist
;
3826 blacklist
.Append(new base::StringValue("*"));
3827 base::ListValue whitelist
;
3828 whitelist
.Append(new base::StringValue("host.name"));
3830 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3831 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3832 policies
.Set(key::kNativeMessagingWhitelist
, POLICY_LEVEL_MANDATORY
,
3833 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
3834 UpdateProviderPolicy(policies
);
3836 PrefService
* prefs
= browser()->profile()->GetPrefs();
3837 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3838 prefs
, "host.name"));
3839 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3840 prefs
, "other.host.name"));
3843 #endif // !defined(CHROME_OS)
3846 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3847 // Sets the hardware acceleration mode policy before the browser is started.
3848 class HardwareAccelerationModePolicyTest
: public PolicyTest
{
3850 HardwareAccelerationModePolicyTest() {}
3852 void SetUpInProcessBrowserTestFixture() override
{
3853 PolicyTest::SetUpInProcessBrowserTestFixture();
3855 policies
.Set(key::kHardwareAccelerationModeEnabled
,
3856 POLICY_LEVEL_MANDATORY
,
3858 new base::FundamentalValue(false),
3860 provider_
.UpdateChromePolicy(policies
);
3864 IN_PROC_BROWSER_TEST_F(HardwareAccelerationModePolicyTest
,
3865 HardwareAccelerationDisabled
) {
3866 // Verifies that hardware acceleration can be disabled with policy.
3868 content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr));
3870 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3872 } // namespace policy