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/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_number_conversions.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/stringprintf.h"
25 #include "base/strings/utf_string_conversions.h"
26 #include "base/test/test_file_util.h"
27 #include "base/threading/sequenced_worker_pool.h"
28 #include "base/time/time.h"
29 #include "base/values.h"
30 #include "chrome/app/chrome_command_ids.h"
31 #include "chrome/browser/background/background_contents_service.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
35 #include "chrome/browser/devtools/devtools_window_testing.h"
36 #include "chrome/browser/download/download_prefs.h"
37 #include "chrome/browser/extensions/api/messaging/message_service.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/extension_management_constants.h"
40 #include "chrome/browser/extensions/extension_management_test_util.h"
41 #include "chrome/browser/extensions/extension_service.h"
42 #include "chrome/browser/extensions/shared_module_service.h"
43 #include "chrome/browser/extensions/unpacked_installer.h"
44 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
45 #include "chrome/browser/extensions/updater/extension_updater.h"
46 #include "chrome/browser/infobars/infobar_service.h"
47 #include "chrome/browser/interstitials/security_interstitial_page.h"
48 #include "chrome/browser/interstitials/security_interstitial_page_test_utils.h"
49 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
50 #include "chrome/browser/media/media_stream_devices_controller.h"
51 #include "chrome/browser/metrics/variations/variations_service.h"
52 #include "chrome/browser/net/prediction_options.h"
53 #include "chrome/browser/net/url_request_mock_util.h"
54 #include "chrome/browser/plugins/plugin_prefs.h"
55 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
56 #include "chrome/browser/policy/profile_policy_connector.h"
57 #include "chrome/browser/policy/profile_policy_connector_factory.h"
58 #include "chrome/browser/prefs/session_startup_pref.h"
59 #include "chrome/browser/profiles/profile.h"
60 #include "chrome/browser/search/instant_service.h"
61 #include "chrome/browser/search/instant_service_factory.h"
62 #include "chrome/browser/search/search.h"
63 #include "chrome/browser/search_engines/template_url_service_factory.h"
64 #include "chrome/browser/ssl/ssl_blocking_page.h"
65 #include "chrome/browser/translate/chrome_translate_client.h"
66 #include "chrome/browser/translate/cld_data_harness.h"
67 #include "chrome/browser/translate/cld_data_harness_factory.h"
68 #include "chrome/browser/translate/translate_service.h"
69 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
70 #include "chrome/browser/ui/browser.h"
71 #include "chrome/browser/ui/browser_commands.h"
72 #include "chrome/browser/ui/browser_list.h"
73 #include "chrome/browser/ui/browser_tabstrip.h"
74 #include "chrome/browser/ui/browser_window.h"
75 #include "chrome/browser/ui/host_desktop.h"
76 #include "chrome/browser/ui/location_bar/location_bar.h"
77 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
78 #include "chrome/browser/ui/omnibox/omnibox_view.h"
79 #include "chrome/browser/ui/tabs/tab_strip_model.h"
80 #include "chrome/common/chrome_paths.h"
81 #include "chrome/common/chrome_switches.h"
82 #include "chrome/common/extensions/extension_constants.h"
83 #include "chrome/common/extensions/features/feature_channel.h"
84 #include "chrome/common/pref_names.h"
85 #include "chrome/common/url_constants.h"
86 #include "chrome/grit/generated_resources.h"
87 #include "chrome/test/base/in_process_browser_test.h"
88 #include "chrome/test/base/test_switches.h"
89 #include "chrome/test/base/ui_test_utils.h"
90 #include "components/content_settings/core/common/content_settings.h"
91 #include "components/content_settings/core/common/content_settings_pattern.h"
92 #include "components/infobars/core/infobar.h"
93 #include "components/omnibox/browser/autocomplete_controller.h"
94 #include "components/policy/core/browser/browser_policy_connector.h"
95 #include "components/policy/core/common/external_data_fetcher.h"
96 #include "components/policy/core/common/mock_configuration_policy_provider.h"
97 #include "components/policy/core/common/policy_map.h"
98 #include "components/policy/core/common/policy_pref_names.h"
99 #include "components/policy/core/common/policy_service.h"
100 #include "components/policy/core/common/policy_service_impl.h"
101 #include "components/search_engines/template_url.h"
102 #include "components/search_engines/template_url_service.h"
103 #include "components/translate/core/browser/language_state.h"
104 #include "components/translate/core/browser/translate_infobar_delegate.h"
105 #include "content/public/browser/browser_child_process_host_iterator.h"
106 #include "content/public/browser/browser_context.h"
107 #include "content/public/browser/browser_thread.h"
108 #include "content/public/browser/child_process_data.h"
109 #include "content/public/browser/download_item.h"
110 #include "content/public/browser/download_manager.h"
111 #include "content/public/browser/gpu_data_manager.h"
112 #include "content/public/browser/interstitial_page.h"
113 #include "content/public/browser/notification_details.h"
114 #include "content/public/browser/notification_observer.h"
115 #include "content/public/browser/notification_registrar.h"
116 #include "content/public/browser/notification_service.h"
117 #include "content/public/browser/notification_source.h"
118 #include "content/public/browser/notification_types.h"
119 #include "content/public/browser/plugin_service.h"
120 #include "content/public/browser/render_frame_host.h"
121 #include "content/public/browser/render_process_host.h"
122 #include "content/public/browser/render_view_host.h"
123 #include "content/public/browser/web_contents.h"
124 #include "content/public/common/content_constants.h"
125 #include "content/public/common/content_paths.h"
126 #include "content/public/common/process_type.h"
127 #include "content/public/common/result_codes.h"
128 #include "content/public/common/url_constants.h"
129 #include "content/public/common/webplugininfo.h"
130 #include "content/public/test/browser_test_utils.h"
131 #include "content/public/test/download_test_observer.h"
132 #include "content/public/test/mock_notification_observer.h"
133 #include "content/public/test/test_navigation_observer.h"
134 #include "content/public/test/test_utils.h"
135 #include "extensions/browser/extension_dialog_auto_confirm.h"
136 #include "extensions/browser/extension_host.h"
137 #include "extensions/browser/extension_prefs.h"
138 #include "extensions/browser/extension_registry.h"
139 #include "extensions/browser/extension_system.h"
140 #include "extensions/browser/process_manager.h"
141 #include "extensions/browser/test_extension_registry_observer.h"
142 #include "extensions/browser/uninstall_reason.h"
143 #include "extensions/common/constants.h"
144 #include "extensions/common/extension.h"
145 #include "extensions/common/extension_set.h"
146 #include "extensions/common/manifest_handlers/shared_module_info.h"
147 #include "net/base/net_errors.h"
148 #include "net/base/net_util.h"
149 #include "net/base/url_util.h"
150 #include "net/http/http_stream_factory.h"
151 #include "net/ssl/ssl_config.h"
152 #include "net/ssl/ssl_config_service.h"
153 #include "net/test/spawned_test_server/spawned_test_server.h"
154 #include "net/test/url_request/url_request_failed_job.h"
155 #include "net/test/url_request/url_request_mock_http_job.h"
156 #include "net/url_request/url_request.h"
157 #include "net/url_request/url_request_filter.h"
158 #include "net/url_request/url_request_interceptor.h"
159 #include "policy/policy_constants.h"
160 #include "testing/gmock/include/gmock/gmock.h"
161 #include "testing/gtest/include/gtest/gtest.h"
162 #include "third_party/WebKit/public/web/WebInputEvent.h"
163 #include "ui/base/l10n/l10n_util.h"
164 #include "ui/base/page_transition_types.h"
165 #include "ui/base/resource/resource_bundle.h"
166 #include "url/gurl.h"
168 #if defined(OS_CHROMEOS)
169 #include "ash/accelerators/accelerator_controller.h"
170 #include "ash/accelerators/accelerator_table.h"
171 #include "ash/shell.h"
172 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
173 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
174 #include "chrome/browser/profiles/profile_manager.h"
175 #include "chrome/browser/ui/ash/chrome_screenshot_grabber.h"
176 #include "chromeos/audio/cras_audio_handler.h"
177 #include "ui/chromeos/accessibility_types.h"
178 #include "ui/keyboard/keyboard_util.h"
179 #include "ui/snapshot/screenshot_grabber.h"
182 #if !defined(OS_MACOSX)
183 #include "base/basictypes.h"
184 #include "base/compiler_specific.h"
185 #include "chrome/browser/ui/extensions/app_launch_params.h"
186 #include "chrome/browser/ui/extensions/application_launch.h"
187 #include "extensions/browser/app_window/app_window.h"
188 #include "extensions/browser/app_window/app_window_registry.h"
189 #include "extensions/browser/app_window/native_app_window.h"
190 #include "ui/base/window_open_disposition.h"
193 using content::BrowserThread
;
194 using net::URLRequestMockHTTPJob
;
196 using testing::Return
;
203 #if defined(OS_CHROMEOS)
204 const int kOneHourInMs
= 60 * 60 * 1000;
205 const int kThreeHoursInMs
= 180 * 60 * 1000;
208 const char kURL
[] = "http://example.com";
209 const char kCookieValue
[] = "converted=true";
210 // Assigned to Philip J. Fry to fix eventually.
211 const char kCookieOptions
[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
213 const base::FilePath::CharType kTestExtensionsDir
[] =
214 FILE_PATH_LITERAL("extensions");
215 const base::FilePath::CharType kGoodCrxName
[] = FILE_PATH_LITERAL("good.crx");
216 const base::FilePath::CharType kAdBlockCrxName
[] =
217 FILE_PATH_LITERAL("adblock.crx");
218 const base::FilePath::CharType kHostedAppCrxName
[] =
219 FILE_PATH_LITERAL("hosted_app.crx");
221 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
222 const char kAdBlockCrxId
[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
223 const char kHostedAppCrxId
[] = "kbmnembihfiondgfjekmnmcbddelicoi";
225 const base::FilePath::CharType kGood2CrxManifestName
[] =
226 FILE_PATH_LITERAL("good2_update_manifest.xml");
227 const base::FilePath::CharType kGoodV1CrxManifestName
[] =
228 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
229 const base::FilePath::CharType kGoodV1CrxName
[] =
230 FILE_PATH_LITERAL("good_v1.crx");
231 const base::FilePath::CharType kGoodUnpackedExt
[] =
232 FILE_PATH_LITERAL("good_unpacked");
233 const base::FilePath::CharType kAppUnpackedExt
[] =
234 FILE_PATH_LITERAL("app");
236 #if !defined(OS_MACOSX)
237 const base::FilePath::CharType kUnpackedFullscreenAppName
[] =
238 FILE_PATH_LITERAL("fullscreen_app");
239 #endif // !defined(OS_MACOSX)
241 // Filters requests to the hosts in |urls| and redirects them to the test data
242 // dir through URLRequestMockHTTPJobs.
243 void RedirectHostsToTestData(const char* const urls
[], size_t size
) {
244 // Map the given hosts to the test data dir.
245 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
246 base::FilePath base_path
;
247 PathService::Get(chrome::DIR_TEST_DATA
, &base_path
);
248 for (size_t i
= 0; i
< size
; ++i
) {
249 const GURL
url(urls
[i
]);
250 EXPECT_TRUE(url
.is_valid());
251 filter
->AddUrlInterceptor(url
,
252 URLRequestMockHTTPJob::CreateInterceptor(
253 base_path
, BrowserThread::GetBlockingPool()));
257 // Remove filters for requests to the hosts in |urls|.
258 void UndoRedirectHostsToTestData(const char* const urls
[], size_t size
) {
259 // Map the given hosts to the test data dir.
260 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
261 for (size_t i
= 0; i
< size
; ++i
) {
262 const GURL
url(urls
[i
]);
263 EXPECT_TRUE(url
.is_valid());
264 filter
->RemoveUrlHandler(url
);
268 // Fails requests using ERR_CONNECTION_RESET.
269 class FailedJobInterceptor
: public net::URLRequestInterceptor
{
271 FailedJobInterceptor() {}
272 ~FailedJobInterceptor() override
{}
274 // URLRequestInterceptor implementation:
275 net::URLRequestJob
* MaybeInterceptRequest(
276 net::URLRequest
* request
,
277 net::NetworkDelegate
* network_delegate
) const override
{
278 return new net::URLRequestFailedJob(request
, network_delegate
,
279 net::ERR_CONNECTION_RESET
);
283 DISALLOW_COPY_AND_ASSIGN(FailedJobInterceptor
);
286 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
287 class MakeRequestFail
{
289 // Sets up the filter on IO thread such that requests to |host| fail.
290 explicit MakeRequestFail(const std::string
& host
) : host_(host
) {
291 BrowserThread::PostTaskAndReply(
292 BrowserThread::IO
, FROM_HERE
,
293 base::Bind(MakeRequestFailOnIO
, host_
),
294 base::MessageLoop::QuitClosure());
295 content::RunMessageLoop();
298 BrowserThread::PostTaskAndReply(
299 BrowserThread::IO
, FROM_HERE
,
300 base::Bind(UndoMakeRequestFailOnIO
, host_
),
301 base::MessageLoop::QuitClosure());
302 content::RunMessageLoop();
306 // Filters requests to the |host| such that they fail. Run on IO thread.
307 static void MakeRequestFailOnIO(const std::string
& host
) {
308 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
309 filter
->AddHostnameInterceptor(
311 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
312 filter
->AddHostnameInterceptor(
314 scoped_ptr
<net::URLRequestInterceptor
>(new FailedJobInterceptor()));
317 // Remove filters for requests to the |host|. Run on IO thread.
318 static void UndoMakeRequestFailOnIO(const std::string
& host
) {
319 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
320 filter
->RemoveHostnameHandler("http", host
);
321 filter
->RemoveHostnameHandler("https", host
);
324 const std::string host_
;
327 // Verifies that the given url |spec| can be opened. This assumes that |spec|
328 // points at empty.html in the test data dir.
329 void CheckCanOpenURL(Browser
* browser
, const char* spec
) {
331 ui_test_utils::NavigateToURL(browser
, url
);
332 content::WebContents
* contents
=
333 browser
->tab_strip_model()->GetActiveWebContents();
334 EXPECT_EQ(url
, contents
->GetURL());
335 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
336 base::string16 title
=
337 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
338 EXPECT_NE(title
, contents
->GetTitle());
341 // Verifies that access to the given url |spec| is blocked.
342 void CheckURLIsBlocked(Browser
* browser
, const char* spec
) {
344 ui_test_utils::NavigateToURL(browser
, url
);
345 content::WebContents
* contents
=
346 browser
->tab_strip_model()->GetActiveWebContents();
347 EXPECT_EQ(url
, contents
->GetURL());
348 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
349 base::string16 title
=
350 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
351 EXPECT_EQ(title
, contents
->GetTitle());
353 // Verify that the expected error page is being displayed.
355 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
357 "var textContent = document.body.textContent;"
358 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
359 "domAutomationController.send(hasError);",
364 // Downloads a file named |file| and expects it to be saved to |dir|, which
366 void DownloadAndVerifyFile(
367 Browser
* browser
, const base::FilePath
& dir
, const base::FilePath
& file
) {
368 content::DownloadManager
* download_manager
=
369 content::BrowserContext::GetDownloadManager(browser
->profile());
370 content::DownloadTestObserverTerminal
observer(
372 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
373 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
374 base::FilePath downloaded
= dir
.Append(file
);
375 EXPECT_FALSE(base::PathExists(downloaded
));
376 ui_test_utils::NavigateToURL(browser
, url
);
377 observer
.WaitForFinished();
379 1u, observer
.NumDownloadsSeenInState(content::DownloadItem::COMPLETE
));
380 EXPECT_TRUE(base::PathExists(downloaded
));
381 base::FileEnumerator
enumerator(dir
, false, base::FileEnumerator::FILES
);
382 EXPECT_EQ(file
, enumerator
.Next().BaseName());
383 EXPECT_EQ(base::FilePath(), enumerator
.Next());
386 #if defined(OS_CHROMEOS)
387 int CountScreenshots() {
388 DownloadPrefs
* download_prefs
= DownloadPrefs::FromBrowserContext(
389 ProfileManager::GetActiveUserProfile());
390 base::FileEnumerator
enumerator(download_prefs
->DownloadPath(),
391 false, base::FileEnumerator::FILES
,
394 while (!enumerator
.Next().empty())
400 // Checks if WebGL is enabled in the given WebContents.
401 bool IsWebGLEnabled(content::WebContents
* contents
) {
403 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
405 "var canvas = document.createElement('canvas');"
406 "var context = canvas.getContext('webgl');"
407 "domAutomationController.send(context != null);",
412 bool IsJavascriptEnabled(content::WebContents
* contents
) {
413 scoped_ptr
<base::Value
> value
= content::ExecuteScriptAndGetValue(
414 contents
->GetMainFrame(), "123");
416 if (!value
->GetAsInteger(&result
))
417 EXPECT_EQ(base::Value::TYPE_NULL
, value
->GetType());
418 return result
== 123;
421 bool IsNetworkPredictionEnabled(PrefService
* prefs
) {
422 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs
);
425 void CopyPluginListAndQuit(std::vector
<content::WebPluginInfo
>* out
,
426 const std::vector
<content::WebPluginInfo
>& in
) {
428 base::MessageLoop::current()->QuitWhenIdle();
432 void CopyValueAndQuit(T
* out
, T in
) {
434 base::MessageLoop::current()->QuitWhenIdle();
437 void GetPluginList(std::vector
<content::WebPluginInfo
>* plugins
) {
438 content::PluginService
* service
= content::PluginService::GetInstance();
439 service
->GetPlugins(base::Bind(CopyPluginListAndQuit
, plugins
));
440 content::RunMessageLoop();
443 const content::WebPluginInfo
* GetFlashPlugin(
444 const std::vector
<content::WebPluginInfo
>& plugins
) {
445 const content::WebPluginInfo
* flash
= NULL
;
446 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
447 if (plugins
[i
].name
== base::ASCIIToUTF16(content::kFlashPluginName
)) {
452 #if defined(OFFICIAL_BUILD)
453 // Official builds bundle Flash.
457 LOG(INFO
) << "Test skipped because the Flash plugin couldn't be found.";
462 bool SetPluginEnabled(PluginPrefs
* plugin_prefs
,
463 const content::WebPluginInfo
* plugin
,
466 plugin_prefs
->EnablePlugin(enabled
, plugin
->path
,
467 base::Bind(CopyValueAndQuit
<bool>, &ok
));
468 content::RunMessageLoop();
472 int CountPluginsOnIOThread() {
474 for (content::BrowserChildProcessHostIterator iter
; !iter
.Done(); ++iter
) {
475 if (iter
.GetData().process_type
== content::PROCESS_TYPE_PLUGIN
||
476 iter
.GetData().process_type
== content::PROCESS_TYPE_PPAPI_PLUGIN
) {
485 BrowserThread::PostTaskAndReplyWithResult(
486 BrowserThread::IO
, FROM_HERE
,
487 base::Bind(CountPluginsOnIOThread
),
488 base::Bind(CopyValueAndQuit
<int>, &count
));
489 content::RunMessageLoop();
494 void FlushBlacklistPolicy() {
495 // Updates of the URLBlacklist are done on IO, after building the blacklist
496 // on the blocking pool, which is initiated from IO.
497 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
498 BrowserThread::GetBlockingPool()->FlushForTesting();
499 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
502 bool ContainsVisibleElement(content::WebContents
* contents
,
503 const std::string
& id
) {
505 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
507 "var elem = document.getElementById('" + id
+ "');"
508 "domAutomationController.send(!!elem && !elem.hidden);",
513 #if defined(OS_CHROMEOS)
514 class TestAudioObserver
: public chromeos::CrasAudioHandler::AudioObserver
{
516 TestAudioObserver() : output_mute_changed_count_(0) {
519 int output_mute_changed_count() const {
520 return output_mute_changed_count_
;
523 ~TestAudioObserver() override
{}
526 // chromeos::CrasAudioHandler::AudioObserver overrides.
527 void OnOutputMuteChanged(bool /* mute_on */) override
{
528 ++output_mute_changed_count_
;
532 int output_mute_changed_count_
;
534 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver
);
538 // This class waits until either a load stops or the WebContents is destroyed.
539 class WebContentsLoadedOrDestroyedWatcher
540 : public content::WebContentsObserver
{
542 explicit WebContentsLoadedOrDestroyedWatcher(
543 content::WebContents
* web_contents
);
544 ~WebContentsLoadedOrDestroyedWatcher() override
;
546 // Waits until the WebContents's load is done or until it is destroyed.
549 // Overridden WebContentsObserver methods.
550 void WebContentsDestroyed() override
;
551 void DidStopLoading() override
;
554 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
556 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher
);
559 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
560 content::WebContents
* web_contents
)
561 : content::WebContentsObserver(web_contents
),
562 message_loop_runner_(new content::MessageLoopRunner
) {
565 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
567 void WebContentsLoadedOrDestroyedWatcher::Wait() {
568 message_loop_runner_
->Run();
571 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
572 message_loop_runner_
->Quit();
575 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading() {
576 message_loop_runner_
->Quit();
579 #if !defined(OS_MACOSX)
581 // Observer used to wait for the creation of a new app window.
582 class TestAddAppWindowObserver
583 : public extensions::AppWindowRegistry::Observer
{
585 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry
* registry
);
586 ~TestAddAppWindowObserver() override
;
588 // extensions::AppWindowRegistry::Observer:
589 void OnAppWindowAdded(extensions::AppWindow
* app_window
) override
;
591 extensions::AppWindow
* WaitForAppWindow();
594 extensions::AppWindowRegistry
* registry_
; // Not owned.
595 extensions::AppWindow
* window_
; // Not owned.
596 base::RunLoop run_loop_
;
598 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver
);
601 TestAddAppWindowObserver::TestAddAppWindowObserver(
602 extensions::AppWindowRegistry
* registry
)
603 : registry_(registry
), window_(NULL
) {
604 registry_
->AddObserver(this);
607 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
608 registry_
->RemoveObserver(this);
611 void TestAddAppWindowObserver::OnAppWindowAdded(
612 extensions::AppWindow
* app_window
) {
613 window_
= app_window
;
617 extensions::AppWindow
* TestAddAppWindowObserver::WaitForAppWindow() {
626 class PolicyTest
: public InProcessBrowserTest
{
629 ~PolicyTest() override
{}
631 void SetUp() override
{
632 test_extension_cache_
.reset(new extensions::ExtensionCacheFake());
633 InProcessBrowserTest::SetUp();
636 void SetUpInProcessBrowserTestFixture() override
{
637 base::CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
638 EXPECT_CALL(provider_
, IsInitializationComplete(_
))
639 .WillRepeatedly(Return(true));
640 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_
);
643 void SetUpOnMainThread() override
{
644 BrowserThread::PostTask(
645 BrowserThread::IO
, FROM_HERE
,
646 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled
, true));
647 if (extension_service()->updater()) {
648 extension_service()->updater()->SetExtensionCacheForTesting(
649 test_extension_cache_
.get());
653 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
654 // instead of chrome::DIR_TEST_DATA.
655 void ServeContentTestData() {
656 base::FilePath root_http
;
657 PathService::Get(content::DIR_TEST_DATA
, &root_http
);
658 BrowserThread::PostTaskAndReply(
659 BrowserThread::IO
, FROM_HERE
,
660 base::Bind(URLRequestMockHTTPJob::AddUrlHandlers
, root_http
,
661 make_scoped_refptr(BrowserThread::GetBlockingPool())),
662 base::MessageLoop::current()->QuitWhenIdleClosure());
663 content::RunMessageLoop();
666 void SetScreenshotPolicy(bool enabled
) {
668 policies
.Set(key::kDisableScreenshots
,
669 POLICY_LEVEL_MANDATORY
,
671 new base::FundamentalValue(!enabled
),
673 UpdateProviderPolicy(policies
);
676 #if defined(OS_CHROMEOS)
677 class QuitMessageLoopAfterScreenshot
: public ui::ScreenshotGrabberObserver
{
679 void OnScreenshotCompleted(
680 ScreenshotGrabberObserver::Result screenshot_result
,
681 const base::FilePath
& screenshot_path
) override
{
682 BrowserThread::PostTaskAndReply(BrowserThread::IO
,
684 base::Bind(base::DoNothing
),
685 base::MessageLoop::QuitClosure());
688 ~QuitMessageLoopAfterScreenshot() override
{}
691 void TestScreenshotFile(bool enabled
) {
692 // AddObserver is an ash-specific method, so just replace the screenshot
693 // grabber with one we've created here.
694 scoped_ptr
<ChromeScreenshotGrabber
> chrome_screenshot_grabber(
695 new ChromeScreenshotGrabber
);
696 // ScreenshotGrabber doesn't own this observer, so the observer's lifetime
697 // is tied to the test instead.
698 chrome_screenshot_grabber
->screenshot_grabber()->AddObserver(&observer_
);
699 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
700 chrome_screenshot_grabber
.Pass());
702 SetScreenshotPolicy(enabled
);
703 ash::Shell::GetInstance()->accelerator_controller()->PerformActionIfEnabled(
704 ash::TAKE_SCREENSHOT
);
706 content::RunMessageLoop();
707 static_cast<ChromeScreenshotGrabber
*>(ash::Shell::GetInstance()
708 ->accelerator_controller()
709 ->screenshot_delegate())
710 ->screenshot_grabber()
711 ->RemoveObserver(&observer_
);
715 ExtensionService
* extension_service() {
716 extensions::ExtensionSystem
* system
=
717 extensions::ExtensionSystem::Get(browser()->profile());
718 return system
->extension_service();
721 const extensions::Extension
* InstallExtension(
722 const base::FilePath::StringType
& name
) {
723 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
724 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
725 scoped_refptr
<extensions::CrxInstaller
> installer
=
726 extensions::CrxInstaller::CreateSilent(extension_service());
727 installer
->set_allow_silent_install(true);
728 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
729 installer
->set_creation_flags(extensions::Extension::FROM_WEBSTORE
);
731 content::WindowedNotificationObserver
observer(
732 extensions::NOTIFICATION_CRX_INSTALLER_DONE
,
733 content::NotificationService::AllSources());
734 installer
->InstallCrx(extension_path
);
736 content::Details
<const extensions::Extension
> details
= observer
.details();
737 return details
.ptr();
740 const extensions::Extension
* LoadUnpackedExtension(
741 const base::FilePath::StringType
& name
, bool expect_success
) {
742 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
743 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
744 scoped_refptr
<extensions::UnpackedInstaller
> installer
=
745 extensions::UnpackedInstaller::Create(extension_service());
746 content::WindowedNotificationObserver
observer(
747 expect_success
? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
748 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR
,
749 content::NotificationService::AllSources());
750 installer
->Load(extension_path
);
753 extensions::ExtensionRegistry
* registry
=
754 extensions::ExtensionRegistry::Get(browser()->profile());
755 for (const scoped_refptr
<const extensions::Extension
>& extension
:
756 registry
->enabled_extensions()) {
757 if (extension
->path() == extension_path
)
758 return extension
.get();
763 void UninstallExtension(const std::string
& id
, bool expect_success
) {
764 if (expect_success
) {
765 extensions::TestExtensionRegistryObserver
observer(
766 extensions::ExtensionRegistry::Get(browser()->profile()));
767 extension_service()->UninstallExtension(
768 id
, extensions::UNINSTALL_REASON_FOR_TESTING
,
769 base::Bind(&base::DoNothing
), NULL
);
770 observer
.WaitForExtensionUninstalled();
772 content::WindowedNotificationObserver
observer(
773 extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
774 content::NotificationService::AllSources());
775 extension_service()->UninstallExtension(
777 extensions::UNINSTALL_REASON_FOR_TESTING
,
778 base::Bind(&base::DoNothing
),
784 void DisableExtension(const std::string
& id
) {
785 extensions::TestExtensionRegistryObserver
observer(
786 extensions::ExtensionRegistry::Get(browser()->profile()));
787 extension_service()->DisableExtension(id
,
788 extensions::Extension::DISABLE_NONE
);
789 observer
.WaitForExtensionUnloaded();
792 void UpdateProviderPolicy(const PolicyMap
& policy
) {
793 provider_
.UpdateChromePolicy(policy
);
794 DCHECK(base::MessageLoop::current());
799 // Sends a mouse click at the given coordinates to the current renderer.
800 void PerformClick(int x
, int y
) {
801 content::WebContents
* contents
=
802 browser()->tab_strip_model()->GetActiveWebContents();
803 blink::WebMouseEvent click_event
;
804 click_event
.type
= blink::WebInputEvent::MouseDown
;
805 click_event
.button
= blink::WebMouseEvent::ButtonLeft
;
806 click_event
.clickCount
= 1;
809 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
810 click_event
.type
= blink::WebInputEvent::MouseUp
;
811 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
814 void SetPolicy(PolicyMap
* policies
, const char* key
, base::Value
* value
) {
817 POLICY_LEVEL_MANDATORY
,
822 policies
->Erase(key
);
826 void ApplySafeSearchPolicy(base::FundamentalValue
* legacy_safe_search
,
827 base::FundamentalValue
* google_safe_search
,
828 base::FundamentalValue
* youtube_safety_mode
) {
830 SetPolicy(&policies
, key::kForceSafeSearch
, legacy_safe_search
);
831 SetPolicy(&policies
, key::kForceGoogleSafeSearch
, google_safe_search
);
832 SetPolicy(&policies
, key::kForceYouTubeSafetyMode
, youtube_safety_mode
);
833 UpdateProviderPolicy(policies
);
836 void CheckSafeSearch(bool expect_safe_search
) {
837 content::WebContents
* web_contents
=
838 browser()->tab_strip_model()->GetActiveWebContents();
839 content::TestNavigationObserver
observer(web_contents
);
840 chrome::FocusLocationBar(browser());
841 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
842 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
843 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
845 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
847 std::string
expected_url("http://google.com/");
848 if (expect_safe_search
) {
849 expected_url
+= "?" + std::string(chrome::kSafeSearchSafeParameter
) +
850 "&" + chrome::kSafeSearchSsuiParameter
;
852 EXPECT_EQ(GURL(expected_url
), web_contents
->GetURL());
855 MockConfigurationPolicyProvider provider_
;
856 scoped_ptr
<extensions::ExtensionCacheFake
> test_extension_cache_
;
857 #if defined(OS_CHROMEOS)
858 QuitMessageLoopAfterScreenshot observer_
;
863 // This policy only exists on Windows.
865 // Sets the locale policy before the browser is started.
866 class LocalePolicyTest
: public PolicyTest
{
868 LocalePolicyTest() {}
869 ~LocalePolicyTest() override
{}
871 void SetUpInProcessBrowserTestFixture() override
{
872 PolicyTest::SetUpInProcessBrowserTestFixture();
874 policies
.Set(key::kApplicationLocaleValue
,
875 POLICY_LEVEL_MANDATORY
,
877 new base::StringValue("fr"),
879 provider_
.UpdateChromePolicy(policies
);
880 // The "en-US" ResourceBundle is always loaded before this step for tests,
881 // but in this test we want the browser to load the bundle as it
883 ResourceBundle::CleanupSharedInstance();
887 IN_PROC_BROWSER_TEST_F(LocalePolicyTest
, ApplicationLocaleValue
) {
888 // Verifies that the default locale can be overridden with policy.
889 EXPECT_EQ("fr", g_browser_process
->GetApplicationLocale());
890 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
891 base::string16 french_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
892 base::string16 title
;
893 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title
));
894 EXPECT_EQ(french_title
, title
);
896 // Make sure this is really French and differs from the English title.
898 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
899 EXPECT_EQ("en-US", loaded
);
900 base::string16 english_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
901 EXPECT_NE(french_title
, english_title
);
905 IN_PROC_BROWSER_TEST_F(PolicyTest
, BookmarkBarEnabled
) {
906 #if defined(OS_WIN) && defined(USE_ASH)
907 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
908 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
909 switches::kAshBrowserTests
))
913 // Verifies that the bookmarks bar can be forced to always or never show up.
915 // Test starts in about:blank.
916 PrefService
* prefs
= browser()->profile()->GetPrefs();
917 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
918 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
919 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
922 policies
.Set(key::kBookmarkBarEnabled
,
923 POLICY_LEVEL_MANDATORY
,
925 new base::FundamentalValue(true),
927 UpdateProviderPolicy(policies
);
928 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
929 EXPECT_TRUE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
930 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
932 // The NTP has special handling of the bookmark bar.
933 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
934 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
936 policies
.Set(key::kBookmarkBarEnabled
,
937 POLICY_LEVEL_MANDATORY
,
939 new base::FundamentalValue(false),
941 UpdateProviderPolicy(policies
);
942 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
943 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
944 // The bookmark bar is hidden in the NTP when disabled by policy.
945 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
948 UpdateProviderPolicy(policies
);
949 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
950 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
951 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
952 EXPECT_EQ(BookmarkBar::DETACHED
, browser()->bookmark_bar_state());
955 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_PRE_DefaultCookiesSetting
) {
956 // Verifies that cookies are deleted on shutdown. This test is split in 3
957 // parts because it spans 2 browser restarts.
959 Profile
* profile
= browser()->profile();
961 // No cookies at startup.
962 EXPECT_TRUE(content::GetCookies(profile
, url
).empty());
964 std::string value
= std::string(kCookieValue
) + std::string(kCookieOptions
);
965 EXPECT_TRUE(content::SetCookie(profile
, url
, value
));
966 // Verify it was set.
967 EXPECT_EQ(kCookieValue
, GetCookies(profile
, url
));
970 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_DefaultCookiesSetting
) {
971 // Verify that the cookie persists across restarts.
972 EXPECT_EQ(kCookieValue
, GetCookies(browser()->profile(), GURL(kURL
)));
973 // Now set the policy and the cookie should be gone after another restart.
975 policies
.Set(key::kDefaultCookiesSetting
,
976 POLICY_LEVEL_MANDATORY
,
978 new base::FundamentalValue(4),
980 UpdateProviderPolicy(policies
);
983 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultCookiesSetting
) {
984 // Verify that the cookie is gone.
985 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL
)).empty());
988 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultSearchProvider
) {
989 MakeRequestFail
make_request_fail("search.example");
991 // Verifies that a default search is made using the provider configured via
992 // policy. Also checks that default search can be completely disabled.
993 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
994 const std::string
kSearchURL("http://search.example/search?q={searchTerms}");
995 const std::string
kAlternateURL0(
996 "http://search.example/search#q={searchTerms}");
997 const std::string
kAlternateURL1("http://search.example/#q={searchTerms}");
998 const std::string
kSearchTermsReplacementKey("zekey");
999 const std::string
kImageURL("http://test.com/searchbyimage/upload");
1000 const std::string
kImageURLPostParams(
1001 "image_content=content,image_url=http://test.com/test.png");
1002 const std::string
kNewTabURL("http://search.example/newtab");
1004 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1005 browser()->profile());
1006 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1007 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1008 ASSERT_TRUE(default_search
);
1009 EXPECT_NE(kKeyword
, default_search
->keyword());
1010 EXPECT_NE(kSearchURL
, default_search
->url());
1012 default_search
->alternate_urls().size() == 2 &&
1013 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1014 default_search
->alternate_urls()[1] == kAlternateURL1
&&
1015 default_search
->search_terms_replacement_key() ==
1016 kSearchTermsReplacementKey
&&
1017 default_search
->image_url() == kImageURL
&&
1018 default_search
->image_url_post_params() == kImageURLPostParams
&&
1019 default_search
->new_tab_url() == kNewTabURL
);
1021 // Override the default search provider using policies.
1023 policies
.Set(key::kDefaultSearchProviderEnabled
,
1024 POLICY_LEVEL_MANDATORY
,
1026 new base::FundamentalValue(true),
1028 policies
.Set(key::kDefaultSearchProviderKeyword
,
1029 POLICY_LEVEL_MANDATORY
,
1031 new base::StringValue(kKeyword
),
1033 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1034 POLICY_LEVEL_MANDATORY
,
1036 new base::StringValue(kSearchURL
),
1038 base::ListValue
* alternate_urls
= new base::ListValue();
1039 alternate_urls
->AppendString(kAlternateURL0
);
1040 alternate_urls
->AppendString(kAlternateURL1
);
1041 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1042 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1043 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1044 POLICY_LEVEL_MANDATORY
,
1046 new base::StringValue(kSearchTermsReplacementKey
),
1048 policies
.Set(key::kDefaultSearchProviderImageURL
,
1049 POLICY_LEVEL_MANDATORY
,
1051 new base::StringValue(kImageURL
),
1053 policies
.Set(key::kDefaultSearchProviderImageURLPostParams
,
1054 POLICY_LEVEL_MANDATORY
,
1056 new base::StringValue(kImageURLPostParams
),
1058 policies
.Set(key::kDefaultSearchProviderNewTabURL
,
1059 POLICY_LEVEL_MANDATORY
,
1061 new base::StringValue(kNewTabURL
),
1063 UpdateProviderPolicy(policies
);
1064 default_search
= service
->GetDefaultSearchProvider();
1065 ASSERT_TRUE(default_search
);
1066 EXPECT_EQ(kKeyword
, default_search
->keyword());
1067 EXPECT_EQ(kSearchURL
, default_search
->url());
1068 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1069 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1070 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1071 EXPECT_EQ(kSearchTermsReplacementKey
,
1072 default_search
->search_terms_replacement_key());
1073 EXPECT_EQ(kImageURL
, default_search
->image_url());
1074 EXPECT_EQ(kImageURLPostParams
, default_search
->image_url_post_params());
1075 EXPECT_EQ(kNewTabURL
, default_search
->new_tab_url());
1077 // Verify that searching from the omnibox uses kSearchURL.
1078 chrome::FocusLocationBar(browser());
1079 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1080 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "stuff to search for");
1081 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1082 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1083 content::WebContents
* web_contents
=
1084 browser()->tab_strip_model()->GetActiveWebContents();
1085 GURL
expected("http://search.example/search?q=stuff+to+search+for");
1086 EXPECT_EQ(expected
, web_contents
->GetURL());
1088 // Verify that searching from the omnibox can be disabled.
1089 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1090 policies
.Set(key::kDefaultSearchProviderEnabled
,
1091 POLICY_LEVEL_MANDATORY
,
1093 new base::FundamentalValue(false),
1095 EXPECT_TRUE(service
->GetDefaultSearchProvider());
1096 UpdateProviderPolicy(policies
);
1097 EXPECT_FALSE(service
->GetDefaultSearchProvider());
1098 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "should not work");
1099 // This means that submitting won't trigger any action.
1100 EXPECT_FALSE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1101 EXPECT_EQ(GURL(url::kAboutBlankURL
), web_contents
->GetURL());
1104 IN_PROC_BROWSER_TEST_F(PolicyTest
, PolicyPreprocessing
) {
1105 // Add an individual proxy policy value.
1107 policies
.Set(key::kProxyServerMode
,
1108 POLICY_LEVEL_MANDATORY
,
1110 new base::FundamentalValue(3),
1112 UpdateProviderPolicy(policies
);
1114 // It should be removed and replaced with a dictionary.
1116 scoped_ptr
<base::DictionaryValue
> expected_value(new base::DictionaryValue
);
1117 expected_value
->SetInteger(key::kProxyServerMode
, 3);
1118 expected
.Set(key::kProxySettings
,
1119 POLICY_LEVEL_MANDATORY
,
1121 expected_value
.release(),
1124 // Check both the browser and the profile.
1125 const PolicyMap
& actual_from_browser
=
1126 g_browser_process
->browser_policy_connector()
1127 ->GetPolicyService()
1128 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1129 EXPECT_TRUE(expected
.Equals(actual_from_browser
));
1130 const PolicyMap
& actual_from_profile
=
1131 ProfilePolicyConnectorFactory::GetForBrowserContext(browser()->profile())
1133 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1134 EXPECT_TRUE(expected
.Equals(actual_from_profile
));
1137 IN_PROC_BROWSER_TEST_F(PolicyTest
, ForceSafeSearch
) {
1138 // Makes the requests fail since all we want to check is that the redirection
1139 // is done properly.
1140 MakeRequestFail
make_request_fail("google.com");
1142 // Verifies that requests to Google Search engine with the SafeSearch
1143 // enabled set the safe=active&ssui=on parameters at the end of the query.
1144 // First check that nothing happens.
1145 CheckSafeSearch(false);
1147 // Go over all combinations of (undefined,true,false) for the three policies.
1148 for (int i
= 0; i
< 3 * 3 * 3; i
++) {
1150 int google
= (i
/ 3) % 3;
1151 int youtube
= i
/ (3 * 3);
1153 // Override the default SafeSearch setting using policies.
1154 ApplySafeSearchPolicy(
1155 legacy
== 0 ? nullptr : new base::FundamentalValue(legacy
== 1),
1156 google
== 0 ? nullptr : new base::FundamentalValue(google
== 1),
1157 youtube
== 0 ? nullptr : new base::FundamentalValue(youtube
== 1));
1159 // The legacy policy should only have an effect if both google and youtube
1161 bool legacy_in_effect
= (google
== 0 && youtube
== 0 && legacy
!= 0);
1162 bool legacy_enabled
= legacy_in_effect
&& legacy
== 1;
1164 PrefService
* prefs
= browser()->profile()->GetPrefs();
1165 EXPECT_EQ(google
!= 0 || legacy_in_effect
,
1166 prefs
->IsManagedPreference(prefs::kForceGoogleSafeSearch
));
1167 EXPECT_EQ(google
== 1 || legacy_enabled
,
1168 prefs
->GetBoolean(prefs::kForceGoogleSafeSearch
));
1170 EXPECT_EQ(youtube
!= 0 || legacy_in_effect
,
1171 prefs
->IsManagedPreference(prefs::kForceYouTubeSafetyMode
));
1172 EXPECT_EQ(youtube
== 1 || legacy_enabled
,
1173 prefs
->GetBoolean(prefs::kForceYouTubeSafetyMode
));
1175 CheckSafeSearch(google
== 1 || legacy_enabled
);
1179 IN_PROC_BROWSER_TEST_F(PolicyTest
, ReplaceSearchTerms
) {
1180 MakeRequestFail
make_request_fail("search.example");
1182 chrome::EnableQueryExtractionForTesting();
1184 // Verifies that a default search is made using the provider configured via
1185 // policy. Also checks that default search can be completely disabled.
1186 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1187 const std::string
kSearchURL("https://www.google.com/search?q={searchTerms}");
1188 const std::string
kInstantURL("http://does/not/exist");
1189 const std::string
kAlternateURL0(
1190 "https://www.google.com/search#q={searchTerms}");
1191 const std::string
kAlternateURL1("https://www.google.com/#q={searchTerms}");
1192 const std::string
kSearchTermsReplacementKey(
1193 "{google:instantExtendedEnabledKey}");
1195 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1196 browser()->profile());
1197 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1198 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1199 ASSERT_TRUE(default_search
);
1200 EXPECT_NE(kKeyword
, default_search
->keyword());
1201 EXPECT_NE(kSearchURL
, default_search
->url());
1202 EXPECT_NE(kInstantURL
, default_search
->instant_url());
1204 default_search
->alternate_urls().size() == 2 &&
1205 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1206 default_search
->alternate_urls()[1] == kAlternateURL1
);
1208 // Override the default search provider using policies.
1210 policies
.Set(key::kDefaultSearchProviderEnabled
,
1211 POLICY_LEVEL_MANDATORY
,
1213 new base::FundamentalValue(true),
1215 policies
.Set(key::kDefaultSearchProviderKeyword
,
1216 POLICY_LEVEL_MANDATORY
,
1218 new base::StringValue(kKeyword
),
1220 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1221 POLICY_LEVEL_MANDATORY
,
1223 new base::StringValue(kSearchURL
),
1225 policies
.Set(key::kDefaultSearchProviderInstantURL
,
1226 POLICY_LEVEL_MANDATORY
,
1228 new base::StringValue(kInstantURL
),
1230 base::ListValue
* alternate_urls
= new base::ListValue();
1231 alternate_urls
->AppendString(kAlternateURL0
);
1232 alternate_urls
->AppendString(kAlternateURL1
);
1233 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1234 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1235 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1236 POLICY_LEVEL_MANDATORY
,
1238 new base::StringValue(kSearchTermsReplacementKey
),
1240 UpdateProviderPolicy(policies
);
1241 default_search
= service
->GetDefaultSearchProvider();
1242 ASSERT_TRUE(default_search
);
1243 EXPECT_EQ(kKeyword
, default_search
->keyword());
1244 EXPECT_EQ(kSearchURL
, default_search
->url());
1245 EXPECT_EQ(kInstantURL
, default_search
->instant_url());
1246 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1247 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1248 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1250 // Query terms replacement requires that the renderer process be a recognized
1251 // Instant renderer. Fake it.
1252 InstantService
* instant_service
=
1253 InstantServiceFactory::GetForProfile(browser()->profile());
1254 instant_service
->AddInstantProcess(browser()->tab_strip_model()->
1255 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1257 // Verify that searching from the omnibox does search term replacement with
1258 // first URL pattern.
1259 chrome::FocusLocationBar(browser());
1260 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1261 OmniboxView
* omnibox_view
= location_bar
->GetOmniboxView();
1262 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1263 "https://www.google.com/?espv=1#q=foobar");
1265 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1266 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1268 // Verify that not using espv=1 does not do search term replacement.
1269 chrome::FocusLocationBar(browser());
1270 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1271 "https://www.google.com/?q=foobar");
1273 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1274 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1275 omnibox_view
->GetText());
1277 // Verify that searching from the omnibox does search term replacement with
1278 // second URL pattern.
1279 chrome::FocusLocationBar(browser());
1280 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1281 "https://www.google.com/search?espv=1#q=banana");
1283 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1284 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view
->GetText());
1286 // Verify that searching from the omnibox does search term replacement with
1287 // standard search URL pattern.
1288 chrome::FocusLocationBar(browser());
1289 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1290 "https://www.google.com/search?q=tractor+parts&espv=1");
1292 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1293 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view
->GetText());
1295 // Verify that searching from the omnibox prioritizes hash over query.
1296 chrome::FocusLocationBar(browser());
1297 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1298 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1300 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1301 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1304 IN_PROC_BROWSER_TEST_F(PolicyTest
, Disable3DAPIs
) {
1305 // This test assumes Gpu access.
1306 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
))
1309 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1310 // WebGL is enabled by default.
1311 content::WebContents
* contents
=
1312 browser()->tab_strip_model()->GetActiveWebContents();
1313 EXPECT_TRUE(IsWebGLEnabled(contents
));
1314 // Disable with a policy.
1316 policies
.Set(key::kDisable3DAPIs
,
1317 POLICY_LEVEL_MANDATORY
,
1319 new base::FundamentalValue(true),
1321 UpdateProviderPolicy(policies
);
1322 // Crash and reload the tab to get a new renderer.
1323 content::CrashTab(contents
);
1324 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1325 EXPECT_FALSE(IsWebGLEnabled(contents
));
1326 // Enable with a policy.
1327 policies
.Set(key::kDisable3DAPIs
,
1328 POLICY_LEVEL_MANDATORY
,
1330 new base::FundamentalValue(false),
1332 UpdateProviderPolicy(policies
);
1333 content::CrashTab(contents
);
1334 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1335 EXPECT_TRUE(IsWebGLEnabled(contents
));
1338 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableSpdy
) {
1339 // Verifies that SPDY can be disable by policy.
1340 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1342 policies
.Set(key::kDisableSpdy
,
1343 POLICY_LEVEL_MANDATORY
,
1345 new base::FundamentalValue(true),
1347 UpdateProviderPolicy(policies
);
1348 content::RunAllPendingInMessageLoop();
1349 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1350 // Verify that it can be force-enabled too.
1351 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy
, true);
1352 policies
.Set(key::kDisableSpdy
,
1353 POLICY_LEVEL_MANDATORY
,
1355 new base::FundamentalValue(false),
1357 UpdateProviderPolicy(policies
);
1358 content::RunAllPendingInMessageLoop();
1359 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1362 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPlugins
) {
1363 // Verifies that plugins can be forced to be disabled by policy.
1365 // Verify that the Flash plugin exists and that it can be enabled and disabled
1367 std::vector
<content::WebPluginInfo
> plugins
;
1368 GetPluginList(&plugins
);
1369 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1372 PluginPrefs
* plugin_prefs
=
1373 PluginPrefs::GetForProfile(browser()->profile()).get();
1374 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1375 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1376 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1377 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1378 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1380 // Now disable it with a policy.
1381 base::ListValue disabled_plugins
;
1382 disabled_plugins
.Append(new base::StringValue("*Flash*"));
1384 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1385 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1386 UpdateProviderPolicy(policies
);
1387 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1388 // The user shouldn't be able to enable it.
1389 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1390 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1393 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPluginsExceptions
) {
1394 // Verifies that plugins with an exception in the blacklist can be enabled.
1396 // Verify that the Flash plugin exists and that it can be enabled and disabled
1398 std::vector
<content::WebPluginInfo
> plugins
;
1399 GetPluginList(&plugins
);
1400 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1403 PluginPrefs
* plugin_prefs
=
1404 PluginPrefs::GetForProfile(browser()->profile()).get();
1405 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1407 // Disable all plugins.
1408 base::ListValue disabled_plugins
;
1409 disabled_plugins
.Append(new base::StringValue("*"));
1411 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1412 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1413 UpdateProviderPolicy(policies
);
1414 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1415 // The user shouldn't be able to enable it.
1416 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1417 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1419 // Now open an exception for flash.
1420 base::ListValue disabled_plugins_exceptions
;
1421 disabled_plugins_exceptions
.Append(new base::StringValue("*Flash*"));
1422 policies
.Set(key::kDisabledPluginsExceptions
, POLICY_LEVEL_MANDATORY
,
1423 POLICY_SCOPE_USER
, disabled_plugins_exceptions
.DeepCopy(), NULL
);
1424 UpdateProviderPolicy(policies
);
1425 // It should revert to the user's preference automatically.
1426 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1427 // And the user should be able to disable and enable again.
1428 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1429 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1430 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1431 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1434 IN_PROC_BROWSER_TEST_F(PolicyTest
, EnabledPlugins
) {
1435 // Verifies that a plugin can be force-installed with a policy.
1436 std::vector
<content::WebPluginInfo
> plugins
;
1437 GetPluginList(&plugins
);
1438 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1441 PluginPrefs
* plugin_prefs
=
1442 PluginPrefs::GetForProfile(browser()->profile()).get();
1443 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1445 // The user disables it and then a policy forces it to be enabled.
1446 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1447 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1448 base::ListValue plugin_list
;
1449 plugin_list
.Append(new base::StringValue(content::kFlashPluginName
));
1451 policies
.Set(key::kEnabledPlugins
, POLICY_LEVEL_MANDATORY
,
1452 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1453 UpdateProviderPolicy(policies
);
1454 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1455 // The user can't disable it anymore.
1456 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, false));
1457 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1459 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1460 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1461 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1462 UpdateProviderPolicy(policies
);
1463 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1466 IN_PROC_BROWSER_TEST_F(PolicyTest
, AlwaysAuthorizePlugins
) {
1467 // Verifies that dangerous plugins can be always authorized to run with
1470 // Verify that the test page exists. It is only present in checkouts with
1472 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1473 base::FilePath(FILE_PATH_LITERAL("plugin")),
1474 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1476 "Test skipped because plugin/quicktime.html test file wasn't found.";
1480 ServeContentTestData();
1481 // No plugins at startup.
1482 EXPECT_EQ(0, CountPlugins());
1484 content::WebContents
* contents
=
1485 browser()->tab_strip_model()->GetActiveWebContents();
1486 ASSERT_TRUE(contents
);
1487 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
1488 ASSERT_TRUE(infobar_service
);
1489 EXPECT_EQ(0u, infobar_service
->infobar_count());
1491 base::FilePath
path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1492 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1493 ui_test_utils::NavigateToURL(browser(), url
);
1494 // This should have triggered the dangerous plugin infobar.
1495 ASSERT_EQ(1u, infobar_service
->infobar_count());
1497 infobar_service
->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1498 // And the plugin isn't running.
1499 EXPECT_EQ(0, CountPlugins());
1501 // Now set a policy to always authorize this.
1503 policies
.Set(key::kAlwaysAuthorizePlugins
,
1504 POLICY_LEVEL_MANDATORY
,
1506 new base::FundamentalValue(true),
1508 UpdateProviderPolicy(policies
);
1509 // Reloading the page shouldn't trigger the infobar this time.
1510 ui_test_utils::NavigateToURL(browser(), url
);
1511 EXPECT_EQ(0u, infobar_service
->infobar_count());
1512 // And the plugin started automatically.
1513 EXPECT_EQ(1, CountPlugins());
1516 IN_PROC_BROWSER_TEST_F(PolicyTest
, DeveloperToolsDisabled
) {
1517 // Verifies that access to the developer tools can be disabled.
1520 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1521 content::WebContents
* contents
=
1522 browser()->tab_strip_model()->GetActiveWebContents();
1523 DevToolsWindow
* devtools_window
=
1524 DevToolsWindow::GetInstanceForInspectedWebContents(contents
);
1525 EXPECT_TRUE(devtools_window
);
1527 // Disable devtools via policy.
1529 policies
.Set(key::kDeveloperToolsDisabled
,
1530 POLICY_LEVEL_MANDATORY
,
1532 new base::FundamentalValue(true),
1534 content::WindowedNotificationObserver
close_observer(
1535 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
1536 content::Source
<content::WebContents
>(
1537 DevToolsWindowTesting::Get(devtools_window
)->main_web_contents()));
1538 UpdateProviderPolicy(policies
);
1539 // wait for devtools close
1540 close_observer
.Wait();
1541 // The existing devtools window should have closed.
1542 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1543 // And it's not possible to open it again.
1544 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1545 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1548 // TODO(samarth): remove along with rest of NTP4 code.
1549 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_WebStoreIconHidden
) {
1550 #if defined(OS_WIN) && defined(USE_ASH)
1551 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1552 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1553 switches::kAshBrowserTests
))
1557 // Verifies that the web store icons can be hidden from the new tab page.
1559 // Open new tab page and look for the web store icons.
1560 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1561 content::WebContents
* contents
=
1562 browser()->tab_strip_model()->GetActiveWebContents();
1564 #if !defined(OS_CHROMEOS)
1565 // Look for web store's app ID in the apps page.
1566 EXPECT_TRUE(ContainsVisibleElement(contents
,
1567 "ahfgeienlihckogmohjhadlkjgocpleb"));
1570 // The next NTP has no footer.
1571 if (ContainsVisibleElement(contents
, "footer"))
1572 EXPECT_TRUE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1574 // Turn off the web store icons.
1576 policies
.Set(key::kHideWebStoreIcon
,
1577 POLICY_LEVEL_MANDATORY
,
1579 new base::FundamentalValue(true),
1581 UpdateProviderPolicy(policies
);
1583 // The web store icons should now be hidden.
1584 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1585 EXPECT_FALSE(ContainsVisibleElement(contents
,
1586 "ahfgeienlihckogmohjhadlkjgocpleb"));
1587 EXPECT_FALSE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1590 IN_PROC_BROWSER_TEST_F(PolicyTest
, DownloadDirectory
) {
1591 // Verifies that the download directory can be forced by policy.
1593 // Set the initial download directory.
1594 base::ScopedTempDir initial_dir
;
1595 ASSERT_TRUE(initial_dir
.CreateUniqueTempDir());
1596 browser()->profile()->GetPrefs()->SetFilePath(
1597 prefs::kDownloadDefaultDirectory
, initial_dir
.path());
1598 // Don't prompt for the download location during this test.
1599 browser()->profile()->GetPrefs()->SetBoolean(
1600 prefs::kPromptForDownload
, false);
1602 // Verify that downloads end up on the default directory.
1603 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1604 DownloadAndVerifyFile(browser(), initial_dir
.path(), file
);
1605 base::DieFileDie(initial_dir
.path().Append(file
), false);
1607 // Override the download directory with the policy and verify a download.
1608 base::ScopedTempDir forced_dir
;
1609 ASSERT_TRUE(forced_dir
.CreateUniqueTempDir());
1611 policies
.Set(key::kDownloadDirectory
,
1612 POLICY_LEVEL_MANDATORY
,
1614 new base::StringValue(forced_dir
.path().value()),
1616 UpdateProviderPolicy(policies
);
1617 DownloadAndVerifyFile(browser(), forced_dir
.path(), file
);
1618 // Verify that the first download location wasn't affected.
1619 EXPECT_FALSE(base::PathExists(initial_dir
.path().Append(file
)));
1622 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSelective
) {
1623 // Verifies that blacklisted extensions can't be installed.
1624 ExtensionService
* service
= extension_service();
1625 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1626 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1627 base::ListValue blacklist
;
1628 blacklist
.Append(new base::StringValue(kGoodCrxId
));
1630 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1631 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1632 UpdateProviderPolicy(policies
);
1634 // "good.crx" is blacklisted.
1635 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1636 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1638 // "adblock.crx" is not.
1639 const extensions::Extension
* adblock
= InstallExtension(kAdBlockCrxName
);
1640 ASSERT_TRUE(adblock
);
1641 EXPECT_EQ(kAdBlockCrxId
, adblock
->id());
1643 service
->GetExtensionById(kAdBlockCrxId
, true));
1646 // Flaky on windows; http://crbug.com/307994.
1648 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1650 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1652 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallBlacklistWildcard
) {
1653 // Verify that a wildcard blacklist takes effect.
1654 EXPECT_TRUE(InstallExtension(kAdBlockCrxName
));
1655 ExtensionService
* service
= extension_service();
1656 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1657 ASSERT_TRUE(service
->GetExtensionById(kAdBlockCrxId
, true));
1658 base::ListValue blacklist
;
1659 blacklist
.Append(new base::StringValue("*"));
1661 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1662 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1663 UpdateProviderPolicy(policies
);
1665 // AdBlock was automatically removed.
1666 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1668 // And can't be installed again, nor can good.crx.
1669 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1670 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1671 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1672 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1675 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSharedModules
) {
1676 // Verifies that shared_modules are not affected by the blacklist.
1678 const char kImporterId
[] = "pchakhniekfaeoddkifplhnfbffomabh";
1679 const char kSharedModuleId
[] = "nfgclafboonjbiafbllihiailjlhelpm";
1681 // Make sure that "import" and "export" are available to these extension IDs
1682 // by mocking the release channel.
1683 extensions::ScopedCurrentChannel
channel(chrome::VersionInfo::CHANNEL_DEV
);
1685 // Verify that the extensions are not installed initially.
1686 ExtensionService
* service
= extension_service();
1687 ASSERT_FALSE(service
->GetExtensionById(kImporterId
, true));
1688 ASSERT_FALSE(service
->GetExtensionById(kSharedModuleId
, true));
1690 // Mock the webstore update URL. This is where the shared module extension
1691 // will be installed from.
1692 base::FilePath update_xml_path
= base::FilePath(kTestExtensionsDir
)
1693 .AppendASCII("policy_shared_module")
1694 .AppendASCII("update.xml");
1695 GURL
update_xml_url(URLRequestMockHTTPJob::GetMockUrl(update_xml_path
));
1696 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1697 switches::kAppsGalleryUpdateURL
, update_xml_url
.spec());
1698 ui_test_utils::NavigateToURL(browser(), update_xml_url
);
1700 // Blacklist "*" but force-install the importer extension. The shared module
1701 // should be automatically installed too.
1702 base::ListValue blacklist
;
1703 blacklist
.AppendString("*");
1704 base::ListValue forcelist
;
1705 forcelist
.AppendString(
1706 base::StringPrintf("%s;%s", kImporterId
, update_xml_url
.spec().c_str()));
1708 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1709 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1710 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1711 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1713 extensions::ExtensionRegistry
* registry
=
1714 extensions::ExtensionRegistry::Get(browser()->profile());
1715 extensions::TestExtensionRegistryObserver
observe_importer(
1716 registry
, kImporterId
);
1717 extensions::TestExtensionRegistryObserver
observe_shared_module(
1718 registry
, kSharedModuleId
);
1719 UpdateProviderPolicy(policies
);
1720 observe_importer
.WaitForExtensionLoaded();
1721 observe_shared_module
.WaitForExtensionLoaded();
1723 // Verify that both extensions got installed.
1724 const extensions::Extension
* importer
=
1725 service
->GetExtensionById(kImporterId
, true);
1726 ASSERT_TRUE(importer
);
1727 EXPECT_EQ(kImporterId
, importer
->id());
1728 const extensions::Extension
* shared_module
=
1729 service
->GetExtensionById(kSharedModuleId
, true);
1730 ASSERT_TRUE(shared_module
);
1731 EXPECT_EQ(kSharedModuleId
, shared_module
->id());
1732 EXPECT_TRUE(shared_module
->is_shared_module());
1734 // Verify the dependency.
1735 scoped_ptr
<extensions::ExtensionSet
> set
=
1736 service
->shared_module_service()->GetDependentExtensions(shared_module
);
1738 EXPECT_EQ(1u, set
->size());
1739 EXPECT_TRUE(set
->Contains(importer
->id()));
1741 std::vector
<extensions::SharedModuleInfo::ImportInfo
> imports
=
1742 extensions::SharedModuleInfo::GetImports(importer
);
1743 ASSERT_EQ(1u, imports
.size());
1744 EXPECT_EQ(kSharedModuleId
, imports
[0].extension_id
);
1747 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallWhitelist
) {
1748 // Verifies that the whitelist can open exceptions to the blacklist.
1749 ExtensionService
* service
= extension_service();
1750 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1751 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1752 base::ListValue blacklist
;
1753 blacklist
.Append(new base::StringValue("*"));
1754 base::ListValue whitelist
;
1755 whitelist
.Append(new base::StringValue(kGoodCrxId
));
1757 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1758 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1759 policies
.Set(key::kExtensionInstallWhitelist
, POLICY_LEVEL_MANDATORY
,
1760 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
1761 UpdateProviderPolicy(policies
);
1762 // "adblock.crx" is blacklisted.
1763 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1764 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1765 // "good.crx" has a whitelist exception.
1766 const extensions::Extension
* good
= InstallExtension(kGoodCrxName
);
1768 EXPECT_EQ(kGoodCrxId
, good
->id());
1769 EXPECT_EQ(good
, service
->GetExtensionById(kGoodCrxId
, true));
1770 // The user can also remove this extension.
1771 UninstallExtension(kGoodCrxId
, true);
1774 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallForcelist
) {
1775 // Verifies that extensions that are force-installed by policies are
1776 // installed and can't be uninstalled.
1777 ExtensionService
* service
= extension_service();
1778 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1780 // Extensions that are force-installed come from an update URL, which defaults
1781 // to the webstore. Use a mock URL for this test with an update manifest
1782 // that includes "good_v1.crx".
1783 base::FilePath path
=
1784 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1785 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1787 // Setting the forcelist extension should install "good_v1.crx".
1788 base::ListValue forcelist
;
1789 forcelist
.Append(new base::StringValue(
1790 base::StringPrintf("%s;%s", kGoodCrxId
, url
.spec().c_str())));
1792 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1793 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1794 content::WindowedNotificationObserver
observer(
1795 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1796 content::NotificationService::AllSources());
1797 UpdateProviderPolicy(policies
);
1799 // Note: Cannot check that the notification details match the expected
1800 // exception, since the details object has already been freed prior to
1801 // the completion of observer.Wait().
1803 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1805 // The user is not allowed to uninstall force-installed extensions.
1806 UninstallExtension(kGoodCrxId
, false);
1808 // The user is not allowed to load an unpacked extension with the
1809 // same ID as a force-installed extension.
1810 LoadUnpackedExtension(kGoodUnpackedExt
, false);
1812 // Loading other unpacked extensions are not blocked.
1813 LoadUnpackedExtension(kAppUnpackedExt
, true);
1815 const std::string old_version_number
=
1816 service
->GetExtensionById(kGoodCrxId
, true)->version()->GetString();
1818 base::FilePath test_path
;
1819 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1821 TestRequestInterceptor
interceptor(
1823 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1824 interceptor
.PushJobCallback(
1825 TestRequestInterceptor::FileJob(
1826 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1828 // Updating the force-installed extension.
1829 extensions::ExtensionUpdater
* updater
= service
->updater();
1830 extensions::ExtensionUpdater::CheckParams params
;
1831 params
.install_immediately
= true;
1832 content::WindowedNotificationObserver
update_observer(
1833 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1834 content::NotificationService::AllSources());
1835 updater
->CheckNow(params
);
1836 update_observer
.Wait();
1838 const base::Version
* new_version
=
1839 service
->GetExtensionById(kGoodCrxId
, true)->version();
1840 ASSERT_TRUE(new_version
->IsValid());
1841 base::Version
old_version(old_version_number
);
1842 ASSERT_TRUE(old_version
.IsValid());
1844 EXPECT_EQ(1, new_version
->CompareTo(old_version
));
1846 EXPECT_EQ(0u, interceptor
.GetPendingSize());
1848 // Wait until any background pages belonging to force-installed extensions
1849 // have been loaded.
1850 extensions::ProcessManager
* manager
=
1851 extensions::ProcessManager::Get(browser()->profile());
1852 extensions::ProcessManager::FrameSet all_frames
= manager
->GetAllFrames();
1853 for (extensions::ProcessManager::FrameSet::const_iterator iter
=
1855 iter
!= all_frames
.end();) {
1856 content::WebContents
* web_contents
=
1857 content::WebContents::FromRenderFrameHost(*iter
);
1858 ASSERT_TRUE(web_contents
);
1859 if (!web_contents
->IsLoading()) {
1862 WebContentsLoadedOrDestroyedWatcher(web_contents
).Wait();
1864 // Test activity may have modified the set of extension processes during
1865 // message processing, so re-start the iteration to catch added/removed
1867 all_frames
= manager
->GetAllFrames();
1868 iter
= all_frames
.begin();
1872 // Test policy-installed extensions are reloaded when killed.
1873 BackgroundContentsService::
1874 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1875 content::WindowedNotificationObserver
extension_crashed_observer(
1876 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
1877 content::NotificationService::AllSources());
1878 content::WindowedNotificationObserver
extension_loaded_observer(
1879 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1880 content::NotificationService::AllSources());
1881 extensions::ExtensionHost
* extension_host
=
1882 extensions::ProcessManager::Get(browser()->profile())
1883 ->GetBackgroundHostForExtension(kGoodCrxId
);
1884 extension_host
->render_process_host()->Shutdown(content::RESULT_CODE_KILLED
,
1886 extension_crashed_observer
.Wait();
1887 extension_loaded_observer
.Wait();
1890 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionRecommendedInstallationMode
) {
1891 // Verifies that extensions that are recommended-installed by policies are
1892 // installed, can be disabled but not uninstalled.
1893 ExtensionService
* service
= extension_service();
1894 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1896 base::FilePath path
=
1897 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1898 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1900 // Setting the forcelist extension should install "good_v1.crx".
1901 base::DictionaryValue dict_value
;
1902 dict_value
.SetString(std::string(kGoodCrxId
) + "." +
1903 extensions::schema_constants::kInstallationMode
,
1904 extensions::schema_constants::kNormalInstalled
);
1905 dict_value
.SetString(
1906 std::string(kGoodCrxId
) + "." + extensions::schema_constants::kUpdateUrl
,
1909 policies
.Set(key::kExtensionSettings
,
1910 POLICY_LEVEL_MANDATORY
,
1912 dict_value
.DeepCopy(),
1914 content::WindowedNotificationObserver
observer(
1915 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1916 content::NotificationService::AllSources());
1917 UpdateProviderPolicy(policies
);
1920 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1922 // The user is not allowed to uninstall recommended-installed extensions.
1923 UninstallExtension(kGoodCrxId
, false);
1925 // Explictly re-enables the extension.
1926 service
->EnableExtension(kGoodCrxId
);
1928 // But the user is allowed to disable them.
1929 EXPECT_TRUE(service
->IsExtensionEnabled(kGoodCrxId
));
1930 DisableExtension(kGoodCrxId
);
1931 EXPECT_FALSE(service
->IsExtensionEnabled(kGoodCrxId
));
1934 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionAllowedTypes
) {
1935 // Verifies that extensions are blocked if policy specifies an allowed types
1936 // list and the extension's type is not on that list.
1937 ExtensionService
* service
= extension_service();
1938 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1939 ASSERT_FALSE(service
->GetExtensionById(kHostedAppCrxId
, true));
1941 base::ListValue allowed_types
;
1942 allowed_types
.AppendString("hosted_app");
1944 policies
.Set(key::kExtensionAllowedTypes
, POLICY_LEVEL_MANDATORY
,
1945 POLICY_SCOPE_USER
, allowed_types
.DeepCopy(), NULL
);
1946 UpdateProviderPolicy(policies
);
1948 // "good.crx" is blocked.
1949 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1950 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1952 // "hosted_app.crx" is of a whitelisted type.
1953 const extensions::Extension
* hosted_app
= InstallExtension(kHostedAppCrxName
);
1954 ASSERT_TRUE(hosted_app
);
1955 EXPECT_EQ(kHostedAppCrxId
, hosted_app
->id());
1956 EXPECT_EQ(hosted_app
, service
->GetExtensionById(kHostedAppCrxId
, true));
1958 // The user can remove the extension.
1959 UninstallExtension(kHostedAppCrxId
, true);
1962 // Checks that a click on an extension CRX download triggers the extension
1963 // installation prompt without further user interaction when the source is
1964 // whitelisted by policy.
1965 // Flaky on windows; http://crbug.com/295729 .
1967 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1969 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1971 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallSources
) {
1972 extensions::ScopedTestDialogAutoConfirm
auto_confirm(
1973 extensions::ScopedTestDialogAutoConfirm::ACCEPT
);
1975 const GURL
install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1976 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1977 const GURL
referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1978 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1980 base::ScopedTempDir download_directory
;
1981 ASSERT_TRUE(download_directory
.CreateUniqueTempDir());
1982 DownloadPrefs
* download_prefs
=
1983 DownloadPrefs::FromBrowserContext(browser()->profile());
1984 download_prefs
->SetDownloadPath(download_directory
.path());
1986 const GURL
download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1987 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1988 ui_test_utils::NavigateToURL(browser(), download_page_url
);
1990 // As long as the policy is not present, extensions are considered dangerous.
1991 content::DownloadTestObserverTerminal
download_observer(
1992 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1993 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
);
1995 download_observer
.WaitForFinished();
1997 // Install the policy and trigger another download.
1998 base::ListValue install_sources
;
1999 install_sources
.AppendString(install_source_url
.spec());
2000 install_sources
.AppendString(referrer_url
.spec());
2002 policies
.Set(key::kExtensionInstallSources
, POLICY_LEVEL_MANDATORY
,
2003 POLICY_SCOPE_USER
, install_sources
.DeepCopy(), NULL
);
2004 UpdateProviderPolicy(policies
);
2006 content::WindowedNotificationObserver
observer(
2007 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2008 content::NotificationService::AllSources());
2011 // Note: Cannot check that the notification details match the expected
2012 // exception, since the details object has already been freed prior to
2013 // the completion of observer.Wait().
2015 // The first extension shouldn't be present, the second should be there.
2016 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId
, true));
2017 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId
, false));
2020 // Verifies that extensions with version older than the minimum version required
2021 // by policy will get disabled, and will be auto-updated and/or re-enabled upon
2022 // policy changes as well as regular auto-updater scheduled updates.
2023 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequired
) {
2024 ExtensionService
* service
= extension_service();
2025 extensions::ExtensionRegistry
* registry
=
2026 extensions::ExtensionRegistry::Get(browser()->profile());
2027 extensions::ExtensionPrefs
* extension_prefs
=
2028 extensions::ExtensionPrefs::Get(browser()->profile());
2030 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2031 service
->updater()->StopTimerForTesting();
2033 // Setup interceptor for extension updates.
2034 base::FilePath test_path
;
2035 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2036 TestRequestInterceptor
interceptor(
2038 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2039 interceptor
.PushJobCallback(TestRequestInterceptor::BadRequestJob());
2040 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2041 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2043 // Install the extension.
2044 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2045 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2047 // Update policy to set a minimum version of 1.0.0.0, the extension (with
2048 // version 1.0.0.0) should still be enabled.
2050 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2051 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.0");
2053 base::RunLoop().RunUntilIdle();
2055 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2057 // Update policy to set a minimum version of 1.0.0.1, the extension (with
2058 // version 1.0.0.0) should now be disabled.
2059 EXPECT_EQ(2u, interceptor
.GetPendingSize());
2060 base::RunLoop service_request_run_loop
;
2061 interceptor
.AddRequestServicedCallback(
2062 service_request_run_loop
.QuitClosure());
2064 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2065 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2067 service_request_run_loop
.Run();
2068 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2070 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2071 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2072 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2074 // Provide a new version (1.0.0.1) which is expected to be auto updated to
2075 // via the update URL in the manifest of the older version.
2076 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2078 content::WindowedNotificationObserver
update_observer(
2079 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2080 content::NotificationService::AllSources());
2081 service
->updater()->CheckSoon();
2082 update_observer
.Wait();
2084 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2086 // The extension should be auto-updated to newer version and re-enabled.
2087 EXPECT_EQ("1.0.0.1",
2088 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2089 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2092 // Similar to ExtensionMinimumVersionRequired test, but with different settings
2094 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionRequiredAlt
) {
2095 ExtensionService
* service
= extension_service();
2096 extensions::ExtensionRegistry
* registry
=
2097 extensions::ExtensionRegistry::Get(browser()->profile());
2098 extensions::ExtensionPrefs
* extension_prefs
=
2099 extensions::ExtensionPrefs::Get(browser()->profile());
2101 // Explicitly stop the timer to avoid all scheduled extension auto-updates.
2102 service
->updater()->StopTimerForTesting();
2104 // Setup interceptor for extension updates.
2105 base::FilePath test_path
;
2106 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
2107 TestRequestInterceptor
interceptor(
2109 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
2110 interceptor
.PushJobCallback(TestRequestInterceptor::FileJob(
2111 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
2113 // Set the policy to require an even higher minimum version this time.
2115 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2116 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.2");
2118 base::RunLoop().RunUntilIdle();
2120 // Install the 1.0.0.0 version, it should be installed but disabled.
2121 EXPECT_TRUE(InstallExtension(kGoodV1CrxName
));
2122 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2123 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2124 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2125 EXPECT_EQ("1.0.0.0",
2126 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2128 // An extension management policy update should trigger an update as well.
2129 EXPECT_EQ(1u, interceptor
.GetPendingSize());
2131 content::WindowedNotificationObserver
update_observer(
2132 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2133 content::NotificationService::AllSources());
2135 // Set a higher minimum version, just intend to trigger a policy update.
2136 extensions::ExtensionManagementPolicyUpdater
management_policy(
2138 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.3");
2140 base::RunLoop().RunUntilIdle();
2141 update_observer
.Wait();
2143 EXPECT_EQ(0u, interceptor
.GetPendingSize());
2145 // It should be updated to 1.0.0.1 but remain disabled.
2146 EXPECT_EQ("1.0.0.1",
2147 service
->GetInstalledExtension(kGoodCrxId
)->version()->GetString());
2148 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2149 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2150 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2152 // Remove the minimum version requirement. The extension should be re-enabled.
2154 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2155 management_policy
.UnsetMinimumVersionRequired(kGoodCrxId
);
2157 base::RunLoop().RunUntilIdle();
2159 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2160 EXPECT_FALSE(extension_prefs
->HasDisableReason(
2161 kGoodCrxId
, extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
));
2164 // Verifies that a force-installed extension which does not meet a subsequently
2165 // set minimum version requirement is handled well.
2166 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionMinimumVersionForceInstalled
) {
2167 extensions::ExtensionRegistry
* registry
=
2168 extensions::ExtensionRegistry::Get(browser()->profile());
2169 extensions::ExtensionPrefs
* extension_prefs
=
2170 extensions::ExtensionPrefs::Get(browser()->profile());
2172 // Prepare the update URL for force installing.
2173 const base::FilePath path
=
2174 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
2175 const GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
2177 // Set policy to force-install the extension, it should be installed and
2179 content::WindowedNotificationObserver
install_observer(
2180 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
2181 content::NotificationService::AllSources());
2182 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2184 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2185 management_policy
.SetIndividualExtensionAutoInstalled(kGoodCrxId
,
2188 base::RunLoop().RunUntilIdle();
2189 install_observer
.Wait();
2191 EXPECT_TRUE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2193 // Set policy a minimum version of "1.0.0.1", the extension now should be
2196 extensions::ExtensionManagementPolicyUpdater
management_policy(&provider_
);
2197 management_policy
.SetMinimumVersionRequired(kGoodCrxId
, "1.0.0.1");
2199 base::RunLoop().RunUntilIdle();
2200 EXPECT_FALSE(registry
->enabled_extensions().Contains(kGoodCrxId
));
2201 EXPECT_TRUE(registry
->disabled_extensions().Contains(kGoodCrxId
));
2202 EXPECT_EQ(extensions::Extension::DISABLE_UPDATE_REQUIRED_BY_POLICY
,
2203 extension_prefs
->GetDisableReasons(kGoodCrxId
));
2206 IN_PROC_BROWSER_TEST_F(PolicyTest
, HomepageLocation
) {
2207 #if defined(OS_WIN) && defined(USE_ASH)
2208 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2209 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2210 switches::kAshBrowserTests
))
2214 // Verifies that the homepage can be configured with policies.
2215 // Set a default, and check that the home button navigates there.
2216 browser()->profile()->GetPrefs()->SetString(
2217 prefs::kHomePage
, chrome::kChromeUIPolicyURL
);
2218 browser()->profile()->GetPrefs()->SetBoolean(
2219 prefs::kHomePageIsNewTabPage
, false);
2220 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
),
2221 browser()->profile()->GetHomePage());
2222 content::WebContents
* contents
=
2223 browser()->tab_strip_model()->GetActiveWebContents();
2224 EXPECT_EQ(GURL(url::kAboutBlankURL
), contents
->GetURL());
2225 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2226 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
), contents
->GetURL());
2228 // Now override with policy.
2230 policies
.Set(key::kHomepageLocation
,
2231 POLICY_LEVEL_MANDATORY
,
2233 new base::StringValue(chrome::kChromeUICreditsURL
),
2235 UpdateProviderPolicy(policies
);
2236 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2237 content::WaitForLoadStop(contents
);
2238 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL
), contents
->GetURL());
2240 policies
.Set(key::kHomepageIsNewTabPage
,
2241 POLICY_LEVEL_MANDATORY
,
2243 new base::FundamentalValue(true),
2245 UpdateProviderPolicy(policies
);
2246 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
2247 content::WaitForLoadStop(contents
);
2248 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL
), contents
->GetURL());
2251 IN_PROC_BROWSER_TEST_F(PolicyTest
, IncognitoEnabled
) {
2252 // Verifies that incognito windows can't be opened when disabled by policy.
2254 const BrowserList
* active_browser_list
=
2255 BrowserList::GetInstance(chrome::GetActiveDesktop());
2257 // Disable incognito via policy and verify that incognito windows can't be
2259 EXPECT_EQ(1u, active_browser_list
->size());
2260 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2262 policies
.Set(key::kIncognitoEnabled
,
2263 POLICY_LEVEL_MANDATORY
,
2265 new base::FundamentalValue(false),
2267 UpdateProviderPolicy(policies
);
2268 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2269 EXPECT_EQ(1u, active_browser_list
->size());
2270 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
2272 // Enable via policy and verify that incognito windows can be opened.
2273 policies
.Set(key::kIncognitoEnabled
,
2274 POLICY_LEVEL_MANDATORY
,
2276 new base::FundamentalValue(true),
2278 UpdateProviderPolicy(policies
);
2279 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
2280 EXPECT_EQ(2u, active_browser_list
->size());
2281 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
2284 IN_PROC_BROWSER_TEST_F(PolicyTest
, Javascript
) {
2285 // Verifies that Javascript can be disabled.
2286 content::WebContents
* contents
=
2287 browser()->tab_strip_model()->GetActiveWebContents();
2288 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2289 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2290 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2291 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2293 // Disable Javascript via policy.
2295 policies
.Set(key::kJavascriptEnabled
,
2296 POLICY_LEVEL_MANDATORY
,
2298 new base::FundamentalValue(false),
2300 UpdateProviderPolicy(policies
);
2302 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2303 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2304 // Developer tools still work when javascript is disabled.
2305 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
2306 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
2307 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
2308 // Javascript is always enabled for the internal pages.
2309 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL
));
2310 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2312 // The javascript content setting policy overrides the javascript policy.
2313 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2314 EXPECT_FALSE(IsJavascriptEnabled(contents
));
2315 policies
.Set(key::kDefaultJavaScriptSetting
,
2316 POLICY_LEVEL_MANDATORY
,
2318 new base::FundamentalValue(CONTENT_SETTING_ALLOW
),
2320 UpdateProviderPolicy(policies
);
2321 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
2322 EXPECT_TRUE(IsJavascriptEnabled(contents
));
2325 IN_PROC_BROWSER_TEST_F(PolicyTest
, NetworkPrediction
) {
2326 PrefService
* prefs
= browser()->profile()->GetPrefs();
2328 // Enabled by default.
2329 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2331 // Disable by old, deprecated policy.
2333 policies
.Set(key::kDnsPrefetchingEnabled
,
2334 POLICY_LEVEL_MANDATORY
,
2336 new base::FundamentalValue(false),
2338 UpdateProviderPolicy(policies
);
2340 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs
));
2342 // Enabled by new policy, this should override old one.
2344 key::kNetworkPredictionOptions
,
2345 POLICY_LEVEL_MANDATORY
,
2347 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS
),
2349 UpdateProviderPolicy(policies
);
2351 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2354 IN_PROC_BROWSER_TEST_F(PolicyTest
, SavingBrowserHistoryDisabled
) {
2355 // Verifies that browsing history is not saved.
2357 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2358 POLICY_LEVEL_MANDATORY
,
2360 new base::FundamentalValue(true),
2362 UpdateProviderPolicy(policies
);
2363 GURL url
= ui_test_utils::GetTestUrl(
2364 base::FilePath(base::FilePath::kCurrentDirectory
),
2365 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2366 ui_test_utils::NavigateToURL(browser(), url
);
2367 // Verify that the navigation wasn't saved in the history.
2368 ui_test_utils::HistoryEnumerator
enumerator1(browser()->profile());
2369 EXPECT_EQ(0u, enumerator1
.urls().size());
2371 // Now flip the policy and try again.
2372 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2373 POLICY_LEVEL_MANDATORY
,
2375 new base::FundamentalValue(false),
2377 UpdateProviderPolicy(policies
);
2378 ui_test_utils::NavigateToURL(browser(), url
);
2379 // Verify that the navigation was saved in the history.
2380 ui_test_utils::HistoryEnumerator
enumerator2(browser()->profile());
2381 ASSERT_EQ(1u, enumerator2
.urls().size());
2382 EXPECT_EQ(url
, enumerator2
.urls()[0]);
2385 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2386 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_TranslateEnabled
) {
2387 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2388 if (TranslateService::IsTranslateBubbleEnabled())
2391 scoped_ptr
<test::CldDataHarness
> cld_data_scope
=
2392 test::CldDataHarnessFactory::Get()->CreateCldDataHarness();
2393 ASSERT_NO_FATAL_FAILURE(cld_data_scope
->Init());
2395 // Verifies that translate can be forced enabled or disabled by policy.
2397 // Get the InfoBarService, and verify that there are no infobars on startup.
2398 content::WebContents
* contents
=
2399 browser()->tab_strip_model()->GetActiveWebContents();
2400 ASSERT_TRUE(contents
);
2401 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
2402 ASSERT_TRUE(infobar_service
);
2403 EXPECT_EQ(0u, infobar_service
->infobar_count());
2405 // Force enable the translate feature.
2407 policies
.Set(key::kTranslateEnabled
,
2408 POLICY_LEVEL_MANDATORY
,
2410 new base::FundamentalValue(true),
2412 UpdateProviderPolicy(policies
);
2413 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2414 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2415 // TranslateManager observes. This allows checking that an infobar is NOT
2416 // shown below, without polling for infobars for some indeterminate amount
2418 GURL url
= ui_test_utils::GetTestUrl(
2420 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2421 content::WindowedNotificationObserver
language_observer1(
2422 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2423 content::NotificationService::AllSources());
2424 ui_test_utils::NavigateToURL(browser(), url
);
2425 language_observer1
.Wait();
2427 // Verify the translation detected for this tab.
2428 ChromeTranslateClient
* chrome_translate_client
=
2429 ChromeTranslateClient::FromWebContents(contents
);
2430 ASSERT_TRUE(chrome_translate_client
);
2431 translate::LanguageState
& language_state
=
2432 chrome_translate_client
->GetLanguageState();
2433 EXPECT_EQ("fr", language_state
.original_language());
2434 EXPECT_TRUE(language_state
.page_needs_translation());
2435 EXPECT_FALSE(language_state
.translation_pending());
2436 EXPECT_FALSE(language_state
.translation_declined());
2437 EXPECT_FALSE(language_state
.IsPageTranslated());
2439 // Verify that the translate infobar showed up.
2440 ASSERT_EQ(1u, infobar_service
->infobar_count());
2441 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2442 translate::TranslateInfoBarDelegate
* translate_infobar_delegate
=
2443 infobar
->delegate()->AsTranslateInfoBarDelegate();
2444 ASSERT_TRUE(translate_infobar_delegate
);
2445 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE
,
2446 translate_infobar_delegate
->translate_step());
2447 EXPECT_EQ("fr", translate_infobar_delegate
->original_language_code());
2449 // Now force disable translate.
2450 infobar_service
->RemoveInfoBar(infobar
);
2451 EXPECT_EQ(0u, infobar_service
->infobar_count());
2452 policies
.Set(key::kTranslateEnabled
,
2453 POLICY_LEVEL_MANDATORY
,
2455 new base::FundamentalValue(false),
2457 UpdateProviderPolicy(policies
);
2458 // Navigating to the same URL now doesn't trigger an infobar.
2459 content::WindowedNotificationObserver
language_observer2(
2460 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2461 content::NotificationService::AllSources());
2462 ui_test_utils::NavigateToURL(browser(), url
);
2463 language_observer2
.Wait();
2464 EXPECT_EQ(0u, infobar_service
->infobar_count());
2467 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklist
) {
2468 // Checks that URLs can be blacklisted, and that exceptions can be made to
2471 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2472 // as URLRequestMockHTTPJobs.
2473 const char* kURLS
[] = {
2474 "http://aaa.com/empty.html",
2475 "http://bbb.com/empty.html",
2476 "http://sub.bbb.com/empty.html",
2477 "http://bbb.com/policy/blank.html",
2478 "http://bbb.com./policy/blank.html",
2482 BrowserThread::PostTaskAndReply(
2483 BrowserThread::IO
, FROM_HERE
,
2484 base::Bind(RedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2485 loop
.QuitClosure());
2489 // Verify that "bbb.com" opens before applying the blacklist.
2490 CheckCanOpenURL(browser(), kURLS
[1]);
2493 base::ListValue blacklist
;
2494 blacklist
.Append(new base::StringValue("bbb.com"));
2496 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2497 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2498 UpdateProviderPolicy(policies
);
2499 FlushBlacklistPolicy();
2500 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2501 CheckCanOpenURL(browser(), kURLS
[0]);
2502 for (size_t i
= 1; i
< arraysize(kURLS
); ++i
)
2503 CheckURLIsBlocked(browser(), kURLS
[i
]);
2505 // Whitelist some sites of bbb.com.
2506 base::ListValue whitelist
;
2507 whitelist
.Append(new base::StringValue("sub.bbb.com"));
2508 whitelist
.Append(new base::StringValue("bbb.com/policy"));
2509 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2510 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2511 UpdateProviderPolicy(policies
);
2512 FlushBlacklistPolicy();
2513 CheckURLIsBlocked(browser(), kURLS
[1]);
2514 CheckCanOpenURL(browser(), kURLS
[2]);
2515 CheckCanOpenURL(browser(), kURLS
[3]);
2516 CheckCanOpenURL(browser(), kURLS
[4]);
2520 BrowserThread::PostTaskAndReply(
2521 BrowserThread::IO
, FROM_HERE
,
2522 base::Bind(UndoRedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2523 loop
.QuitClosure());
2528 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklistSubresources
) {
2529 // Checks that an image with a blacklisted URL is loaded, but an iframe with a
2530 // blacklisted URL is not.
2532 GURL main_url
= URLRequestMockHTTPJob::GetMockUrl(
2533 base::FilePath(FILE_PATH_LITERAL("policy/blacklist-subresources.html")));
2534 GURL image_url
= URLRequestMockHTTPJob::GetMockUrl(
2535 base::FilePath(FILE_PATH_LITERAL("policy/pixel.png")));
2536 GURL subframe_url
= URLRequestMockHTTPJob::GetMockUrl(
2537 base::FilePath(FILE_PATH_LITERAL("policy/blank.html")));
2539 // Set a blacklist containing the image and the iframe which are used by the
2541 base::ListValue blacklist
;
2542 blacklist
.Append(new base::StringValue(image_url
.spec().c_str()));
2543 blacklist
.Append(new base::StringValue(subframe_url
.spec().c_str()));
2545 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2546 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2547 UpdateProviderPolicy(policies
);
2548 FlushBlacklistPolicy();
2550 std::string blacklisted_image_load_result
;
2551 ui_test_utils::NavigateToURL(browser(), main_url
);
2552 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2553 browser()->tab_strip_model()->GetActiveWebContents(),
2554 "window.domAutomationController.send(imageLoadResult)",
2555 &blacklisted_image_load_result
));
2556 EXPECT_EQ("success", blacklisted_image_load_result
);
2558 std::string blacklisted_iframe_load_result
;
2559 ui_test_utils::NavigateToURL(browser(), main_url
);
2560 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2561 browser()->tab_strip_model()->GetActiveWebContents(),
2562 "window.domAutomationController.send(iframeLoadResult)",
2563 &blacklisted_iframe_load_result
));
2564 EXPECT_EQ("error", blacklisted_iframe_load_result
);
2567 #if defined(OS_MACOSX)
2568 // http://crbug.com/339240
2569 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2571 #define MAYBE_FileURLBlacklist FileURLBlacklist
2573 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_FileURLBlacklist
) {
2574 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2575 // with URLblacklisting and URLwhitelisting.
2577 base::FilePath test_path
;
2578 PathService::Get(chrome::DIR_TEST_DATA
, &test_path
);
2579 const std::string base_path
= "file://" + test_path
.AsUTF8Unsafe() +"/";
2580 const std::string folder_path
= base_path
+ "apptest/";
2581 const std::string file_path1
= base_path
+ "title1.html";
2582 const std::string file_path2
= folder_path
+ "basic.html";
2584 CheckCanOpenURL(browser(), file_path1
.c_str());
2585 CheckCanOpenURL(browser(), file_path2
.c_str());
2587 // Set a blacklist for all the files.
2588 base::ListValue blacklist
;
2589 blacklist
.Append(new base::StringValue("file://*"));
2591 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2592 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2593 UpdateProviderPolicy(policies
);
2594 FlushBlacklistPolicy();
2596 CheckURLIsBlocked(browser(), file_path1
.c_str());
2597 CheckURLIsBlocked(browser(), file_path2
.c_str());
2599 // Replace the URLblacklist with disabling the file scheme.
2600 blacklist
.Remove(base::StringValue("file://*"), NULL
);
2601 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2602 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2603 UpdateProviderPolicy(policies
);
2604 FlushBlacklistPolicy();
2606 PrefService
* prefs
= browser()->profile()->GetPrefs();
2607 const base::ListValue
* list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2608 EXPECT_EQ(list_url
->Find(base::StringValue("file://*")),
2611 base::ListValue disabledscheme
;
2612 disabledscheme
.Append(new base::StringValue("file"));
2613 policies
.Set(key::kDisabledSchemes
, POLICY_LEVEL_MANDATORY
,
2614 POLICY_SCOPE_USER
, disabledscheme
.DeepCopy(), NULL
);
2615 UpdateProviderPolicy(policies
);
2616 FlushBlacklistPolicy();
2618 list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2619 EXPECT_NE(list_url
->Find(base::StringValue("file://*")),
2622 // Whitelist one folder and blacklist an another just inside.
2623 base::ListValue whitelist
;
2624 whitelist
.Append(new base::StringValue(base_path
));
2625 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2626 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2627 blacklist
.Append(new base::StringValue(folder_path
));
2628 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2629 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2630 UpdateProviderPolicy(policies
);
2631 FlushBlacklistPolicy();
2633 CheckCanOpenURL(browser(), file_path1
.c_str());
2634 CheckURLIsBlocked(browser(), file_path2
.c_str());
2639 void GetSSLVersionFallbackMinOnIOThread(
2640 const scoped_refptr
<net::SSLConfigService
>& config_service
,
2641 uint16_t* version_fallback_min
) {
2642 net::SSLConfig config
;
2643 config_service
->GetSSLConfig(&config
);
2644 *version_fallback_min
= config
.version_fallback_min
;
2647 uint16_t GetSSLVersionFallbackMin(Profile
* profile
) {
2648 scoped_refptr
<net::SSLConfigService
> config_service(
2649 profile
->GetSSLConfigService());
2650 uint16_t version_fallback_min
;
2652 BrowserThread::PostTaskAndReply(
2653 BrowserThread::IO
, FROM_HERE
,
2654 base::Bind(&GetSSLVersionFallbackMinOnIOThread
, config_service
,
2655 base::Unretained(&version_fallback_min
)),
2656 loop
.QuitClosure());
2658 return version_fallback_min
;
2663 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionFallbackMin
) {
2664 PrefService
* prefs
= g_browser_process
->local_state();
2666 const std::string
new_value("tls1.2");
2667 const std::string
default_value(
2668 prefs
->GetString(prefs::kSSLVersionFallbackMin
));
2670 EXPECT_NE(default_value
, new_value
);
2671 EXPECT_NE(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2672 GetSSLVersionFallbackMin(browser()->profile()));
2675 policies
.Set(key::kSSLVersionFallbackMin
,
2676 POLICY_LEVEL_MANDATORY
,
2678 new base::StringValue(new_value
),
2680 UpdateProviderPolicy(policies
);
2682 EXPECT_EQ(net::SSL_PROTOCOL_VERSION_TLS1_2
,
2683 GetSSLVersionFallbackMin(browser()->profile()));
2686 #if !defined(OS_MACOSX)
2687 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedBrowser
) {
2689 policies
.Set(key::kFullscreenAllowed
,
2690 POLICY_LEVEL_MANDATORY
,
2692 new base::FundamentalValue(false),
2694 UpdateProviderPolicy(policies
);
2696 BrowserWindow
* browser_window
= browser()->window();
2697 ASSERT_TRUE(browser_window
);
2699 EXPECT_FALSE(browser_window
->IsFullscreen());
2700 chrome::ToggleFullscreenMode(browser());
2701 EXPECT_FALSE(browser_window
->IsFullscreen());
2704 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedApp
) {
2706 policies
.Set(key::kFullscreenAllowed
,
2707 POLICY_LEVEL_MANDATORY
,
2709 new base::FundamentalValue(false),
2711 UpdateProviderPolicy(policies
);
2713 const extensions::Extension
* extension
=
2714 LoadUnpackedExtension(kUnpackedFullscreenAppName
, true);
2715 ASSERT_TRUE(extension
);
2717 // Launch an app that tries to open a fullscreen window.
2718 TestAddAppWindowObserver
add_window_observer(
2719 extensions::AppWindowRegistry::Get(browser()->profile()));
2720 OpenApplication(AppLaunchParams(browser()->profile(), extension
,
2721 extensions::LAUNCH_CONTAINER_NONE
, NEW_WINDOW
,
2722 extensions::SOURCE_TEST
));
2723 extensions::AppWindow
* window
= add_window_observer
.WaitForAppWindow();
2724 ASSERT_TRUE(window
);
2726 // Verify that the window is not in fullscreen mode.
2727 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2729 // Verify that the window cannot be toggled into fullscreen mode via apps
2731 EXPECT_TRUE(content::ExecuteScript(
2732 window
->web_contents(),
2733 "chrome.app.window.current().fullscreen();"));
2734 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2736 // Verify that the window cannot be toggled into fullscreen mode from within
2737 // Chrome (e.g., using keyboard accelerators).
2738 window
->Fullscreen();
2739 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2743 #if defined(OS_CHROMEOS)
2745 // Flaky http://crbug.com/476964
2746 #if defined(MEMORY_SANITIZER)
2747 #define MAYBE_DisableScreenshotsFile DISABLED_DisableScreenshotsFile
2749 #define MAYBE_DisableScreenshotsFile DisableScreenshotsFile
2752 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_DisableScreenshotsFile
) {
2753 int screenshot_count
= CountScreenshots();
2755 // Make sure screenshots are counted correctly.
2756 TestScreenshotFile(true);
2757 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2759 // Check if trying to take a screenshot fails when disabled by policy.
2760 TestScreenshotFile(false);
2761 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2764 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableAudioOutput
) {
2765 // Set up the mock observer.
2766 chromeos::CrasAudioHandler
* audio_handler
= chromeos::CrasAudioHandler::Get();
2767 scoped_ptr
<TestAudioObserver
> test_observer(new TestAudioObserver
);
2768 audio_handler
->AddAudioObserver(test_observer
.get());
2770 bool prior_state
= audio_handler
->IsOutputMuted();
2771 // Make sure the audio is not muted and then toggle the policy and observe
2772 // if the output mute changed event is fired.
2773 audio_handler
->SetOutputMute(false);
2774 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2775 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2777 policies
.Set(key::kAudioOutputAllowed
,
2778 POLICY_LEVEL_MANDATORY
,
2780 new base::FundamentalValue(false),
2782 UpdateProviderPolicy(policies
);
2783 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2784 // This should not change the state now and should not trigger output mute
2786 audio_handler
->SetOutputMute(false);
2787 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2788 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2790 // Toggle back and observe if the output mute changed event is fired.
2791 policies
.Set(key::kAudioOutputAllowed
,
2792 POLICY_LEVEL_MANDATORY
,
2794 new base::FundamentalValue(true),
2796 UpdateProviderPolicy(policies
);
2797 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2798 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2799 audio_handler
->SetOutputMute(true);
2800 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2801 EXPECT_EQ(2, test_observer
->output_mute_changed_count());
2802 // Revert the prior state.
2803 audio_handler
->SetOutputMute(prior_state
);
2804 audio_handler
->RemoveAudioObserver(test_observer
.get());
2807 // Disabled, see http://crbug.com/315308.
2808 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_PRE_SessionLengthLimit
) {
2809 // Indicate that the session started 2 hours ago and no user activity has
2811 g_browser_process
->local_state()->SetInt64(
2812 prefs::kSessionStartTime
,
2813 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2814 .ToInternalValue());
2817 // Disabled, see http://crbug.com/315308.
2818 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_SessionLengthLimit
) {
2819 content::MockNotificationObserver observer
;
2820 content::NotificationRegistrar registrar
;
2821 registrar
.Add(&observer
,
2822 chrome::NOTIFICATION_APP_TERMINATING
,
2823 content::NotificationService::AllSources());
2825 // Set the session length limit to 3 hours. Verify that the session is not
2827 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2830 policies
.Set(key::kSessionLengthLimit
,
2831 POLICY_LEVEL_MANDATORY
,
2833 new base::FundamentalValue(kThreeHoursInMs
),
2835 UpdateProviderPolicy(policies
);
2836 base::RunLoop().RunUntilIdle();
2837 Mock::VerifyAndClearExpectations(&observer
);
2839 // Decrease the session length limit to 1 hour. Verify that the session is
2840 // terminated immediately.
2841 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2842 policies
.Set(key::kSessionLengthLimit
,
2843 POLICY_LEVEL_MANDATORY
,
2845 new base::FundamentalValue(kOneHourInMs
),
2847 UpdateProviderPolicy(policies
);
2848 base::RunLoop().RunUntilIdle();
2849 Mock::VerifyAndClearExpectations(&observer
);
2852 // Disabled, see http://crbug.com/315308.
2853 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2854 DISABLED_PRE_WaitForInitialUserActivityUsatisfied
) {
2855 // Indicate that the session started 2 hours ago and no user activity has
2857 g_browser_process
->local_state()->SetInt64(
2858 prefs::kSessionStartTime
,
2859 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2860 .ToInternalValue());
2863 // Disabled, see http://crbug.com/315308.
2864 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2865 DISABLED_WaitForInitialUserActivityUsatisfied
) {
2866 content::MockNotificationObserver observer
;
2867 content::NotificationRegistrar registrar
;
2868 registrar
.Add(&observer
,
2869 chrome::NOTIFICATION_APP_TERMINATING
,
2870 content::NotificationService::AllSources());
2872 // Require initial user activity.
2874 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2876 new base::FundamentalValue(true),
2878 UpdateProviderPolicy(policies
);
2879 base::RunLoop().RunUntilIdle();
2881 // Set the session length limit to 1 hour. Verify that the session is not
2883 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2885 policies
.Set(key::kSessionLengthLimit
,
2886 POLICY_LEVEL_MANDATORY
,
2888 new base::FundamentalValue(kOneHourInMs
),
2890 UpdateProviderPolicy(policies
);
2891 base::RunLoop().RunUntilIdle();
2892 Mock::VerifyAndClearExpectations(&observer
);
2895 // Disabled, see http://crbug.com/315308.
2896 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2897 DISABLED_PRE_WaitForInitialUserActivitySatisfied
) {
2898 // Indicate that initial user activity in this session occurred 2 hours ago.
2899 g_browser_process
->local_state()->SetInt64(
2900 prefs::kSessionStartTime
,
2901 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2902 .ToInternalValue());
2903 g_browser_process
->local_state()->SetBoolean(
2904 prefs::kSessionUserActivitySeen
,
2908 // Disabled, see http://crbug.com/315308.
2909 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2910 DISABLED_WaitForInitialUserActivitySatisfied
) {
2911 content::MockNotificationObserver observer
;
2912 content::NotificationRegistrar registrar
;
2913 registrar
.Add(&observer
,
2914 chrome::NOTIFICATION_APP_TERMINATING
,
2915 content::NotificationService::AllSources());
2917 // Require initial user activity and set the session length limit to 3 hours.
2918 // Verify that the session is not terminated.
2919 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2922 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2924 new base::FundamentalValue(true),
2926 policies
.Set(key::kSessionLengthLimit
,
2927 POLICY_LEVEL_MANDATORY
,
2929 new base::FundamentalValue(kThreeHoursInMs
),
2931 UpdateProviderPolicy(policies
);
2932 base::RunLoop().RunUntilIdle();
2933 Mock::VerifyAndClearExpectations(&observer
);
2935 // Decrease the session length limit to 1 hour. Verify that the session is
2936 // terminated immediately.
2937 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2938 policies
.Set(key::kSessionLengthLimit
,
2939 POLICY_LEVEL_MANDATORY
,
2941 new base::FundamentalValue(kOneHourInMs
),
2943 UpdateProviderPolicy(policies
);
2944 base::RunLoop().RunUntilIdle();
2945 Mock::VerifyAndClearExpectations(&observer
);
2948 IN_PROC_BROWSER_TEST_F(PolicyTest
, LargeCursorEnabled
) {
2949 // Verifies that the large cursor accessibility feature can be controlled
2951 chromeos::AccessibilityManager
* accessibility_manager
=
2952 chromeos::AccessibilityManager::Get();
2954 // Manually enable the large cursor.
2955 accessibility_manager
->EnableLargeCursor(true);
2956 EXPECT_TRUE(accessibility_manager
->IsLargeCursorEnabled());
2958 // Verify that policy overrides the manual setting.
2960 policies
.Set(key::kLargeCursorEnabled
,
2961 POLICY_LEVEL_MANDATORY
,
2963 new base::FundamentalValue(false),
2965 UpdateProviderPolicy(policies
);
2966 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2968 // Verify that the large cursor cannot be enabled manually anymore.
2969 accessibility_manager
->EnableLargeCursor(true);
2970 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2973 IN_PROC_BROWSER_TEST_F(PolicyTest
, SpokenFeedbackEnabled
) {
2974 // Verifies that the spoken feedback accessibility feature can be controlled
2976 chromeos::AccessibilityManager
* accessibility_manager
=
2977 chromeos::AccessibilityManager::Get();
2979 // Manually enable spoken feedback.
2980 accessibility_manager
->EnableSpokenFeedback(
2981 true, ui::A11Y_NOTIFICATION_NONE
);
2982 EXPECT_TRUE(accessibility_manager
->IsSpokenFeedbackEnabled());
2984 // Verify that policy overrides the manual setting.
2986 policies
.Set(key::kSpokenFeedbackEnabled
,
2987 POLICY_LEVEL_MANDATORY
,
2989 new base::FundamentalValue(false),
2991 UpdateProviderPolicy(policies
);
2992 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2994 // Verify that spoken feedback cannot be enabled manually anymore.
2995 accessibility_manager
->EnableSpokenFeedback(
2996 true, ui::A11Y_NOTIFICATION_NONE
);
2997 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
3000 IN_PROC_BROWSER_TEST_F(PolicyTest
, HighContrastEnabled
) {
3001 // Verifies that the high contrast mode accessibility feature can be
3002 // controlled through policy.
3003 chromeos::AccessibilityManager
* accessibility_manager
=
3004 chromeos::AccessibilityManager::Get();
3006 // Manually enable high contrast mode.
3007 accessibility_manager
->EnableHighContrast(true);
3008 EXPECT_TRUE(accessibility_manager
->IsHighContrastEnabled());
3010 // Verify that policy overrides the manual setting.
3012 policies
.Set(key::kHighContrastEnabled
,
3013 POLICY_LEVEL_MANDATORY
,
3015 new base::FundamentalValue(false),
3017 UpdateProviderPolicy(policies
);
3018 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3020 // Verify that high contrast mode cannot be enabled manually anymore.
3021 accessibility_manager
->EnableHighContrast(true);
3022 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
3025 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeNone
) {
3026 // Verifies that the screen magnifier can be disabled through policy.
3027 chromeos::MagnificationManager
* magnification_manager
=
3028 chromeos::MagnificationManager::Get();
3030 // Manually enable the full-screen magnifier.
3031 magnification_manager
->SetMagnifierType(ui::MAGNIFIER_FULL
);
3032 magnification_manager
->SetMagnifierEnabled(true);
3033 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3034 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3036 // Verify that policy overrides the manual setting.
3038 policies
.Set(key::kScreenMagnifierType
,
3039 POLICY_LEVEL_MANDATORY
,
3041 new base::FundamentalValue(0),
3043 UpdateProviderPolicy(policies
);
3044 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3046 // Verify that the screen magnifier cannot be enabled manually anymore.
3047 magnification_manager
->SetMagnifierEnabled(true);
3048 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3051 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeFull
) {
3052 // Verifies that the full-screen magnifier can be enabled through policy.
3053 chromeos::MagnificationManager
* magnification_manager
=
3054 chromeos::MagnificationManager::Get();
3056 // Verify that the screen magnifier is initially disabled.
3057 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
3059 // Verify that policy can enable the full-screen magnifier.
3061 policies
.Set(key::kScreenMagnifierType
,
3062 POLICY_LEVEL_MANDATORY
,
3064 new base::FundamentalValue(ui::MAGNIFIER_FULL
),
3066 UpdateProviderPolicy(policies
);
3067 EXPECT_EQ(ui::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
3068 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3070 // Verify that the screen magnifier cannot be disabled manually anymore.
3071 magnification_manager
->SetMagnifierEnabled(false);
3072 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
3075 IN_PROC_BROWSER_TEST_F(PolicyTest
, AccessibilityVirtualKeyboardEnabled
) {
3076 // Verifies that the on-screen keyboard accessibility feature can be
3077 // controlled through policy.
3078 chromeos::AccessibilityManager
* accessibility_manager
=
3079 chromeos::AccessibilityManager::Get();
3081 // Manually enable the on-screen keyboard.
3082 accessibility_manager
->EnableVirtualKeyboard(true);
3083 EXPECT_TRUE(accessibility_manager
->IsVirtualKeyboardEnabled());
3085 // Verify that policy overrides the manual setting.
3087 policies
.Set(key::kVirtualKeyboardEnabled
,
3088 POLICY_LEVEL_MANDATORY
,
3090 new base::FundamentalValue(false),
3092 UpdateProviderPolicy(policies
);
3093 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3095 // Verify that the on-screen keyboard cannot be enabled manually anymore.
3096 accessibility_manager
->EnableVirtualKeyboard(true);
3097 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
3100 IN_PROC_BROWSER_TEST_F(PolicyTest
, VirtualKeyboardEnabled
) {
3101 // Verify keyboard disabled by default.
3102 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3103 // Verify keyboard can be toggled by default.
3104 keyboard::SetTouchKeyboardEnabled(true);
3105 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3106 keyboard::SetTouchKeyboardEnabled(false);
3107 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3109 // Verify enabling the policy takes effect immediately and that that user
3110 // cannot disable the keyboard..
3112 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3113 POLICY_LEVEL_MANDATORY
,
3115 new base::FundamentalValue(true),
3117 UpdateProviderPolicy(policies
);
3118 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3119 keyboard::SetTouchKeyboardEnabled(false);
3120 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
3122 // Verify that disabling the policy takes effect immediately and that the user
3123 // cannot enable the keyboard.
3124 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
3125 POLICY_LEVEL_MANDATORY
,
3127 new base::FundamentalValue(false),
3129 UpdateProviderPolicy(policies
);
3130 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3131 keyboard::SetTouchKeyboardEnabled(true);
3132 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
3139 static const char* kRestoredURLs
[] = {
3140 "http://aaa.com/empty.html",
3141 "http://bbb.com/empty.html",
3144 bool IsNonSwitchArgument(const base::CommandLine::StringType
& s
) {
3145 return s
.empty() || s
[0] != '-';
3150 // Similar to PolicyTest but allows setting policies before the browser is
3151 // created. Each test parameter is a method that sets up the early policies
3152 // and stores the expected startup URLs in |expected_urls_|.
3153 class RestoreOnStartupPolicyTest
3154 : public PolicyTest
,
3155 public testing::WithParamInterface
<
3156 void (RestoreOnStartupPolicyTest::*)(void)> {
3158 RestoreOnStartupPolicyTest() {}
3159 virtual ~RestoreOnStartupPolicyTest() {}
3161 #if defined(OS_CHROMEOS)
3162 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
3163 // TODO(nkostylev): Investigate if we can remove this switch.
3164 command_line
->AppendSwitch(switches::kCreateBrowserOnStartupForTests
);
3165 PolicyTest::SetUpCommandLine(command_line
);
3169 void SetUpInProcessBrowserTestFixture() override
{
3170 PolicyTest::SetUpInProcessBrowserTestFixture();
3171 // Set early policies now, before the browser is created.
3172 (this->*(GetParam()))();
3174 // Remove the non-switch arguments, so that session restore kicks in for
3176 base::CommandLine
* command_line
= base::CommandLine::ForCurrentProcess();
3177 base::CommandLine::StringVector argv
= command_line
->argv();
3178 argv
.erase(std::remove_if(++argv
.begin(), argv
.end(), IsNonSwitchArgument
),
3180 command_line
->InitFromArgv(argv
);
3181 ASSERT_TRUE(std::equal(argv
.begin(), argv
.end(),
3182 command_line
->argv().begin()));
3185 void SetUpOnMainThread() override
{
3186 BrowserThread::PostTask(
3190 RedirectHostsToTestData
, kRestoredURLs
, arraysize(kRestoredURLs
)));
3193 void HomepageIsNotNTP() {
3194 // Verifies that policy can set the startup pages to the homepage, when
3195 // the homepage is not the NTP.
3198 key::kRestoreOnStartup
,
3199 POLICY_LEVEL_MANDATORY
,
3201 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3203 policies
.Set(key::kHomepageIsNewTabPage
,
3204 POLICY_LEVEL_MANDATORY
,
3206 new base::FundamentalValue(false),
3208 policies
.Set(key::kHomepageLocation
,
3209 POLICY_LEVEL_MANDATORY
,
3211 new base::StringValue(kRestoredURLs
[1]),
3213 provider_
.UpdateChromePolicy(policies
);
3215 expected_urls_
.push_back(GURL(kRestoredURLs
[1]));
3218 void HomepageIsNTP() {
3219 // Verifies that policy can set the startup pages to the homepage, when
3220 // the homepage is the NTP.
3223 key::kRestoreOnStartup
,
3224 POLICY_LEVEL_MANDATORY
,
3226 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
3228 policies
.Set(key::kHomepageIsNewTabPage
,
3229 POLICY_LEVEL_MANDATORY
,
3231 new base::FundamentalValue(true),
3233 provider_
.UpdateChromePolicy(policies
);
3235 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3239 // Verifies that policy can set the startup pages to a list of URLs.
3240 base::ListValue urls
;
3241 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
) {
3242 urls
.Append(new base::StringValue(kRestoredURLs
[i
]));
3243 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3246 policies
.Set(key::kRestoreOnStartup
,
3247 POLICY_LEVEL_MANDATORY
,
3249 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs
),
3252 key::kRestoreOnStartupURLs
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3253 urls
.DeepCopy(), NULL
);
3254 provider_
.UpdateChromePolicy(policies
);
3258 // Verifies that policy can set the startup page to the NTP.
3261 key::kRestoreOnStartup
,
3262 POLICY_LEVEL_MANDATORY
,
3264 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab
),
3266 provider_
.UpdateChromePolicy(policies
);
3267 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
3271 // Verifies that policy can set the startup pages to the last session.
3273 policies
.Set(key::kRestoreOnStartup
,
3274 POLICY_LEVEL_MANDATORY
,
3276 new base::FundamentalValue(SessionStartupPref::kPrefValueLast
),
3278 provider_
.UpdateChromePolicy(policies
);
3279 // This should restore the tabs opened at PRE_RunTest below.
3280 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
)
3281 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
3284 std::vector
<GURL
> expected_urls_
;
3287 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, PRE_RunTest
) {
3288 // Open some tabs to verify if they are restored after the browser restarts.
3289 // Most policy settings override this, except kPrefValueLast which enforces
3291 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs
[0]));
3292 for (size_t i
= 1; i
< arraysize(kRestoredURLs
); ++i
) {
3293 content::WindowedNotificationObserver
observer(
3294 content::NOTIFICATION_LOAD_STOP
,
3295 content::NotificationService::AllSources());
3296 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs
[i
]),
3297 ui::PAGE_TRANSITION_LINK
);
3302 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, RunTest
) {
3303 #if defined(OS_WIN) && defined(USE_ASH)
3304 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3305 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3306 switches::kAshBrowserTests
))
3310 TabStripModel
* model
= browser()->tab_strip_model();
3311 int size
= static_cast<int>(expected_urls_
.size());
3312 EXPECT_EQ(size
, model
->count());
3313 for (int i
= 0; i
< size
&& i
< model
->count(); ++i
) {
3314 EXPECT_EQ(expected_urls_
[i
], model
->GetWebContentsAt(i
)->GetURL());
3318 INSTANTIATE_TEST_CASE_P(
3319 RestoreOnStartupPolicyTestInstance
,
3320 RestoreOnStartupPolicyTest
,
3321 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP
,
3322 &RestoreOnStartupPolicyTest::HomepageIsNTP
,
3323 &RestoreOnStartupPolicyTest::ListOfURLs
,
3324 &RestoreOnStartupPolicyTest::NTP
,
3325 &RestoreOnStartupPolicyTest::Last
));
3327 // Similar to PolicyTest but sets a couple of policies before the browser is
3329 class PolicyStatisticsCollectorTest
: public PolicyTest
{
3331 PolicyStatisticsCollectorTest() {}
3332 ~PolicyStatisticsCollectorTest() override
{}
3334 void SetUpInProcessBrowserTestFixture() override
{
3335 PolicyTest::SetUpInProcessBrowserTestFixture();
3337 policies
.Set(key::kShowHomeButton
,
3338 POLICY_LEVEL_MANDATORY
,
3340 new base::FundamentalValue(true),
3342 policies
.Set(key::kBookmarkBarEnabled
,
3343 POLICY_LEVEL_MANDATORY
,
3345 new base::FundamentalValue(false),
3347 policies
.Set(key::kHomepageLocation
,
3348 POLICY_LEVEL_MANDATORY
,
3350 new base::StringValue("http://chromium.org"),
3352 provider_
.UpdateChromePolicy(policies
);
3356 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest
, Startup
) {
3357 // Verifies that policy usage histograms are collected at startup.
3359 // BrowserPolicyConnector::Init() has already been called. Make sure the
3360 // CompleteInitialization() task has executed as well.
3361 content::RunAllPendingInMessageLoop();
3363 GURL kAboutHistograms
= GURL(std::string(url::kAboutScheme
) +
3364 std::string(url::kStandardSchemeSeparator
) +
3365 std::string(content::kChromeUIHistogramHost
));
3366 ui_test_utils::NavigateToURL(browser(), kAboutHistograms
);
3367 content::WebContents
* contents
=
3368 browser()->tab_strip_model()->GetActiveWebContents();
3370 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3372 "var nodes = document.querySelectorAll('body > pre');"
3374 "for (var i = 0; i < nodes.length; ++i) {"
3375 " var text = nodes[i].innerHTML;"
3376 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3381 "domAutomationController.send(result);",
3383 ASSERT_FALSE(text
.empty());
3384 const std::string kExpectedLabel
=
3385 "Histogram: Enterprise.Policies recorded 3 samples";
3386 EXPECT_EQ(kExpectedLabel
, text
.substr(0, kExpectedLabel
.size()));
3387 // HomepageLocation has policy ID 1.
3388 EXPECT_NE(std::string::npos
, text
.find("<br>1 ---"));
3389 // ShowHomeButton has policy ID 35.
3390 EXPECT_NE(std::string::npos
, text
.find("<br>35 ---"));
3391 // BookmarkBarEnabled has policy ID 82.
3392 EXPECT_NE(std::string::npos
, text
.find("<br>82 ---"));
3395 class MediaStreamDevicesControllerBrowserTest
3396 : public PolicyTest
,
3397 public testing::WithParamInterface
<bool> {
3399 MediaStreamDevicesControllerBrowserTest()
3400 : request_url_allowed_via_whitelist_(false),
3401 request_url_("http://www.example.com/foo") {
3402 policy_value_
= GetParam();
3404 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3406 // Configure a given policy map. The |policy_name| is the name of either the
3407 // audio or video capture allow policy and must never be NULL.
3408 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3409 // policy is set. If non-NULL, the whitelist policy is set to contain either
3410 // the |allow_rule| (if non-NULL) or an "allow all" wildcard.
3411 void ConfigurePolicyMap(PolicyMap
* policies
, const char* policy_name
,
3412 const char* whitelist_policy
,
3413 const char* allow_rule
) {
3414 policies
->Set(policy_name
,
3415 POLICY_LEVEL_MANDATORY
,
3417 new base::FundamentalValue(policy_value_
),
3420 if (whitelist_policy
) {
3421 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3422 // in the media exceptions UI.
3423 // See discussion here: https://codereview.chromium.org/15738004/
3424 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3425 switches::kKioskMode
);
3427 // Add an entry to the whitelist that allows the specified URL regardless
3428 // of the setting of kAudioCapturedAllowed.
3429 base::ListValue
* list
= new base::ListValue();
3431 list
->AppendString(allow_rule
);
3432 request_url_allowed_via_whitelist_
= true;
3434 list
->AppendString(ContentSettingsPattern::Wildcard().ToString());
3435 // We should ignore all wildcard entries in the whitelist, so even
3436 // though we've added an entry, it should be ignored and our expectation
3437 // is that the request has not been allowed via the whitelist.
3438 request_url_allowed_via_whitelist_
= false;
3440 policies
->Set(whitelist_policy
, POLICY_LEVEL_MANDATORY
,
3441 POLICY_SCOPE_USER
, list
, NULL
);
3445 void Accept(const content::MediaStreamDevices
& devices
,
3446 content::MediaStreamRequestResult result
,
3447 scoped_ptr
<content::MediaStreamUI
> ui
) {
3448 if (policy_value_
|| request_url_allowed_via_whitelist_
) {
3449 ASSERT_EQ(1U, devices
.size());
3450 ASSERT_EQ("fake_dev", devices
[0].id
);
3452 ASSERT_EQ(0U, devices
.size());
3456 void FinishAudioTest() {
3457 content::MediaStreamRequest
request(0, 0, 0,
3458 request_url_
.GetOrigin(), false,
3459 content::MEDIA_DEVICE_ACCESS
,
3460 std::string(), std::string(),
3461 content::MEDIA_DEVICE_AUDIO_CAPTURE
,
3462 content::MEDIA_NO_SERVICE
);
3463 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3464 // and microphone permissions at the same time.
3465 MediaStreamDevicesController
controller(
3466 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3467 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3468 if (controller
.IsAskingForAudio())
3469 controller
.PermissionGranted();
3471 base::MessageLoop::current()->QuitWhenIdle();
3474 void FinishVideoTest() {
3475 content::MediaStreamRequest
request(0, 0, 0,
3476 request_url_
.GetOrigin(), false,
3477 content::MEDIA_DEVICE_ACCESS
,
3480 content::MEDIA_NO_SERVICE
,
3481 content::MEDIA_DEVICE_VIDEO_CAPTURE
);
3482 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3483 // and microphone permissions at the same time.
3484 MediaStreamDevicesController
controller(
3485 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3486 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3487 if (controller
.IsAskingForVideo())
3488 controller
.PermissionGranted();
3490 base::MessageLoop::current()->QuitWhenIdle();
3494 bool request_url_allowed_via_whitelist_
;
3496 static const char kExampleRequestPattern
[];
3500 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern
[] =
3501 "http://[*.]example.com/";
3503 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3504 AudioCaptureAllowed
) {
3505 content::MediaStreamDevices audio_devices
;
3506 content::MediaStreamDevice
fake_audio_device(
3507 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3508 audio_devices
.push_back(fake_audio_device
);
3511 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
, NULL
, NULL
);
3512 UpdateProviderPolicy(policies
);
3514 content::BrowserThread::PostTaskAndReply(
3515 content::BrowserThread::IO
, FROM_HERE
,
3516 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3517 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3519 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3522 base::MessageLoop::current()->Run();
3525 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3526 AudioCaptureAllowedUrls
) {
3527 content::MediaStreamDevices audio_devices
;
3528 content::MediaStreamDevice
fake_audio_device(
3529 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3530 audio_devices
.push_back(fake_audio_device
);
3532 const char* allow_pattern
[] = {
3533 kExampleRequestPattern
,
3534 // This will set an allow-all policy whitelist. Since we do not allow
3535 // setting an allow-all entry in the whitelist, this entry should be ignored
3536 // and therefore the request should be denied.
3540 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3542 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
,
3543 key::kAudioCaptureAllowedUrls
, allow_pattern
[i
]);
3544 UpdateProviderPolicy(policies
);
3546 content::BrowserThread::PostTaskAndReply(
3547 content::BrowserThread::IO
, FROM_HERE
,
3549 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3550 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3553 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3556 base::MessageLoop::current()->Run();
3560 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3561 VideoCaptureAllowed
) {
3562 content::MediaStreamDevices video_devices
;
3563 content::MediaStreamDevice
fake_video_device(
3564 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3565 video_devices
.push_back(fake_video_device
);
3568 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
, NULL
, NULL
);
3569 UpdateProviderPolicy(policies
);
3571 content::BrowserThread::PostTaskAndReply(
3572 content::BrowserThread::IO
, FROM_HERE
,
3573 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3574 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3576 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3579 base::MessageLoop::current()->Run();
3582 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3583 VideoCaptureAllowedUrls
) {
3584 content::MediaStreamDevices video_devices
;
3585 content::MediaStreamDevice
fake_video_device(
3586 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3587 video_devices
.push_back(fake_video_device
);
3589 const char* allow_pattern
[] = {
3590 kExampleRequestPattern
,
3591 // This will set an allow-all policy whitelist. Since we do not allow
3592 // setting an allow-all entry in the whitelist, this entry should be ignored
3593 // and therefore the request should be denied.
3597 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3599 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
,
3600 key::kVideoCaptureAllowedUrls
, allow_pattern
[i
]);
3601 UpdateProviderPolicy(policies
);
3603 content::BrowserThread::PostTaskAndReply(
3604 content::BrowserThread::IO
, FROM_HERE
,
3605 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3606 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3609 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3612 base::MessageLoop::current()->Run();
3616 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance
,
3617 MediaStreamDevicesControllerBrowserTest
,
3620 // Test that when extended reporting opt-in is disabled by policy, the
3621 // opt-in checkbox does not appear on SSL blocking pages.
3622 IN_PROC_BROWSER_TEST_F(PolicyTest
, SafeBrowsingExtendedReportingOptInAllowed
) {
3623 net::SpawnedTestServer
https_server_expired(
3624 net::SpawnedTestServer::TYPE_HTTPS
,
3625 net::SpawnedTestServer::SSLOptions(
3626 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3627 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3628 ASSERT_TRUE(https_server_expired
.Start());
3630 // Set the enterprise policy to disallow opt-in.
3631 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3633 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3635 policies
.Set(key::kSafeBrowsingExtendedReportingOptInAllowed
,
3636 POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
3637 new base::FundamentalValue(false), NULL
);
3638 UpdateProviderPolicy(policies
);
3640 prefs
->GetBoolean(prefs::kSafeBrowsingExtendedReportingOptInAllowed
));
3642 // Navigate to an SSL error page.
3643 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3645 const content::InterstitialPage
* const interstitial
=
3646 content::InterstitialPage::GetInterstitialPage(
3647 browser()->tab_strip_model()->GetActiveWebContents());
3648 ASSERT_TRUE(interstitial
);
3649 ASSERT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3650 content::RenderViewHost
* const rvh
=
3651 interstitial
->GetMainFrame()->GetRenderViewHost();
3654 // Check that the checkbox is not visible.
3656 const std::string command
= base::StringPrintf(
3657 "var node = document.getElementById('extended-reporting-opt-in');"
3659 " window.domAutomationController.send(node.offsetWidth > 0 || "
3660 " node.offsetHeight > 0 ? %d : %d);"
3662 // The node should be present but not visible, so trigger an error
3663 // by sending false if it's not present.
3664 " window.domAutomationController.send(%d);"
3666 SecurityInterstitialPage::CMD_TEXT_FOUND
,
3667 SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
,
3668 SecurityInterstitialPage::CMD_ERROR
);
3669 EXPECT_TRUE(content::ExecuteScriptAndExtractInt(rvh
, command
, &result
));
3670 EXPECT_EQ(SecurityInterstitialPage::CMD_TEXT_NOT_FOUND
, result
);
3673 // Test that when SSL error overriding is allowed by policy (default), the
3674 // proceed link appears on SSL blocking pages.
3675 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingAllowed
) {
3676 net::SpawnedTestServer
https_server_expired(
3677 net::SpawnedTestServer::TYPE_HTTPS
,
3678 net::SpawnedTestServer::SSLOptions(
3679 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3680 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3681 ASSERT_TRUE(https_server_expired
.Start());
3683 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3685 // Policy should allow overriding by default.
3686 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3688 // Policy allows overriding - navigate to an SSL error page and expect the
3690 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3692 const content::InterstitialPage
* const interstitial
=
3693 content::InterstitialPage::GetInterstitialPage(
3694 browser()->tab_strip_model()->GetActiveWebContents());
3695 ASSERT_TRUE(interstitial
);
3696 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3698 // The interstitial should display the proceed link.
3699 EXPECT_TRUE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3700 interstitial
, "proceed-link"));
3703 // Test that when SSL error overriding is disallowed by policy, the
3704 // proceed link does not appear on SSL blocking pages and users should not
3705 // be able to proceed.
3706 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLErrorOverridingDisallowed
) {
3707 net::SpawnedTestServer
https_server_expired(
3708 net::SpawnedTestServer::TYPE_HTTPS
,
3709 net::SpawnedTestServer::SSLOptions(
3710 net::SpawnedTestServer::SSLOptions::CERT_EXPIRED
),
3711 base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
3712 ASSERT_TRUE(https_server_expired
.Start());
3714 const PrefService
* const prefs
= browser()->profile()->GetPrefs();
3715 EXPECT_TRUE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3717 // Disallowing the proceed link by setting the policy to |false|.
3719 policies
.Set(key::kSSLErrorOverrideAllowed
, POLICY_LEVEL_MANDATORY
,
3720 POLICY_SCOPE_USER
, new base::FundamentalValue(false), NULL
);
3721 UpdateProviderPolicy(policies
);
3723 // Policy should not allow overriding anymore.
3724 EXPECT_FALSE(prefs
->GetBoolean(prefs::kSSLErrorOverrideAllowed
));
3726 // Policy disallows overriding - navigate to an SSL error page and expect no
3728 ui_test_utils::NavigateToURL(browser(), https_server_expired
.GetURL("/"));
3729 const content::InterstitialPage
* const interstitial
=
3730 content::InterstitialPage::GetInterstitialPage(
3731 browser()->tab_strip_model()->GetActiveWebContents());
3732 ASSERT_TRUE(interstitial
);
3733 EXPECT_TRUE(content::WaitForRenderFrameReady(interstitial
->GetMainFrame()));
3735 // The interstitial should not display the proceed link.
3736 EXPECT_FALSE(chrome_browser_interstitials::IsInterstitialDisplayingText(
3737 interstitial
, "proceed-link"));
3739 // The interstitial should not proceed, even if the command is sent in
3740 // some other way (e.g., via the keyboard shortcut).
3741 content::InterstitialPageDelegate
* interstitial_delegate
=
3742 content::InterstitialPage::GetInterstitialPage(
3743 browser()->tab_strip_model()->GetActiveWebContents())
3744 ->GetDelegateForTesting();
3745 ASSERT_EQ(SSLBlockingPage::kTypeForTesting
,
3746 interstitial_delegate
->GetTypeForTesting());
3747 SSLBlockingPage
* ssl_delegate
=
3748 static_cast<SSLBlockingPage
*>(interstitial_delegate
);
3749 ssl_delegate
->CommandReceived(
3750 base::IntToString(SecurityInterstitialPage::CMD_PROCEED
));
3751 EXPECT_TRUE(interstitial
);
3752 EXPECT_TRUE(browser()
3754 ->GetActiveWebContents()
3755 ->ShowingInterstitialPage());
3758 #if !defined(OS_CHROMEOS)
3759 // Similar to PolicyTest but sets the proper policy before the browser is
3761 class PolicyVariationsServiceTest
: public PolicyTest
{
3763 void SetUpInProcessBrowserTestFixture() override
{
3764 PolicyTest::SetUpInProcessBrowserTestFixture();
3766 policies
.Set(key::kVariationsRestrictParameter
,
3767 POLICY_LEVEL_MANDATORY
,
3769 new base::StringValue("restricted"),
3771 provider_
.UpdateChromePolicy(policies
);
3775 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest
, VariationsURLIsValid
) {
3776 const std::string default_variations_url
=
3777 chrome_variations::VariationsService::
3778 GetDefaultVariationsServerURLForTesting();
3781 chrome_variations::VariationsService::GetVariationsServerURL(
3782 g_browser_process
->local_state(), std::string());
3783 EXPECT_TRUE(base::StartsWith(url
.spec(), default_variations_url
,
3784 base::CompareCase::SENSITIVE
));
3786 EXPECT_TRUE(net::GetValueForKeyInQuery(url
, "restrict", &value
));
3787 EXPECT_EQ("restricted", value
);
3790 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistSelective
) {
3791 base::ListValue blacklist
;
3792 blacklist
.Append(new base::StringValue("host.name"));
3794 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3795 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3796 UpdateProviderPolicy(policies
);
3798 PrefService
* prefs
= browser()->profile()->GetPrefs();
3799 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3800 prefs
, "host.name"));
3801 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3802 prefs
, "other.host.name"));
3805 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistWildcard
) {
3806 base::ListValue blacklist
;
3807 blacklist
.Append(new base::StringValue("*"));
3809 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3810 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3811 UpdateProviderPolicy(policies
);
3813 PrefService
* prefs
= browser()->profile()->GetPrefs();
3814 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3815 prefs
, "host.name"));
3816 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3817 prefs
, "other.host.name"));
3820 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingWhitelist
) {
3821 base::ListValue blacklist
;
3822 blacklist
.Append(new base::StringValue("*"));
3823 base::ListValue whitelist
;
3824 whitelist
.Append(new base::StringValue("host.name"));
3826 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3827 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3828 policies
.Set(key::kNativeMessagingWhitelist
, POLICY_LEVEL_MANDATORY
,
3829 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
3830 UpdateProviderPolicy(policies
);
3832 PrefService
* prefs
= browser()->profile()->GetPrefs();
3833 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3834 prefs
, "host.name"));
3835 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3836 prefs
, "other.host.name"));
3839 #endif // !defined(CHROME_OS)
3842 #if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3843 // Sets the hardware acceleration mode policy before the browser is started.
3844 class HardwareAccelerationModePolicyTest
: public PolicyTest
{
3846 HardwareAccelerationModePolicyTest() {}
3848 void SetUpInProcessBrowserTestFixture() override
{
3849 PolicyTest::SetUpInProcessBrowserTestFixture();
3851 policies
.Set(key::kHardwareAccelerationModeEnabled
,
3852 POLICY_LEVEL_MANDATORY
,
3854 new base::FundamentalValue(false),
3856 provider_
.UpdateChromePolicy(policies
);
3860 IN_PROC_BROWSER_TEST_F(HardwareAccelerationModePolicyTest
,
3861 HardwareAccelerationDisabled
) {
3862 // Verifies that hardware acceleration can be disabled with policy.
3864 content::GpuDataManager::GetInstance()->GpuAccessAllowed(nullptr));
3866 #endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
3868 } // namespace policy